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.
 
 
 
 
 
 

11490 lines
286 KiB

  1. ;var MXI_DEBUG = true;
  2. /**
  3. * mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill
  4. * v1.5.2
  5. *
  6. * Copyright 2013, Moxiecode Systems AB
  7. * Released under GPL License.
  8. *
  9. * License: http://www.plupload.com/license
  10. * Contributing: http://www.plupload.com/contributing
  11. *
  12. * Date: 2016-11-23
  13. */
  14. ;(function (global, factory) {
  15. var extract = function() {
  16. var ctx = {};
  17. factory.apply(ctx, arguments);
  18. return ctx.moxie;
  19. };
  20. if (typeof define === "function" && define.amd) {
  21. define("moxie", [], extract);
  22. } else if (typeof module === "object" && module.exports) {
  23. module.exports = extract();
  24. } else {
  25. global.moxie = extract();
  26. }
  27. }(this || window, function() {
  28. /**
  29. * Compiled inline version. (Library mode)
  30. */
  31. /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
  32. /*globals $code */
  33. (function(exports, undefined) {
  34. "use strict";
  35. var modules = {};
  36. function require(ids, callback) {
  37. var module, defs = [];
  38. for (var i = 0; i < ids.length; ++i) {
  39. module = modules[ids[i]] || resolve(ids[i]);
  40. if (!module) {
  41. throw 'module definition dependecy not found: ' + ids[i];
  42. }
  43. defs.push(module);
  44. }
  45. callback.apply(null, defs);
  46. }
  47. function define(id, dependencies, definition) {
  48. if (typeof id !== 'string') {
  49. throw 'invalid module definition, module id must be defined and be a string';
  50. }
  51. if (dependencies === undefined) {
  52. throw 'invalid module definition, dependencies must be specified';
  53. }
  54. if (definition === undefined) {
  55. throw 'invalid module definition, definition function must be specified';
  56. }
  57. require(dependencies, function() {
  58. modules[id] = definition.apply(null, arguments);
  59. });
  60. }
  61. function defined(id) {
  62. return !!modules[id];
  63. }
  64. function resolve(id) {
  65. var target = exports;
  66. var fragments = id.split(/[.\/]/);
  67. for (var fi = 0; fi < fragments.length; ++fi) {
  68. if (!target[fragments[fi]]) {
  69. return;
  70. }
  71. target = target[fragments[fi]];
  72. }
  73. return target;
  74. }
  75. function expose(ids) {
  76. for (var i = 0; i < ids.length; i++) {
  77. var target = exports;
  78. var id = ids[i];
  79. var fragments = id.split(/[.\/]/);
  80. for (var fi = 0; fi < fragments.length - 1; ++fi) {
  81. if (target[fragments[fi]] === undefined) {
  82. target[fragments[fi]] = {};
  83. }
  84. target = target[fragments[fi]];
  85. }
  86. target[fragments[fragments.length - 1]] = modules[id];
  87. }
  88. }
  89. // Included from: src/javascript/core/utils/Basic.js
  90. /**
  91. * Basic.js
  92. *
  93. * Copyright 2013, Moxiecode Systems AB
  94. * Released under GPL License.
  95. *
  96. * License: http://www.plupload.com/license
  97. * Contributing: http://www.plupload.com/contributing
  98. */
  99. /**
  100. @class moxie/core/utils/Basic
  101. @public
  102. @static
  103. */
  104. define('moxie/core/utils/Basic', [], function() {
  105. /**
  106. Gets the true type of the built-in object (better version of typeof).
  107. @author Angus Croll (http://javascriptweblog.wordpress.com/)
  108. @method typeOf
  109. @for Utils
  110. @static
  111. @param {Object} o Object to check.
  112. @return {String} Object [[Class]]
  113. */
  114. function typeOf(o) {
  115. var undef;
  116. if (o === undef) {
  117. return 'undefined';
  118. } else if (o === null) {
  119. return 'null';
  120. } else if (o.nodeType) {
  121. return 'node';
  122. }
  123. // the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8
  124. return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
  125. }
  126. /**
  127. Extends the specified object with another object(s).
  128. @method extend
  129. @static
  130. @param {Object} target Object to extend.
  131. @param {Object} [obj]* Multiple objects to extend with.
  132. @return {Object} Same as target, the extended object.
  133. */
  134. function extend() {
  135. return merge(false, false, arguments);
  136. }
  137. /**
  138. Extends the specified object with another object(s), but only if the property exists in the target.
  139. @method extendIf
  140. @static
  141. @param {Object} target Object to extend.
  142. @param {Object} [obj]* Multiple objects to extend with.
  143. @return {Object} Same as target, the extended object.
  144. */
  145. function extendIf() {
  146. return merge(true, false, arguments);
  147. }
  148. function extendImmutable() {
  149. return merge(false, true, arguments);
  150. }
  151. function extendImmutableIf() {
  152. return merge(true, true, arguments);
  153. }
  154. function shallowCopy(obj) {
  155. switch (typeOf(obj)) {
  156. case 'array':
  157. return Array.prototype.slice.call(obj);
  158. case 'object':
  159. return extend({}, obj);
  160. }
  161. return obj;
  162. }
  163. function merge(strict, immutable, args) {
  164. var undef;
  165. var target = args[0];
  166. each(args, function(arg, i) {
  167. if (i > 0) {
  168. each(arg, function(value, key) {
  169. var isComplex = inArray(typeOf(value), ['array', 'object']) !== -1;
  170. if (value === undef || strict && target[key] === undef) {
  171. return true;
  172. }
  173. if (isComplex && immutable) {
  174. value = shallowCopy(value);
  175. }
  176. if (typeOf(target[key]) === typeOf(value) && isComplex) {
  177. merge(strict, immutable, [target[key], value]);
  178. } else {
  179. target[key] = value;
  180. }
  181. });
  182. }
  183. });
  184. return target;
  185. }
  186. /**
  187. A way to inherit one `class` from another in a consisstent way (more or less)
  188. @method inherit
  189. @static
  190. @since >1.4.1
  191. @param {Function} child
  192. @param {Function} parent
  193. @return {Function} Prepared constructor
  194. */
  195. function inherit(child, parent) {
  196. // copy over all parent properties
  197. for (var key in parent) {
  198. if ({}.hasOwnProperty.call(parent, key)) {
  199. child[key] = parent[key];
  200. }
  201. }
  202. // give child `class` a place to define its own methods
  203. function ctor() {
  204. this.constructor = child;
  205. }
  206. ctor.prototype = parent.prototype;
  207. child.prototype = new ctor();
  208. // keep a way to reference parent methods
  209. child.__parent__ = parent.prototype;
  210. return child;
  211. }
  212. /**
  213. Executes the callback function for each item in array/object. If you return false in the
  214. callback it will break the loop.
  215. @method each
  216. @static
  217. @param {Object} obj Object to iterate.
  218. @param {function} callback Callback function to execute for each item.
  219. */
  220. function each(obj, callback) {
  221. var length, key, i, undef;
  222. if (obj) {
  223. try {
  224. length = obj.length;
  225. } catch(ex) {
  226. length = undef;
  227. }
  228. if (length === undef || typeof(length) !== 'number') {
  229. // Loop object items
  230. for (key in obj) {
  231. if (obj.hasOwnProperty(key)) {
  232. if (callback(obj[key], key) === false) {
  233. return;
  234. }
  235. }
  236. }
  237. } else {
  238. // Loop array items
  239. for (i = 0; i < length; i++) {
  240. if (callback(obj[i], i) === false) {
  241. return;
  242. }
  243. }
  244. }
  245. }
  246. }
  247. /**
  248. Checks if object is empty.
  249. @method isEmptyObj
  250. @static
  251. @param {Object} o Object to check.
  252. @return {Boolean}
  253. */
  254. function isEmptyObj(obj) {
  255. var prop;
  256. if (!obj || typeOf(obj) !== 'object') {
  257. return true;
  258. }
  259. for (prop in obj) {
  260. return false;
  261. }
  262. return true;
  263. }
  264. /**
  265. Recieve an array of functions (usually async) to call in sequence, each function
  266. receives a callback as first argument that it should call, when it completes. Finally,
  267. after everything is complete, main callback is called. Passing truthy value to the
  268. callback as a first argument will interrupt the sequence and invoke main callback
  269. immediately.
  270. @method inSeries
  271. @static
  272. @param {Array} queue Array of functions to call in sequence
  273. @param {Function} cb Main callback that is called in the end, or in case of error
  274. */
  275. function inSeries(queue, cb) {
  276. var i = 0, length = queue.length;
  277. if (typeOf(cb) !== 'function') {
  278. cb = function() {};
  279. }
  280. if (!queue || !queue.length) {
  281. cb();
  282. }
  283. function callNext(i) {
  284. if (typeOf(queue[i]) === 'function') {
  285. queue[i](function(error) {
  286. /*jshint expr:true */
  287. ++i < length && !error ? callNext(i) : cb(error);
  288. });
  289. }
  290. }
  291. callNext(i);
  292. }
  293. /**
  294. Recieve an array of functions (usually async) to call in parallel, each function
  295. receives a callback as first argument that it should call, when it completes. After
  296. everything is complete, main callback is called. Passing truthy value to the
  297. callback as a first argument will interrupt the process and invoke main callback
  298. immediately.
  299. @method inParallel
  300. @static
  301. @param {Array} queue Array of functions to call in sequence
  302. @param {Function} cb Main callback that is called in the end, or in case of erro
  303. */
  304. function inParallel(queue, cb) {
  305. var count = 0, num = queue.length, cbArgs = new Array(num);
  306. each(queue, function(fn, i) {
  307. fn(function(error) {
  308. if (error) {
  309. return cb(error);
  310. }
  311. var args = [].slice.call(arguments);
  312. args.shift(); // strip error - undefined or not
  313. cbArgs[i] = args;
  314. count++;
  315. if (count === num) {
  316. cbArgs.unshift(null);
  317. cb.apply(this, cbArgs);
  318. }
  319. });
  320. });
  321. }
  322. /**
  323. Find an element in array and return it's index if present, otherwise return -1.
  324. @method inArray
  325. @static
  326. @param {Mixed} needle Element to find
  327. @param {Array} array
  328. @return {Int} Index of the element, or -1 if not found
  329. */
  330. function inArray(needle, array) {
  331. if (array) {
  332. if (Array.prototype.indexOf) {
  333. return Array.prototype.indexOf.call(array, needle);
  334. }
  335. for (var i = 0, length = array.length; i < length; i++) {
  336. if (array[i] === needle) {
  337. return i;
  338. }
  339. }
  340. }
  341. return -1;
  342. }
  343. /**
  344. Returns elements of first array if they are not present in second. And false - otherwise.
  345. @private
  346. @method arrayDiff
  347. @param {Array} needles
  348. @param {Array} array
  349. @return {Array|Boolean}
  350. */
  351. function arrayDiff(needles, array) {
  352. var diff = [];
  353. if (typeOf(needles) !== 'array') {
  354. needles = [needles];
  355. }
  356. if (typeOf(array) !== 'array') {
  357. array = [array];
  358. }
  359. for (var i in needles) {
  360. if (inArray(needles[i], array) === -1) {
  361. diff.push(needles[i]);
  362. }
  363. }
  364. return diff.length ? diff : false;
  365. }
  366. /**
  367. Find intersection of two arrays.
  368. @private
  369. @method arrayIntersect
  370. @param {Array} array1
  371. @param {Array} array2
  372. @return {Array} Intersection of two arrays or null if there is none
  373. */
  374. function arrayIntersect(array1, array2) {
  375. var result = [];
  376. each(array1, function(item) {
  377. if (inArray(item, array2) !== -1) {
  378. result.push(item);
  379. }
  380. });
  381. return result.length ? result : null;
  382. }
  383. /**
  384. Forces anything into an array.
  385. @method toArray
  386. @static
  387. @param {Object} obj Object with length field.
  388. @return {Array} Array object containing all items.
  389. */
  390. function toArray(obj) {
  391. var i, arr = [];
  392. for (i = 0; i < obj.length; i++) {
  393. arr[i] = obj[i];
  394. }
  395. return arr;
  396. }
  397. /**
  398. Generates an unique ID. The only way a user would be able to get the same ID is if the two persons
  399. at the same exact millisecond manage to get the same 5 random numbers between 0-65535; it also uses
  400. a counter so each ID is guaranteed to be unique for the given page. It is more probable for the earth
  401. to be hit with an asteroid.
  402. @method guid
  403. @static
  404. @param {String} prefix to prepend (by default 'o' will be prepended).
  405. @method guid
  406. @return {String} Virtually unique id.
  407. */
  408. var guid = (function() {
  409. var counter = 0;
  410. return function(prefix) {
  411. var guid = new Date().getTime().toString(32), i;
  412. for (i = 0; i < 5; i++) {
  413. guid += Math.floor(Math.random() * 65535).toString(32);
  414. }
  415. return (prefix || 'o_') + guid + (counter++).toString(32);
  416. };
  417. }());
  418. /**
  419. Trims white spaces around the string
  420. @method trim
  421. @static
  422. @param {String} str
  423. @return {String}
  424. */
  425. function trim(str) {
  426. if (!str) {
  427. return str;
  428. }
  429. return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, '');
  430. }
  431. /**
  432. Parses the specified size string into a byte value. For example 10kb becomes 10240.
  433. @method parseSizeStr
  434. @static
  435. @param {String/Number} size String to parse or number to just pass through.
  436. @return {Number} Size in bytes.
  437. */
  438. function parseSizeStr(size) {
  439. if (typeof(size) !== 'string') {
  440. return size;
  441. }
  442. var muls = {
  443. t: 1099511627776,
  444. g: 1073741824,
  445. m: 1048576,
  446. k: 1024
  447. },
  448. mul;
  449. size = /^([0-9\.]+)([tmgk]?)$/.exec(size.toLowerCase().replace(/[^0-9\.tmkg]/g, ''));
  450. mul = size[2];
  451. size = +size[1];
  452. if (muls.hasOwnProperty(mul)) {
  453. size *= muls[mul];
  454. }
  455. return Math.floor(size);
  456. }
  457. /**
  458. * Pseudo sprintf implementation - simple way to replace tokens with specified values.
  459. *
  460. * @param {String} str String with tokens
  461. * @return {String} String with replaced tokens
  462. */
  463. function sprintf(str) {
  464. var args = [].slice.call(arguments, 1);
  465. return str.replace(/%[a-z]/g, function() {
  466. var value = args.shift();
  467. return typeOf(value) !== 'undefined' ? value : '';
  468. });
  469. }
  470. function delay(cb, timeout) {
  471. var self = this;
  472. setTimeout(function() {
  473. cb.call(self);
  474. }, timeout || 1);
  475. }
  476. return {
  477. guid: guid,
  478. typeOf: typeOf,
  479. extend: extend,
  480. extendIf: extendIf,
  481. extendImmutable: extendImmutable,
  482. extendImmutableIf: extendImmutableIf,
  483. inherit: inherit,
  484. each: each,
  485. isEmptyObj: isEmptyObj,
  486. inSeries: inSeries,
  487. inParallel: inParallel,
  488. inArray: inArray,
  489. arrayDiff: arrayDiff,
  490. arrayIntersect: arrayIntersect,
  491. toArray: toArray,
  492. trim: trim,
  493. sprintf: sprintf,
  494. parseSizeStr: parseSizeStr,
  495. delay: delay
  496. };
  497. });
  498. // Included from: src/javascript/core/utils/Encode.js
  499. /**
  500. * Encode.js
  501. *
  502. * Copyright 2013, Moxiecode Systems AB
  503. * Released under GPL License.
  504. *
  505. * License: http://www.plupload.com/license
  506. * Contributing: http://www.plupload.com/contributing
  507. */
  508. define('moxie/core/utils/Encode', [], function() {
  509. /**
  510. @class moxie/core/utils/Encode
  511. */
  512. /**
  513. Encode string with UTF-8
  514. @method utf8_encode
  515. @for Utils
  516. @static
  517. @param {String} str String to encode
  518. @return {String} UTF-8 encoded string
  519. */
  520. var utf8_encode = function(str) {
  521. return unescape(encodeURIComponent(str));
  522. };
  523. /**
  524. Decode UTF-8 encoded string
  525. @method utf8_decode
  526. @static
  527. @param {String} str String to decode
  528. @return {String} Decoded string
  529. */
  530. var utf8_decode = function(str_data) {
  531. return decodeURIComponent(escape(str_data));
  532. };
  533. /**
  534. Decode Base64 encoded string (uses browser's default method if available),
  535. from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js
  536. @method atob
  537. @static
  538. @param {String} data String to decode
  539. @return {String} Decoded string
  540. */
  541. var atob = function(data, utf8) {
  542. if (typeof(window.atob) === 'function') {
  543. return utf8 ? utf8_decode(window.atob(data)) : window.atob(data);
  544. }
  545. // http://kevin.vanzonneveld.net
  546. // + original by: Tyler Akins (http://rumkin.com)
  547. // + improved by: Thunder.m
  548. // + input by: Aman Gupta
  549. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  550. // + bugfixed by: Onno Marsman
  551. // + bugfixed by: Pellentesque Malesuada
  552. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  553. // + input by: Brett Zamir (http://brett-zamir.me)
  554. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  555. // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  556. // * returns 1: 'Kevin van Zonneveld'
  557. // mozilla has this native
  558. // - but breaks in 2.0.0.12!
  559. //if (typeof this.window.atob == 'function') {
  560. // return atob(data);
  561. //}
  562. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  563. var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
  564. ac = 0,
  565. dec = "",
  566. tmp_arr = [];
  567. if (!data) {
  568. return data;
  569. }
  570. data += '';
  571. do { // unpack four hexets into three octets using index points in b64
  572. h1 = b64.indexOf(data.charAt(i++));
  573. h2 = b64.indexOf(data.charAt(i++));
  574. h3 = b64.indexOf(data.charAt(i++));
  575. h4 = b64.indexOf(data.charAt(i++));
  576. bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
  577. o1 = bits >> 16 & 0xff;
  578. o2 = bits >> 8 & 0xff;
  579. o3 = bits & 0xff;
  580. if (h3 == 64) {
  581. tmp_arr[ac++] = String.fromCharCode(o1);
  582. } else if (h4 == 64) {
  583. tmp_arr[ac++] = String.fromCharCode(o1, o2);
  584. } else {
  585. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  586. }
  587. } while (i < data.length);
  588. dec = tmp_arr.join('');
  589. return utf8 ? utf8_decode(dec) : dec;
  590. };
  591. /**
  592. Base64 encode string (uses browser's default method if available),
  593. from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js
  594. @method btoa
  595. @static
  596. @param {String} data String to encode
  597. @return {String} Base64 encoded string
  598. */
  599. var btoa = function(data, utf8) {
  600. if (utf8) {
  601. data = utf8_encode(data);
  602. }
  603. if (typeof(window.btoa) === 'function') {
  604. return window.btoa(data);
  605. }
  606. // http://kevin.vanzonneveld.net
  607. // + original by: Tyler Akins (http://rumkin.com)
  608. // + improved by: Bayron Guevara
  609. // + improved by: Thunder.m
  610. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  611. // + bugfixed by: Pellentesque Malesuada
  612. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  613. // + improved by: Rafał Kukawski (http://kukawski.pl)
  614. // * example 1: base64_encode('Kevin van Zonneveld');
  615. // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  616. // mozilla has this native
  617. // - but breaks in 2.0.0.12!
  618. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  619. var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
  620. ac = 0,
  621. enc = "",
  622. tmp_arr = [];
  623. if (!data) {
  624. return data;
  625. }
  626. do { // pack three octets into four hexets
  627. o1 = data.charCodeAt(i++);
  628. o2 = data.charCodeAt(i++);
  629. o3 = data.charCodeAt(i++);
  630. bits = o1 << 16 | o2 << 8 | o3;
  631. h1 = bits >> 18 & 0x3f;
  632. h2 = bits >> 12 & 0x3f;
  633. h3 = bits >> 6 & 0x3f;
  634. h4 = bits & 0x3f;
  635. // use hexets to index into b64, and append result to encoded string
  636. tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  637. } while (i < data.length);
  638. enc = tmp_arr.join('');
  639. var r = data.length % 3;
  640. return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
  641. };
  642. return {
  643. utf8_encode: utf8_encode,
  644. utf8_decode: utf8_decode,
  645. atob: atob,
  646. btoa: btoa
  647. };
  648. });
  649. // Included from: src/javascript/core/utils/Env.js
  650. /**
  651. * Env.js
  652. *
  653. * Copyright 2013, Moxiecode Systems AB
  654. * Released under GPL License.
  655. *
  656. * License: http://www.plupload.com/license
  657. * Contributing: http://www.plupload.com/contributing
  658. */
  659. define("moxie/core/utils/Env", [
  660. "moxie/core/utils/Basic"
  661. ], function(Basic) {
  662. /**
  663. * UAParser.js v0.7.7
  664. * Lightweight JavaScript-based User-Agent string parser
  665. * https://github.com/faisalman/ua-parser-js
  666. *
  667. * Copyright © 2012-2015 Faisal Salman <fyzlman@gmail.com>
  668. * Dual licensed under GPLv2 & MIT
  669. */
  670. var UAParser = (function (undefined) {
  671. //////////////
  672. // Constants
  673. /////////////
  674. var EMPTY = '',
  675. UNKNOWN = '?',
  676. FUNC_TYPE = 'function',
  677. UNDEF_TYPE = 'undefined',
  678. OBJ_TYPE = 'object',
  679. MAJOR = 'major',
  680. MODEL = 'model',
  681. NAME = 'name',
  682. TYPE = 'type',
  683. VENDOR = 'vendor',
  684. VERSION = 'version',
  685. ARCHITECTURE= 'architecture',
  686. CONSOLE = 'console',
  687. MOBILE = 'mobile',
  688. TABLET = 'tablet';
  689. ///////////
  690. // Helper
  691. //////////
  692. var util = {
  693. has : function (str1, str2) {
  694. return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1;
  695. },
  696. lowerize : function (str) {
  697. return str.toLowerCase();
  698. }
  699. };
  700. ///////////////
  701. // Map helper
  702. //////////////
  703. var mapper = {
  704. rgx : function () {
  705. // loop through all regexes maps
  706. for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) {
  707. var regex = args[i], // even sequence (0,2,4,..)
  708. props = args[i + 1]; // odd sequence (1,3,5,..)
  709. // construct object barebones
  710. if (typeof(result) === UNDEF_TYPE) {
  711. result = {};
  712. for (p in props) {
  713. q = props[p];
  714. if (typeof(q) === OBJ_TYPE) {
  715. result[q[0]] = undefined;
  716. } else {
  717. result[q] = undefined;
  718. }
  719. }
  720. }
  721. // try matching uastring with regexes
  722. for (j = k = 0; j < regex.length; j++) {
  723. matches = regex[j].exec(this.getUA());
  724. if (!!matches) {
  725. for (p = 0; p < props.length; p++) {
  726. match = matches[++k];
  727. q = props[p];
  728. // check if given property is actually array
  729. if (typeof(q) === OBJ_TYPE && q.length > 0) {
  730. if (q.length == 2) {
  731. if (typeof(q[1]) == FUNC_TYPE) {
  732. // assign modified match
  733. result[q[0]] = q[1].call(this, match);
  734. } else {
  735. // assign given value, ignore regex match
  736. result[q[0]] = q[1];
  737. }
  738. } else if (q.length == 3) {
  739. // check whether function or regex
  740. if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) {
  741. // call function (usually string mapper)
  742. result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
  743. } else {
  744. // sanitize match using given regex
  745. result[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
  746. }
  747. } else if (q.length == 4) {
  748. result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
  749. }
  750. } else {
  751. result[q] = match ? match : undefined;
  752. }
  753. }
  754. break;
  755. }
  756. }
  757. if(!!matches) break; // break the loop immediately if match found
  758. }
  759. return result;
  760. },
  761. str : function (str, map) {
  762. for (var i in map) {
  763. // check if array
  764. if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) {
  765. for (var j = 0; j < map[i].length; j++) {
  766. if (util.has(map[i][j], str)) {
  767. return (i === UNKNOWN) ? undefined : i;
  768. }
  769. }
  770. } else if (util.has(map[i], str)) {
  771. return (i === UNKNOWN) ? undefined : i;
  772. }
  773. }
  774. return str;
  775. }
  776. };
  777. ///////////////
  778. // String map
  779. //////////////
  780. var maps = {
  781. browser : {
  782. oldsafari : {
  783. major : {
  784. '1' : ['/8', '/1', '/3'],
  785. '2' : '/4',
  786. '?' : '/'
  787. },
  788. version : {
  789. '1.0' : '/8',
  790. '1.2' : '/1',
  791. '1.3' : '/3',
  792. '2.0' : '/412',
  793. '2.0.2' : '/416',
  794. '2.0.3' : '/417',
  795. '2.0.4' : '/419',
  796. '?' : '/'
  797. }
  798. }
  799. },
  800. device : {
  801. sprint : {
  802. model : {
  803. 'Evo Shift 4G' : '7373KT'
  804. },
  805. vendor : {
  806. 'HTC' : 'APA',
  807. 'Sprint' : 'Sprint'
  808. }
  809. }
  810. },
  811. os : {
  812. windows : {
  813. version : {
  814. 'ME' : '4.90',
  815. 'NT 3.11' : 'NT3.51',
  816. 'NT 4.0' : 'NT4.0',
  817. '2000' : 'NT 5.0',
  818. 'XP' : ['NT 5.1', 'NT 5.2'],
  819. 'Vista' : 'NT 6.0',
  820. '7' : 'NT 6.1',
  821. '8' : 'NT 6.2',
  822. '8.1' : 'NT 6.3',
  823. 'RT' : 'ARM'
  824. }
  825. }
  826. }
  827. };
  828. //////////////
  829. // Regex map
  830. /////////////
  831. var regexes = {
  832. browser : [[
  833. // Presto based
  834. /(opera\smini)\/([\w\.-]+)/i, // Opera Mini
  835. /(opera\s[mobiletab]+).+version\/([\w\.-]+)/i, // Opera Mobi/Tablet
  836. /(opera).+version\/([\w\.]+)/i, // Opera > 9.80
  837. /(opera)[\/\s]+([\w\.]+)/i // Opera < 9.80
  838. ], [NAME, VERSION], [
  839. /\s(opr)\/([\w\.]+)/i // Opera Webkit
  840. ], [[NAME, 'Opera'], VERSION], [
  841. // Mixed
  842. /(kindle)\/([\w\.]+)/i, // Kindle
  843. /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,
  844. // Lunascape/Maxthon/Netfront/Jasmine/Blazer
  845. // Trident based
  846. /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,
  847. // Avant/IEMobile/SlimBrowser/Baidu
  848. /(?:ms|\()(ie)\s([\w\.]+)/i, // Internet Explorer
  849. // Webkit/KHTML based
  850. /(rekonq)\/([\w\.]+)*/i, // Rekonq
  851. /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi)\/([\w\.-]+)/i
  852. // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron
  853. ], [NAME, VERSION], [
  854. /(trident).+rv[:\s]([\w\.]+).+like\sgecko/i // IE11
  855. ], [[NAME, 'IE'], VERSION], [
  856. /(edge)\/((\d+)?[\w\.]+)/i // Microsoft Edge
  857. ], [NAME, VERSION], [
  858. /(yabrowser)\/([\w\.]+)/i // Yandex
  859. ], [[NAME, 'Yandex'], VERSION], [
  860. /(comodo_dragon)\/([\w\.]+)/i // Comodo Dragon
  861. ], [[NAME, /_/g, ' '], VERSION], [
  862. /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i,
  863. // Chrome/OmniWeb/Arora/Tizen/Nokia
  864. /(uc\s?browser|qqbrowser)[\/\s]?([\w\.]+)/i
  865. // UCBrowser/QQBrowser
  866. ], [NAME, VERSION], [
  867. /(dolfin)\/([\w\.]+)/i // Dolphin
  868. ], [[NAME, 'Dolphin'], VERSION], [
  869. /((?:android.+)crmo|crios)\/([\w\.]+)/i // Chrome for Android/iOS
  870. ], [[NAME, 'Chrome'], VERSION], [
  871. /XiaoMi\/MiuiBrowser\/([\w\.]+)/i // MIUI Browser
  872. ], [VERSION, [NAME, 'MIUI Browser']], [
  873. /android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)/i // Android Browser
  874. ], [VERSION, [NAME, 'Android Browser']], [
  875. /FBAV\/([\w\.]+);/i // Facebook App for iOS
  876. ], [VERSION, [NAME, 'Facebook']], [
  877. /version\/([\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari
  878. ], [VERSION, [NAME, 'Mobile Safari']], [
  879. /version\/([\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile
  880. ], [VERSION, NAME], [
  881. /webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Safari < 3.0
  882. ], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [
  883. /(konqueror)\/([\w\.]+)/i, // Konqueror
  884. /(webkit|khtml)\/([\w\.]+)/i
  885. ], [NAME, VERSION], [
  886. // Gecko based
  887. /(navigator|netscape)\/([\w\.-]+)/i // Netscape
  888. ], [[NAME, 'Netscape'], VERSION], [
  889. /(swiftfox)/i, // Swiftfox
  890. /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,
  891. // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
  892. /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,
  893. // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
  894. /(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla
  895. // Other
  896. /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf)[\/\s]?([\w\.]+)/i,
  897. // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf
  898. /(links)\s\(([\w\.]+)/i, // Links
  899. /(gobrowser)\/?([\w\.]+)*/i, // GoBrowser
  900. /(ice\s?browser)\/v?([\w\._]+)/i, // ICE Browser
  901. /(mosaic)[\/\s]([\w\.]+)/i // Mosaic
  902. ], [NAME, VERSION]
  903. ],
  904. engine : [[
  905. /windows.+\sedge\/([\w\.]+)/i // EdgeHTML
  906. ], [VERSION, [NAME, 'EdgeHTML']], [
  907. /(presto)\/([\w\.]+)/i, // Presto
  908. /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m
  909. /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links
  910. /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab
  911. ], [NAME, VERSION], [
  912. /rv\:([\w\.]+).*(gecko)/i // Gecko
  913. ], [VERSION, NAME]
  914. ],
  915. os : [[
  916. // Windows based
  917. /microsoft\s(windows)\s(vista|xp)/i // Windows (iTunes)
  918. ], [NAME, VERSION], [
  919. /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT
  920. /(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i
  921. ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [
  922. /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
  923. ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [
  924. // Mobile/Embedded OS
  925. /\((bb)(10);/i // BlackBerry 10
  926. ], [[NAME, 'BlackBerry'], VERSION], [
  927. /(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry
  928. /(tizen)[\/\s]([\w\.]+)/i, // Tizen
  929. /(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,
  930. // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki
  931. /linux;.+(sailfish);/i // Sailfish OS
  932. ], [NAME, VERSION], [
  933. /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian
  934. ], [[NAME, 'Symbian'], VERSION], [
  935. /\((series40);/i // Series 40
  936. ], [NAME], [
  937. /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS
  938. ], [[NAME, 'Firefox OS'], VERSION], [
  939. // Console
  940. /(nintendo|playstation)\s([wids3portablevu]+)/i, // Nintendo/Playstation
  941. // GNU/Linux based
  942. /(mint)[\/\s\(]?(\w+)*/i, // Mint
  943. /(mageia|vectorlinux)[;\s]/i, // Mageia/VectorLinux
  944. /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?([\w\.-]+)*/i,
  945. // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
  946. // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus
  947. /(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux
  948. /(gnu)\s?([\w\.]+)*/i // GNU
  949. ], [NAME, VERSION], [
  950. /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS
  951. ], [[NAME, 'Chromium OS'], VERSION],[
  952. // Solaris
  953. /(sunos)\s?([\w\.]+\d)*/i // Solaris
  954. ], [[NAME, 'Solaris'], VERSION], [
  955. // BSD based
  956. /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
  957. ], [NAME, VERSION],[
  958. /(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i // iOS
  959. ], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [
  960. /(mac\sos\sx)\s?([\w\s\.]+\w)*/i,
  961. /(macintosh|mac(?=_powerpc)\s)/i // Mac OS
  962. ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [
  963. // Other
  964. /((?:open)?solaris)[\/\s-]?([\w\.]+)*/i, // Solaris
  965. /(haiku)\s(\w+)/i, // Haiku
  966. /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX
  967. /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,
  968. // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS
  969. /(unix)\s?([\w\.]+)*/i // UNIX
  970. ], [NAME, VERSION]
  971. ]
  972. };
  973. /////////////////
  974. // Constructor
  975. ////////////////
  976. var UAParser = function (uastring) {
  977. var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);
  978. this.getBrowser = function () {
  979. return mapper.rgx.apply(this, regexes.browser);
  980. };
  981. this.getEngine = function () {
  982. return mapper.rgx.apply(this, regexes.engine);
  983. };
  984. this.getOS = function () {
  985. return mapper.rgx.apply(this, regexes.os);
  986. };
  987. this.getResult = function() {
  988. return {
  989. ua : this.getUA(),
  990. browser : this.getBrowser(),
  991. engine : this.getEngine(),
  992. os : this.getOS()
  993. };
  994. };
  995. this.getUA = function () {
  996. return ua;
  997. };
  998. this.setUA = function (uastring) {
  999. ua = uastring;
  1000. return this;
  1001. };
  1002. this.setUA(ua);
  1003. };
  1004. return UAParser;
  1005. })();
  1006. function version_compare(v1, v2, operator) {
  1007. // From: http://phpjs.org/functions
  1008. // + original by: Philippe Jausions (http://pear.php.net/user/jausions)
  1009. // + original by: Aidan Lister (http://aidanlister.com/)
  1010. // + reimplemented by: Kankrelune (http://www.webfaktory.info/)
  1011. // + improved by: Brett Zamir (http://brett-zamir.me)
  1012. // + improved by: Scott Baker
  1013. // + improved by: Theriault
  1014. // * example 1: version_compare('8.2.5rc', '8.2.5a');
  1015. // * returns 1: 1
  1016. // * example 2: version_compare('8.2.50', '8.2.52', '<');
  1017. // * returns 2: true
  1018. // * example 3: version_compare('5.3.0-dev', '5.3.0');
  1019. // * returns 3: -1
  1020. // * example 4: version_compare('4.1.0.52','4.01.0.51');
  1021. // * returns 4: 1
  1022. // Important: compare must be initialized at 0.
  1023. var i = 0,
  1024. x = 0,
  1025. compare = 0,
  1026. // vm maps textual PHP versions to negatives so they're less than 0.
  1027. // PHP currently defines these as CASE-SENSITIVE. It is important to
  1028. // leave these as negatives so that they can come before numerical versions
  1029. // and as if no letters were there to begin with.
  1030. // (1alpha is < 1 and < 1.1 but > 1dev1)
  1031. // If a non-numerical value can't be mapped to this table, it receives
  1032. // -7 as its value.
  1033. vm = {
  1034. 'dev': -6,
  1035. 'alpha': -5,
  1036. 'a': -5,
  1037. 'beta': -4,
  1038. 'b': -4,
  1039. 'RC': -3,
  1040. 'rc': -3,
  1041. '#': -2,
  1042. 'p': 1,
  1043. 'pl': 1
  1044. },
  1045. // This function will be called to prepare each version argument.
  1046. // It replaces every _, -, and + with a dot.
  1047. // It surrounds any nonsequence of numbers/dots with dots.
  1048. // It replaces sequences of dots with a single dot.
  1049. // version_compare('4..0', '4.0') == 0
  1050. // Important: A string of 0 length needs to be converted into a value
  1051. // even less than an unexisting value in vm (-7), hence [-8].
  1052. // It's also important to not strip spaces because of this.
  1053. // version_compare('', ' ') == 1
  1054. prepVersion = function (v) {
  1055. v = ('' + v).replace(/[_\-+]/g, '.');
  1056. v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.');
  1057. return (!v.length ? [-8] : v.split('.'));
  1058. },
  1059. // This converts a version component to a number.
  1060. // Empty component becomes 0.
  1061. // Non-numerical component becomes a negative number.
  1062. // Numerical component becomes itself as an integer.
  1063. numVersion = function (v) {
  1064. return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10));
  1065. };
  1066. v1 = prepVersion(v1);
  1067. v2 = prepVersion(v2);
  1068. x = Math.max(v1.length, v2.length);
  1069. for (i = 0; i < x; i++) {
  1070. if (v1[i] == v2[i]) {
  1071. continue;
  1072. }
  1073. v1[i] = numVersion(v1[i]);
  1074. v2[i] = numVersion(v2[i]);
  1075. if (v1[i] < v2[i]) {
  1076. compare = -1;
  1077. break;
  1078. } else if (v1[i] > v2[i]) {
  1079. compare = 1;
  1080. break;
  1081. }
  1082. }
  1083. if (!operator) {
  1084. return compare;
  1085. }
  1086. // Important: operator is CASE-SENSITIVE.
  1087. // "No operator" seems to be treated as "<."
  1088. // Any other values seem to make the function return null.
  1089. switch (operator) {
  1090. case '>':
  1091. case 'gt':
  1092. return (compare > 0);
  1093. case '>=':
  1094. case 'ge':
  1095. return (compare >= 0);
  1096. case '<=':
  1097. case 'le':
  1098. return (compare <= 0);
  1099. case '==':
  1100. case '=':
  1101. case 'eq':
  1102. return (compare === 0);
  1103. case '<>':
  1104. case '!=':
  1105. case 'ne':
  1106. return (compare !== 0);
  1107. case '':
  1108. case '<':
  1109. case 'lt':
  1110. return (compare < 0);
  1111. default:
  1112. return null;
  1113. }
  1114. }
  1115. var can = (function() {
  1116. var caps = {
  1117. define_property: (function() {
  1118. /* // currently too much extra code required, not exactly worth it
  1119. try { // as of IE8, getters/setters are supported only on DOM elements
  1120. var obj = {};
  1121. if (Object.defineProperty) {
  1122. Object.defineProperty(obj, 'prop', {
  1123. enumerable: true,
  1124. configurable: true
  1125. });
  1126. return true;
  1127. }
  1128. } catch(ex) {}
  1129. if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) {
  1130. return true;
  1131. }*/
  1132. return false;
  1133. }()),
  1134. create_canvas: (function() {
  1135. // On the S60 and BB Storm, getContext exists, but always returns undefined
  1136. // so we actually have to call getContext() to verify
  1137. // github.com/Modernizr/Modernizr/issues/issue/97/
  1138. var el = document.createElement('canvas');
  1139. return !!(el.getContext && el.getContext('2d'));
  1140. }()),
  1141. return_response_type: function(responseType) {
  1142. try {
  1143. if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) {
  1144. return true;
  1145. } else if (window.XMLHttpRequest) {
  1146. var xhr = new XMLHttpRequest();
  1147. xhr.open('get', '/'); // otherwise Gecko throws an exception
  1148. if ('responseType' in xhr) {
  1149. xhr.responseType = responseType;
  1150. // as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?)
  1151. if (xhr.responseType !== responseType) {
  1152. return false;
  1153. }
  1154. return true;
  1155. }
  1156. }
  1157. } catch (ex) {}
  1158. return false;
  1159. },
  1160. // ideas for this heavily come from Modernizr (http://modernizr.com/)
  1161. use_data_uri: (function() {
  1162. var du = new Image();
  1163. du.onload = function() {
  1164. caps.use_data_uri = (du.width === 1 && du.height === 1);
  1165. };
  1166. setTimeout(function() {
  1167. du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==";
  1168. }, 1);
  1169. return false;
  1170. }()),
  1171. use_data_uri_over32kb: function() { // IE8
  1172. return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9);
  1173. },
  1174. use_data_uri_of: function(bytes) {
  1175. return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb());
  1176. },
  1177. use_fileinput: function() {
  1178. if (navigator.userAgent.match(/(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0))|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|(Kindle\/(1.0|2.0|2.5|3.0))/)) {
  1179. return false;
  1180. }
  1181. var el = document.createElement('input');
  1182. el.setAttribute('type', 'file');
  1183. return !el.disabled;
  1184. }
  1185. };
  1186. return function(cap) {
  1187. var args = [].slice.call(arguments);
  1188. args.shift(); // shift of cap
  1189. return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap];
  1190. };
  1191. }());
  1192. var uaResult = new UAParser().getResult();
  1193. var Env = {
  1194. can: can,
  1195. uaParser: UAParser,
  1196. browser: uaResult.browser.name,
  1197. version: uaResult.browser.version,
  1198. os: uaResult.os.name, // everybody intuitively types it in a lowercase for some reason
  1199. osVersion: uaResult.os.version,
  1200. verComp: version_compare,
  1201. swf_url: "../flash/Moxie.swf",
  1202. xap_url: "../silverlight/Moxie.xap",
  1203. global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent"
  1204. };
  1205. // for backward compatibility
  1206. // @deprecated Use `Env.os` instead
  1207. Env.OS = Env.os;
  1208. if (MXI_DEBUG) {
  1209. Env.debug = {
  1210. runtime: true,
  1211. events: false
  1212. };
  1213. Env.log = function() {
  1214. function logObj(data) {
  1215. // TODO: this should recursively print out the object in a pretty way
  1216. console.appendChild(document.createTextNode(data + "\n"));
  1217. }
  1218. var data = arguments[0];
  1219. if (Basic.typeOf(data) === 'string') {
  1220. data = Basic.sprintf.apply(this, arguments);
  1221. }
  1222. if (window && window.console && window.console.log) {
  1223. window.console.log(data);
  1224. } else if (document) {
  1225. var console = document.getElementById('moxie-console');
  1226. if (!console) {
  1227. console = document.createElement('pre');
  1228. console.id = 'moxie-console';
  1229. //console.style.display = 'none';
  1230. document.body.appendChild(console);
  1231. }
  1232. if (Basic.inArray(Basic.typeOf(data), ['object', 'array']) !== -1) {
  1233. logObj(data);
  1234. } else {
  1235. console.appendChild(document.createTextNode(data + "\n"));
  1236. }
  1237. }
  1238. };
  1239. }
  1240. return Env;
  1241. });
  1242. // Included from: src/javascript/core/Exceptions.js
  1243. /**
  1244. * Exceptions.js
  1245. *
  1246. * Copyright 2013, Moxiecode Systems AB
  1247. * Released under GPL License.
  1248. *
  1249. * License: http://www.plupload.com/license
  1250. * Contributing: http://www.plupload.com/contributing
  1251. */
  1252. define('moxie/core/Exceptions', [
  1253. 'moxie/core/utils/Basic'
  1254. ], function(Basic) {
  1255. function _findKey(obj, value) {
  1256. var key;
  1257. for (key in obj) {
  1258. if (obj[key] === value) {
  1259. return key;
  1260. }
  1261. }
  1262. return null;
  1263. }
  1264. /**
  1265. @class moxie/core/Exception
  1266. */
  1267. return {
  1268. RuntimeError: (function() {
  1269. var namecodes = {
  1270. NOT_INIT_ERR: 1,
  1271. EXCEPTION_ERR: 3,
  1272. NOT_SUPPORTED_ERR: 9,
  1273. JS_ERR: 4
  1274. };
  1275. function RuntimeError(code, message) {
  1276. this.code = code;
  1277. this.name = _findKey(namecodes, code);
  1278. this.message = this.name + (message || ": RuntimeError " + this.code);
  1279. }
  1280. Basic.extend(RuntimeError, namecodes);
  1281. RuntimeError.prototype = Error.prototype;
  1282. return RuntimeError;
  1283. }()),
  1284. OperationNotAllowedException: (function() {
  1285. function OperationNotAllowedException(code) {
  1286. this.code = code;
  1287. this.name = 'OperationNotAllowedException';
  1288. }
  1289. Basic.extend(OperationNotAllowedException, {
  1290. NOT_ALLOWED_ERR: 1
  1291. });
  1292. OperationNotAllowedException.prototype = Error.prototype;
  1293. return OperationNotAllowedException;
  1294. }()),
  1295. ImageError: (function() {
  1296. var namecodes = {
  1297. WRONG_FORMAT: 1,
  1298. MAX_RESOLUTION_ERR: 2,
  1299. INVALID_META_ERR: 3
  1300. };
  1301. function ImageError(code) {
  1302. this.code = code;
  1303. this.name = _findKey(namecodes, code);
  1304. this.message = this.name + ": ImageError " + this.code;
  1305. }
  1306. Basic.extend(ImageError, namecodes);
  1307. ImageError.prototype = Error.prototype;
  1308. return ImageError;
  1309. }()),
  1310. FileException: (function() {
  1311. var namecodes = {
  1312. NOT_FOUND_ERR: 1,
  1313. SECURITY_ERR: 2,
  1314. ABORT_ERR: 3,
  1315. NOT_READABLE_ERR: 4,
  1316. ENCODING_ERR: 5,
  1317. NO_MODIFICATION_ALLOWED_ERR: 6,
  1318. INVALID_STATE_ERR: 7,
  1319. SYNTAX_ERR: 8
  1320. };
  1321. function FileException(code) {
  1322. this.code = code;
  1323. this.name = _findKey(namecodes, code);
  1324. this.message = this.name + ": FileException " + this.code;
  1325. }
  1326. Basic.extend(FileException, namecodes);
  1327. FileException.prototype = Error.prototype;
  1328. return FileException;
  1329. }()),
  1330. DOMException: (function() {
  1331. var namecodes = {
  1332. INDEX_SIZE_ERR: 1,
  1333. DOMSTRING_SIZE_ERR: 2,
  1334. HIERARCHY_REQUEST_ERR: 3,
  1335. WRONG_DOCUMENT_ERR: 4,
  1336. INVALID_CHARACTER_ERR: 5,
  1337. NO_DATA_ALLOWED_ERR: 6,
  1338. NO_MODIFICATION_ALLOWED_ERR: 7,
  1339. NOT_FOUND_ERR: 8,
  1340. NOT_SUPPORTED_ERR: 9,
  1341. INUSE_ATTRIBUTE_ERR: 10,
  1342. INVALID_STATE_ERR: 11,
  1343. SYNTAX_ERR: 12,
  1344. INVALID_MODIFICATION_ERR: 13,
  1345. NAMESPACE_ERR: 14,
  1346. INVALID_ACCESS_ERR: 15,
  1347. VALIDATION_ERR: 16,
  1348. TYPE_MISMATCH_ERR: 17,
  1349. SECURITY_ERR: 18,
  1350. NETWORK_ERR: 19,
  1351. ABORT_ERR: 20,
  1352. URL_MISMATCH_ERR: 21,
  1353. QUOTA_EXCEEDED_ERR: 22,
  1354. TIMEOUT_ERR: 23,
  1355. INVALID_NODE_TYPE_ERR: 24,
  1356. DATA_CLONE_ERR: 25
  1357. };
  1358. function DOMException(code) {
  1359. this.code = code;
  1360. this.name = _findKey(namecodes, code);
  1361. this.message = this.name + ": DOMException " + this.code;
  1362. }
  1363. Basic.extend(DOMException, namecodes);
  1364. DOMException.prototype = Error.prototype;
  1365. return DOMException;
  1366. }()),
  1367. EventException: (function() {
  1368. function EventException(code) {
  1369. this.code = code;
  1370. this.name = 'EventException';
  1371. }
  1372. Basic.extend(EventException, {
  1373. UNSPECIFIED_EVENT_TYPE_ERR: 0
  1374. });
  1375. EventException.prototype = Error.prototype;
  1376. return EventException;
  1377. }())
  1378. };
  1379. });
  1380. // Included from: src/javascript/core/utils/Dom.js
  1381. /**
  1382. * Dom.js
  1383. *
  1384. * Copyright 2013, Moxiecode Systems AB
  1385. * Released under GPL License.
  1386. *
  1387. * License: http://www.plupload.com/license
  1388. * Contributing: http://www.plupload.com/contributing
  1389. */
  1390. define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) {
  1391. /**
  1392. Get DOM Element by it's id.
  1393. @method get
  1394. @for Utils
  1395. @param {String} id Identifier of the DOM Element
  1396. @return {DOMElement}
  1397. */
  1398. var get = function(id) {
  1399. if (typeof id !== 'string') {
  1400. return id;
  1401. }
  1402. return document.getElementById(id);
  1403. };
  1404. /**
  1405. Checks if specified DOM element has specified class.
  1406. @method hasClass
  1407. @static
  1408. @param {Object} obj DOM element like object to add handler to.
  1409. @param {String} name Class name
  1410. */
  1411. var hasClass = function(obj, name) {
  1412. if (!obj.className) {
  1413. return false;
  1414. }
  1415. var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
  1416. return regExp.test(obj.className);
  1417. };
  1418. /**
  1419. Adds specified className to specified DOM element.
  1420. @method addClass
  1421. @static
  1422. @param {Object} obj DOM element like object to add handler to.
  1423. @param {String} name Class name
  1424. */
  1425. var addClass = function(obj, name) {
  1426. if (!hasClass(obj, name)) {
  1427. obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name;
  1428. }
  1429. };
  1430. /**
  1431. Removes specified className from specified DOM element.
  1432. @method removeClass
  1433. @static
  1434. @param {Object} obj DOM element like object to add handler to.
  1435. @param {String} name Class name
  1436. */
  1437. var removeClass = function(obj, name) {
  1438. if (obj.className) {
  1439. var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
  1440. obj.className = obj.className.replace(regExp, function($0, $1, $2) {
  1441. return $1 === ' ' && $2 === ' ' ? ' ' : '';
  1442. });
  1443. }
  1444. };
  1445. /**
  1446. Returns a given computed style of a DOM element.
  1447. @method getStyle
  1448. @static
  1449. @param {Object} obj DOM element like object.
  1450. @param {String} name Style you want to get from the DOM element
  1451. */
  1452. var getStyle = function(obj, name) {
  1453. if (obj.currentStyle) {
  1454. return obj.currentStyle[name];
  1455. } else if (window.getComputedStyle) {
  1456. return window.getComputedStyle(obj, null)[name];
  1457. }
  1458. };
  1459. /**
  1460. Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields.
  1461. @method getPos
  1462. @static
  1463. @param {Element} node HTML element or element id to get x, y position from.
  1464. @param {Element} root Optional root element to stop calculations at.
  1465. @return {object} Absolute position of the specified element object with x, y fields.
  1466. */
  1467. var getPos = function(node, root) {
  1468. var x = 0, y = 0, parent, doc = document, nodeRect, rootRect;
  1469. node = node;
  1470. root = root || doc.body;
  1471. // Returns the x, y cordinate for an element on IE 6 and IE 7
  1472. function getIEPos(node) {
  1473. var bodyElm, rect, x = 0, y = 0;
  1474. if (node) {
  1475. rect = node.getBoundingClientRect();
  1476. bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body;
  1477. x = rect.left + bodyElm.scrollLeft;
  1478. y = rect.top + bodyElm.scrollTop;
  1479. }
  1480. return {
  1481. x : x,
  1482. y : y
  1483. };
  1484. }
  1485. // Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode
  1486. if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) {
  1487. nodeRect = getIEPos(node);
  1488. rootRect = getIEPos(root);
  1489. return {
  1490. x : nodeRect.x - rootRect.x,
  1491. y : nodeRect.y - rootRect.y
  1492. };
  1493. }
  1494. parent = node;
  1495. while (parent && parent != root && parent.nodeType) {
  1496. x += parent.offsetLeft || 0;
  1497. y += parent.offsetTop || 0;
  1498. parent = parent.offsetParent;
  1499. }
  1500. parent = node.parentNode;
  1501. while (parent && parent != root && parent.nodeType) {
  1502. x -= parent.scrollLeft || 0;
  1503. y -= parent.scrollTop || 0;
  1504. parent = parent.parentNode;
  1505. }
  1506. return {
  1507. x : x,
  1508. y : y
  1509. };
  1510. };
  1511. /**
  1512. Returns the size of the specified node in pixels.
  1513. @method getSize
  1514. @static
  1515. @param {Node} node Node to get the size of.
  1516. @return {Object} Object with a w and h property.
  1517. */
  1518. var getSize = function(node) {
  1519. return {
  1520. w : node.offsetWidth || node.clientWidth,
  1521. h : node.offsetHeight || node.clientHeight
  1522. };
  1523. };
  1524. return {
  1525. get: get,
  1526. hasClass: hasClass,
  1527. addClass: addClass,
  1528. removeClass: removeClass,
  1529. getStyle: getStyle,
  1530. getPos: getPos,
  1531. getSize: getSize
  1532. };
  1533. });
  1534. // Included from: src/javascript/core/EventTarget.js
  1535. /**
  1536. * EventTarget.js
  1537. *
  1538. * Copyright 2013, Moxiecode Systems AB
  1539. * Released under GPL License.
  1540. *
  1541. * License: http://www.plupload.com/license
  1542. * Contributing: http://www.plupload.com/contributing
  1543. */
  1544. define('moxie/core/EventTarget', [
  1545. 'moxie/core/utils/Env',
  1546. 'moxie/core/Exceptions',
  1547. 'moxie/core/utils/Basic'
  1548. ], function(Env, x, Basic) {
  1549. // hash of event listeners by object uid
  1550. var eventpool = {};
  1551. /**
  1552. Parent object for all event dispatching components and objects
  1553. @class moxie/core/EventTarget
  1554. @constructor EventTarget
  1555. */
  1556. function EventTarget() {
  1557. /**
  1558. Unique id of the event dispatcher, usually overriden by children
  1559. @property uid
  1560. @type String
  1561. */
  1562. this.uid = Basic.guid();
  1563. }
  1564. Basic.extend(EventTarget.prototype, {
  1565. /**
  1566. Can be called from within a child in order to acquire uniqie id in automated manner
  1567. @method init
  1568. */
  1569. init: function() {
  1570. if (!this.uid) {
  1571. this.uid = Basic.guid('uid_');
  1572. }
  1573. },
  1574. /**
  1575. Register a handler to a specific event dispatched by the object
  1576. @method addEventListener
  1577. @param {String} type Type or basically a name of the event to subscribe to
  1578. @param {Function} fn Callback function that will be called when event happens
  1579. @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first
  1580. @param {Object} [scope=this] A scope to invoke event handler in
  1581. */
  1582. addEventListener: function(type, fn, priority, scope) {
  1583. var self = this, list;
  1584. // without uid no event handlers can be added, so make sure we got one
  1585. if (!this.hasOwnProperty('uid')) {
  1586. this.uid = Basic.guid('uid_');
  1587. }
  1588. type = Basic.trim(type);
  1589. if (/\s/.test(type)) {
  1590. // multiple event types were passed for one handler
  1591. Basic.each(type.split(/\s+/), function(type) {
  1592. self.addEventListener(type, fn, priority, scope);
  1593. });
  1594. return;
  1595. }
  1596. type = type.toLowerCase();
  1597. priority = parseInt(priority, 10) || 0;
  1598. list = eventpool[this.uid] && eventpool[this.uid][type] || [];
  1599. list.push({fn : fn, priority : priority, scope : scope || this});
  1600. if (!eventpool[this.uid]) {
  1601. eventpool[this.uid] = {};
  1602. }
  1603. eventpool[this.uid][type] = list;
  1604. },
  1605. /**
  1606. Check if any handlers were registered to the specified event
  1607. @method hasEventListener
  1608. @param {String} [type] Type or basically a name of the event to check
  1609. @return {Mixed} Returns a handler if it was found and false, if - not
  1610. */
  1611. hasEventListener: function(type) {
  1612. var list;
  1613. if (type) {
  1614. type = type.toLowerCase();
  1615. list = eventpool[this.uid] && eventpool[this.uid][type];
  1616. } else {
  1617. list = eventpool[this.uid];
  1618. }
  1619. return list ? list : false;
  1620. },
  1621. /**
  1622. Unregister the handler from the event, or if former was not specified - unregister all handlers
  1623. @method removeEventListener
  1624. @param {String} type Type or basically a name of the event
  1625. @param {Function} [fn] Handler to unregister
  1626. */
  1627. removeEventListener: function(type, fn) {
  1628. var self = this, list, i;
  1629. type = type.toLowerCase();
  1630. if (/\s/.test(type)) {
  1631. // multiple event types were passed for one handler
  1632. Basic.each(type.split(/\s+/), function(type) {
  1633. self.removeEventListener(type, fn);
  1634. });
  1635. return;
  1636. }
  1637. list = eventpool[this.uid] && eventpool[this.uid][type];
  1638. if (list) {
  1639. if (fn) {
  1640. for (i = list.length - 1; i >= 0; i--) {
  1641. if (list[i].fn === fn) {
  1642. list.splice(i, 1);
  1643. break;
  1644. }
  1645. }
  1646. } else {
  1647. list = [];
  1648. }
  1649. // delete event list if it has become empty
  1650. if (!list.length) {
  1651. delete eventpool[this.uid][type];
  1652. // and object specific entry in a hash if it has no more listeners attached
  1653. if (Basic.isEmptyObj(eventpool[this.uid])) {
  1654. delete eventpool[this.uid];
  1655. }
  1656. }
  1657. }
  1658. },
  1659. /**
  1660. Remove all event handlers from the object
  1661. @method removeAllEventListeners
  1662. */
  1663. removeAllEventListeners: function() {
  1664. if (eventpool[this.uid]) {
  1665. delete eventpool[this.uid];
  1666. }
  1667. },
  1668. /**
  1669. Dispatch the event
  1670. @method dispatchEvent
  1671. @param {String/Object} Type of event or event object to dispatch
  1672. @param {Mixed} [...] Variable number of arguments to be passed to a handlers
  1673. @return {Boolean} true by default and false if any handler returned false
  1674. */
  1675. dispatchEvent: function(type) {
  1676. var uid, list, args, tmpEvt, evt = {}, result = true, undef;
  1677. if (Basic.typeOf(type) !== 'string') {
  1678. // we can't use original object directly (because of Silverlight)
  1679. tmpEvt = type;
  1680. if (Basic.typeOf(tmpEvt.type) === 'string') {
  1681. type = tmpEvt.type;
  1682. if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event
  1683. evt.total = tmpEvt.total;
  1684. evt.loaded = tmpEvt.loaded;
  1685. }
  1686. evt.async = tmpEvt.async || false;
  1687. } else {
  1688. throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR);
  1689. }
  1690. }
  1691. // check if event is meant to be dispatched on an object having specific uid
  1692. if (type.indexOf('::') !== -1) {
  1693. (function(arr) {
  1694. uid = arr[0];
  1695. type = arr[1];
  1696. }(type.split('::')));
  1697. } else {
  1698. uid = this.uid;
  1699. }
  1700. type = type.toLowerCase();
  1701. list = eventpool[uid] && eventpool[uid][type];
  1702. if (list) {
  1703. // sort event list by prority
  1704. list.sort(function(a, b) { return b.priority - a.priority; });
  1705. args = [].slice.call(arguments);
  1706. // first argument will be pseudo-event object
  1707. args.shift();
  1708. evt.type = type;
  1709. args.unshift(evt);
  1710. if (MXI_DEBUG && Env.debug.events) {
  1711. Env.log("Event '%s' fired on %u", evt.type, uid);
  1712. }
  1713. // Dispatch event to all listeners
  1714. var queue = [];
  1715. Basic.each(list, function(handler) {
  1716. // explicitly set the target, otherwise events fired from shims do not get it
  1717. args[0].target = handler.scope;
  1718. // if event is marked as async, detach the handler
  1719. if (evt.async) {
  1720. queue.push(function(cb) {
  1721. setTimeout(function() {
  1722. cb(handler.fn.apply(handler.scope, args) === false);
  1723. }, 1);
  1724. });
  1725. } else {
  1726. queue.push(function(cb) {
  1727. cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation
  1728. });
  1729. }
  1730. });
  1731. if (queue.length) {
  1732. Basic.inSeries(queue, function(err) {
  1733. result = !err;
  1734. });
  1735. }
  1736. }
  1737. return result;
  1738. },
  1739. /**
  1740. Register a handler to the event type that will run only once
  1741. @method bindOnce
  1742. @since >1.4.1
  1743. @param {String} type Type or basically a name of the event to subscribe to
  1744. @param {Function} fn Callback function that will be called when event happens
  1745. @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first
  1746. @param {Object} [scope=this] A scope to invoke event handler in
  1747. */
  1748. bindOnce: function(type, fn, priority, scope) {
  1749. var self = this;
  1750. self.bind.call(this, type, function cb() {
  1751. self.unbind(type, cb);
  1752. return fn.apply(this, arguments);
  1753. }, priority, scope);
  1754. },
  1755. /**
  1756. Alias for addEventListener
  1757. @method bind
  1758. @protected
  1759. */
  1760. bind: function() {
  1761. this.addEventListener.apply(this, arguments);
  1762. },
  1763. /**
  1764. Alias for removeEventListener
  1765. @method unbind
  1766. @protected
  1767. */
  1768. unbind: function() {
  1769. this.removeEventListener.apply(this, arguments);
  1770. },
  1771. /**
  1772. Alias for removeAllEventListeners
  1773. @method unbindAll
  1774. @protected
  1775. */
  1776. unbindAll: function() {
  1777. this.removeAllEventListeners.apply(this, arguments);
  1778. },
  1779. /**
  1780. Alias for dispatchEvent
  1781. @method trigger
  1782. @protected
  1783. */
  1784. trigger: function() {
  1785. return this.dispatchEvent.apply(this, arguments);
  1786. },
  1787. /**
  1788. Handle properties of on[event] type.
  1789. @method handleEventProps
  1790. @private
  1791. */
  1792. handleEventProps: function(dispatches) {
  1793. var self = this;
  1794. this.bind(dispatches.join(' '), function(e) {
  1795. var prop = 'on' + e.type.toLowerCase();
  1796. if (Basic.typeOf(this[prop]) === 'function') {
  1797. this[prop].apply(this, arguments);
  1798. }
  1799. });
  1800. // object must have defined event properties, even if it doesn't make use of them
  1801. Basic.each(dispatches, function(prop) {
  1802. prop = 'on' + prop.toLowerCase(prop);
  1803. if (Basic.typeOf(self[prop]) === 'undefined') {
  1804. self[prop] = null;
  1805. }
  1806. });
  1807. }
  1808. });
  1809. EventTarget.instance = new EventTarget();
  1810. return EventTarget;
  1811. });
  1812. // Included from: src/javascript/runtime/Runtime.js
  1813. /**
  1814. * Runtime.js
  1815. *
  1816. * Copyright 2013, Moxiecode Systems AB
  1817. * Released under GPL License.
  1818. *
  1819. * License: http://www.plupload.com/license
  1820. * Contributing: http://www.plupload.com/contributing
  1821. */
  1822. define('moxie/runtime/Runtime', [
  1823. "moxie/core/utils/Env",
  1824. "moxie/core/utils/Basic",
  1825. "moxie/core/utils/Dom",
  1826. "moxie/core/EventTarget"
  1827. ], function(Env, Basic, Dom, EventTarget) {
  1828. var runtimeConstructors = {}, runtimes = {};
  1829. /**
  1830. Common set of methods and properties for every runtime instance
  1831. @class moxie/runtime/Runtime
  1832. @param {Object} options
  1833. @param {String} type Sanitized name of the runtime
  1834. @param {Object} [caps] Set of capabilities that differentiate specified runtime
  1835. @param {Object} [modeCaps] Set of capabilities that do require specific operational mode
  1836. @param {String} [preferredMode='browser'] Preferred operational mode to choose if no required capabilities were requested
  1837. */
  1838. function Runtime(options, type, caps, modeCaps, preferredMode) {
  1839. /**
  1840. Dispatched when runtime is initialized and ready.
  1841. Results in RuntimeInit on a connected component.
  1842. @event Init
  1843. */
  1844. /**
  1845. Dispatched when runtime fails to initialize.
  1846. Results in RuntimeError on a connected component.
  1847. @event Error
  1848. */
  1849. var self = this
  1850. , _shim
  1851. , _uid = Basic.guid(type + '_')
  1852. , defaultMode = preferredMode || 'browser'
  1853. ;
  1854. options = options || {};
  1855. // register runtime in private hash
  1856. runtimes[_uid] = this;
  1857. /**
  1858. Default set of capabilities, which can be redifined later by specific runtime
  1859. @private
  1860. @property caps
  1861. @type Object
  1862. */
  1863. caps = Basic.extend({
  1864. // Runtime can:
  1865. // provide access to raw binary data of the file
  1866. access_binary: false,
  1867. // provide access to raw binary data of the image (image extension is optional)
  1868. access_image_binary: false,
  1869. // display binary data as thumbs for example
  1870. display_media: false,
  1871. // make cross-domain requests
  1872. do_cors: false,
  1873. // accept files dragged and dropped from the desktop
  1874. drag_and_drop: false,
  1875. // filter files in selection dialog by their extensions
  1876. filter_by_extension: true,
  1877. // resize image (and manipulate it raw data of any file in general)
  1878. resize_image: false,
  1879. // periodically report how many bytes of total in the file were uploaded (loaded)
  1880. report_upload_progress: false,
  1881. // provide access to the headers of http response
  1882. return_response_headers: false,
  1883. // support response of specific type, which should be passed as an argument
  1884. // e.g. runtime.can('return_response_type', 'blob')
  1885. return_response_type: false,
  1886. // return http status code of the response
  1887. return_status_code: true,
  1888. // send custom http header with the request
  1889. send_custom_headers: false,
  1890. // pick up the files from a dialog
  1891. select_file: false,
  1892. // select whole folder in file browse dialog
  1893. select_folder: false,
  1894. // select multiple files at once in file browse dialog
  1895. select_multiple: true,
  1896. // send raw binary data, that is generated after image resizing or manipulation of other kind
  1897. send_binary_string: false,
  1898. // send cookies with http request and therefore retain session
  1899. send_browser_cookies: true,
  1900. // send data formatted as multipart/form-data
  1901. send_multipart: true,
  1902. // slice the file or blob to smaller parts
  1903. slice_blob: false,
  1904. // upload file without preloading it to memory, stream it out directly from disk
  1905. stream_upload: false,
  1906. // programmatically trigger file browse dialog
  1907. summon_file_dialog: false,
  1908. // upload file of specific size, size should be passed as argument
  1909. // e.g. runtime.can('upload_filesize', '500mb')
  1910. upload_filesize: true,
  1911. // initiate http request with specific http method, method should be passed as argument
  1912. // e.g. runtime.can('use_http_method', 'put')
  1913. use_http_method: true
  1914. }, caps);
  1915. // default to the mode that is compatible with preferred caps
  1916. if (options.preferred_caps) {
  1917. defaultMode = Runtime.getMode(modeCaps, options.preferred_caps, defaultMode);
  1918. }
  1919. if (MXI_DEBUG && Env.debug.runtime) {
  1920. Env.log("\tdefault mode: %s", defaultMode);
  1921. }
  1922. // small extension factory here (is meant to be extended with actual extensions constructors)
  1923. _shim = (function() {
  1924. var objpool = {};
  1925. return {
  1926. exec: function(uid, comp, fn, args) {
  1927. if (_shim[comp]) {
  1928. if (!objpool[uid]) {
  1929. objpool[uid] = {
  1930. context: this,
  1931. instance: new _shim[comp]()
  1932. };
  1933. }
  1934. if (objpool[uid].instance[fn]) {
  1935. return objpool[uid].instance[fn].apply(this, args);
  1936. }
  1937. }
  1938. },
  1939. removeInstance: function(uid) {
  1940. delete objpool[uid];
  1941. },
  1942. removeAllInstances: function() {
  1943. var self = this;
  1944. Basic.each(objpool, function(obj, uid) {
  1945. if (Basic.typeOf(obj.instance.destroy) === 'function') {
  1946. obj.instance.destroy.call(obj.context);
  1947. }
  1948. self.removeInstance(uid);
  1949. });
  1950. }
  1951. };
  1952. }());
  1953. // public methods
  1954. Basic.extend(this, {
  1955. /**
  1956. Specifies whether runtime instance was initialized or not
  1957. @property initialized
  1958. @type {Boolean}
  1959. @default false
  1960. */
  1961. initialized: false, // shims require this flag to stop initialization retries
  1962. /**
  1963. Unique ID of the runtime
  1964. @property uid
  1965. @type {String}
  1966. */
  1967. uid: _uid,
  1968. /**
  1969. Runtime type (e.g. flash, html5, etc)
  1970. @property type
  1971. @type {String}
  1972. */
  1973. type: type,
  1974. /**
  1975. Runtime (not native one) may operate in browser or client mode.
  1976. @property mode
  1977. @private
  1978. @type {String|Boolean} current mode or false, if none possible
  1979. */
  1980. mode: Runtime.getMode(modeCaps, (options.required_caps), defaultMode),
  1981. /**
  1982. id of the DOM container for the runtime (if available)
  1983. @property shimid
  1984. @type {String}
  1985. */
  1986. shimid: _uid + '_container',
  1987. /**
  1988. Number of connected clients. If equal to zero, runtime can be destroyed
  1989. @property clients
  1990. @type {Number}
  1991. */
  1992. clients: 0,
  1993. /**
  1994. Runtime initialization options
  1995. @property options
  1996. @type {Object}
  1997. */
  1998. options: options,
  1999. /**
  2000. Checks if the runtime has specific capability
  2001. @method can
  2002. @param {String} cap Name of capability to check
  2003. @param {Mixed} [value] If passed, capability should somehow correlate to the value
  2004. @param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set)
  2005. @return {Boolean} true if runtime has such capability and false, if - not
  2006. */
  2007. can: function(cap, value) {
  2008. var refCaps = arguments[2] || caps;
  2009. // if cap var is a comma-separated list of caps, convert it to object (key/value)
  2010. if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') {
  2011. cap = Runtime.parseCaps(cap);
  2012. }
  2013. if (Basic.typeOf(cap) === 'object') {
  2014. for (var key in cap) {
  2015. if (!this.can(key, cap[key], refCaps)) {
  2016. return false;
  2017. }
  2018. }
  2019. return true;
  2020. }
  2021. // check the individual cap
  2022. if (Basic.typeOf(refCaps[cap]) === 'function') {
  2023. return refCaps[cap].call(this, value);
  2024. } else {
  2025. return (value === refCaps[cap]);
  2026. }
  2027. },
  2028. /**
  2029. Returns container for the runtime as DOM element
  2030. @method getShimContainer
  2031. @return {DOMElement}
  2032. */
  2033. getShimContainer: function() {
  2034. var container, shimContainer = Dom.get(this.shimid);
  2035. // if no container for shim, create one
  2036. if (!shimContainer) {
  2037. container = Dom.get(this.options.container) || document.body;
  2038. // create shim container and insert it at an absolute position into the outer container
  2039. shimContainer = document.createElement('div');
  2040. shimContainer.id = this.shimid;
  2041. shimContainer.className = 'moxie-shim moxie-shim-' + this.type;
  2042. Basic.extend(shimContainer.style, {
  2043. position: 'absolute',
  2044. top: '0px',
  2045. left: '0px',
  2046. width: '1px',
  2047. height: '1px',
  2048. overflow: 'hidden'
  2049. });
  2050. container.appendChild(shimContainer);
  2051. container = null;
  2052. }
  2053. return shimContainer;
  2054. },
  2055. /**
  2056. Returns runtime as DOM element (if appropriate)
  2057. @method getShim
  2058. @return {DOMElement}
  2059. */
  2060. getShim: function() {
  2061. return _shim;
  2062. },
  2063. /**
  2064. Invokes a method within the runtime itself (might differ across the runtimes)
  2065. @method shimExec
  2066. @param {Mixed} []
  2067. @protected
  2068. @return {Mixed} Depends on the action and component
  2069. */
  2070. shimExec: function(component, action) {
  2071. var args = [].slice.call(arguments, 2);
  2072. return self.getShim().exec.call(this, this.uid, component, action, args);
  2073. },
  2074. /**
  2075. Operaional interface that is used by components to invoke specific actions on the runtime
  2076. (is invoked in the scope of component)
  2077. @method exec
  2078. @param {Mixed} []*
  2079. @protected
  2080. @return {Mixed} Depends on the action and component
  2081. */
  2082. exec: function(component, action) { // this is called in the context of component, not runtime
  2083. var args = [].slice.call(arguments, 2);
  2084. if (self[component] && self[component][action]) {
  2085. return self[component][action].apply(this, args);
  2086. }
  2087. return self.shimExec.apply(this, arguments);
  2088. },
  2089. /**
  2090. Destroys the runtime (removes all events and deletes DOM structures)
  2091. @method destroy
  2092. */
  2093. destroy: function() {
  2094. if (!self) {
  2095. return; // obviously already destroyed
  2096. }
  2097. var shimContainer = Dom.get(this.shimid);
  2098. if (shimContainer) {
  2099. shimContainer.parentNode.removeChild(shimContainer);
  2100. }
  2101. if (_shim) {
  2102. _shim.removeAllInstances();
  2103. }
  2104. this.unbindAll();
  2105. delete runtimes[this.uid];
  2106. this.uid = null; // mark this runtime as destroyed
  2107. _uid = self = _shim = shimContainer = null;
  2108. }
  2109. });
  2110. // once we got the mode, test against all caps
  2111. if (this.mode && options.required_caps && !this.can(options.required_caps)) {
  2112. this.mode = false;
  2113. }
  2114. }
  2115. /**
  2116. Default order to try different runtime types
  2117. @property order
  2118. @type String
  2119. @static
  2120. */
  2121. Runtime.order = 'html5,flash,silverlight,html4';
  2122. /**
  2123. Retrieves runtime from private hash by it's uid
  2124. @method getRuntime
  2125. @private
  2126. @static
  2127. @param {String} uid Unique identifier of the runtime
  2128. @return {Runtime|Boolean} Returns runtime, if it exists and false, if - not
  2129. */
  2130. Runtime.getRuntime = function(uid) {
  2131. return runtimes[uid] ? runtimes[uid] : false;
  2132. };
  2133. /**
  2134. Register constructor for the Runtime of new (or perhaps modified) type
  2135. @method addConstructor
  2136. @static
  2137. @param {String} type Runtime type (e.g. flash, html5, etc)
  2138. @param {Function} construct Constructor for the Runtime type
  2139. */
  2140. Runtime.addConstructor = function(type, constructor) {
  2141. constructor.prototype = EventTarget.instance;
  2142. runtimeConstructors[type] = constructor;
  2143. };
  2144. /**
  2145. Get the constructor for the specified type.
  2146. method getConstructor
  2147. @static
  2148. @param {String} type Runtime type (e.g. flash, html5, etc)
  2149. @return {Function} Constructor for the Runtime type
  2150. */
  2151. Runtime.getConstructor = function(type) {
  2152. return runtimeConstructors[type] || null;
  2153. };
  2154. /**
  2155. Get info about the runtime (uid, type, capabilities)
  2156. @method getInfo
  2157. @static
  2158. @param {String} uid Unique identifier of the runtime
  2159. @return {Mixed} Info object or null if runtime doesn't exist
  2160. */
  2161. Runtime.getInfo = function(uid) {
  2162. var runtime = Runtime.getRuntime(uid);
  2163. if (runtime) {
  2164. return {
  2165. uid: runtime.uid,
  2166. type: runtime.type,
  2167. mode: runtime.mode,
  2168. can: function() {
  2169. return runtime.can.apply(runtime, arguments);
  2170. }
  2171. };
  2172. }
  2173. return null;
  2174. };
  2175. /**
  2176. Convert caps represented by a comma-separated string to the object representation.
  2177. @method parseCaps
  2178. @static
  2179. @param {String} capStr Comma-separated list of capabilities
  2180. @return {Object}
  2181. */
  2182. Runtime.parseCaps = function(capStr) {
  2183. var capObj = {};
  2184. if (Basic.typeOf(capStr) !== 'string') {
  2185. return capStr || {};
  2186. }
  2187. Basic.each(capStr.split(','), function(key) {
  2188. capObj[key] = true; // we assume it to be - true
  2189. });
  2190. return capObj;
  2191. };
  2192. /**
  2193. Test the specified runtime for specific capabilities.
  2194. @method can
  2195. @static
  2196. @param {String} type Runtime type (e.g. flash, html5, etc)
  2197. @param {String|Object} caps Set of capabilities to check
  2198. @return {Boolean} Result of the test
  2199. */
  2200. Runtime.can = function(type, caps) {
  2201. var runtime
  2202. , constructor = Runtime.getConstructor(type)
  2203. , mode
  2204. ;
  2205. if (constructor) {
  2206. runtime = new constructor({
  2207. required_caps: caps
  2208. });
  2209. mode = runtime.mode;
  2210. runtime.destroy();
  2211. return !!mode;
  2212. }
  2213. return false;
  2214. };
  2215. /**
  2216. Figure out a runtime that supports specified capabilities.
  2217. @method thatCan
  2218. @static
  2219. @param {String|Object} caps Set of capabilities to check
  2220. @param {String} [runtimeOrder] Comma-separated list of runtimes to check against
  2221. @return {String} Usable runtime identifier or null
  2222. */
  2223. Runtime.thatCan = function(caps, runtimeOrder) {
  2224. var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/);
  2225. for (var i in types) {
  2226. if (Runtime.can(types[i], caps)) {
  2227. return types[i];
  2228. }
  2229. }
  2230. return null;
  2231. };
  2232. /**
  2233. Figure out an operational mode for the specified set of capabilities.
  2234. @method getMode
  2235. @static
  2236. @param {Object} modeCaps Set of capabilities that depend on particular runtime mode
  2237. @param {Object} [requiredCaps] Supplied set of capabilities to find operational mode for
  2238. @param {String|Boolean} [defaultMode='browser'] Default mode to use
  2239. @return {String|Boolean} Compatible operational mode
  2240. */
  2241. Runtime.getMode = function(modeCaps, requiredCaps, defaultMode) {
  2242. var mode = null;
  2243. if (Basic.typeOf(defaultMode) === 'undefined') { // only if not specified
  2244. defaultMode = 'browser';
  2245. }
  2246. if (requiredCaps && !Basic.isEmptyObj(modeCaps)) {
  2247. // loop over required caps and check if they do require the same mode
  2248. Basic.each(requiredCaps, function(value, cap) {
  2249. if (modeCaps.hasOwnProperty(cap)) {
  2250. var capMode = modeCaps[cap](value);
  2251. // make sure we always have an array
  2252. if (typeof(capMode) === 'string') {
  2253. capMode = [capMode];
  2254. }
  2255. if (!mode) {
  2256. mode = capMode;
  2257. } else if (!(mode = Basic.arrayIntersect(mode, capMode))) {
  2258. // if cap requires conflicting mode - runtime cannot fulfill required caps
  2259. if (MXI_DEBUG && Env.debug.runtime) {
  2260. Env.log("\t\t%c: %v (conflicting mode requested: %s)", cap, value, capMode);
  2261. }
  2262. return (mode = false);
  2263. }
  2264. }
  2265. if (MXI_DEBUG && Env.debug.runtime) {
  2266. Env.log("\t\t%c: %v (compatible modes: %s)", cap, value, mode);
  2267. }
  2268. });
  2269. if (mode) {
  2270. return Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0];
  2271. } else if (mode === false) {
  2272. return false;
  2273. }
  2274. }
  2275. return defaultMode;
  2276. };
  2277. /**
  2278. Capability check that always returns true
  2279. @private
  2280. @static
  2281. @return {True}
  2282. */
  2283. Runtime.capTrue = function() {
  2284. return true;
  2285. };
  2286. /**
  2287. Capability check that always returns false
  2288. @private
  2289. @static
  2290. @return {False}
  2291. */
  2292. Runtime.capFalse = function() {
  2293. return false;
  2294. };
  2295. /**
  2296. Evaluate the expression to boolean value and create a function that always returns it.
  2297. @private
  2298. @static
  2299. @param {Mixed} expr Expression to evaluate
  2300. @return {Function} Function returning the result of evaluation
  2301. */
  2302. Runtime.capTest = function(expr) {
  2303. return function() {
  2304. return !!expr;
  2305. };
  2306. };
  2307. return Runtime;
  2308. });
  2309. // Included from: src/javascript/runtime/RuntimeClient.js
  2310. /**
  2311. * RuntimeClient.js
  2312. *
  2313. * Copyright 2013, Moxiecode Systems AB
  2314. * Released under GPL License.
  2315. *
  2316. * License: http://www.plupload.com/license
  2317. * Contributing: http://www.plupload.com/contributing
  2318. */
  2319. define('moxie/runtime/RuntimeClient', [
  2320. 'moxie/core/utils/Env',
  2321. 'moxie/core/Exceptions',
  2322. 'moxie/core/utils/Basic',
  2323. 'moxie/runtime/Runtime'
  2324. ], function(Env, x, Basic, Runtime) {
  2325. /**
  2326. Set of methods and properties, required by a component to acquire ability to connect to a runtime
  2327. @class moxie/runtime/RuntimeClient
  2328. */
  2329. return function RuntimeClient() {
  2330. var runtime;
  2331. Basic.extend(this, {
  2332. /**
  2333. Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one.
  2334. Increments number of clients connected to the specified runtime.
  2335. @private
  2336. @method connectRuntime
  2337. @param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites
  2338. */
  2339. connectRuntime: function(options) {
  2340. var comp = this, ruid;
  2341. function initialize(items) {
  2342. var type, constructor;
  2343. // if we ran out of runtimes
  2344. if (!items.length) {
  2345. comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
  2346. runtime = null;
  2347. return;
  2348. }
  2349. type = items.shift().toLowerCase();
  2350. constructor = Runtime.getConstructor(type);
  2351. if (!constructor) {
  2352. if (MXI_DEBUG && Env.debug.runtime) {
  2353. Env.log("Constructor for '%s' runtime is not available.", type);
  2354. }
  2355. initialize(items);
  2356. return;
  2357. }
  2358. if (MXI_DEBUG && Env.debug.runtime) {
  2359. Env.log("Trying runtime: %s", type);
  2360. Env.log(options);
  2361. }
  2362. // try initializing the runtime
  2363. runtime = new constructor(options);
  2364. runtime.bind('Init', function() {
  2365. // mark runtime as initialized
  2366. runtime.initialized = true;
  2367. if (MXI_DEBUG && Env.debug.runtime) {
  2368. Env.log("Runtime '%s' initialized", runtime.type);
  2369. }
  2370. // jailbreak ...
  2371. setTimeout(function() {
  2372. runtime.clients++;
  2373. comp.ruid = runtime.uid;
  2374. // this will be triggered on component
  2375. comp.trigger('RuntimeInit', runtime);
  2376. }, 1);
  2377. });
  2378. runtime.bind('Error', function() {
  2379. if (MXI_DEBUG && Env.debug.runtime) {
  2380. Env.log("Runtime '%s' failed to initialize", runtime.type);
  2381. }
  2382. runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here
  2383. initialize(items);
  2384. });
  2385. runtime.bind('Exception', function(e, err) {
  2386. var message = err.name + "(#" + err.code + ")" + (err.message ? ", from: " + err.message : '');
  2387. if (MXI_DEBUG && Env.debug.runtime) {
  2388. Env.log("Runtime '%s' has thrown an exception: %s", this.type, message);
  2389. }
  2390. comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.EXCEPTION_ERR, message));
  2391. });
  2392. if (MXI_DEBUG && Env.debug.runtime) {
  2393. Env.log("\tselected mode: %s", runtime.mode);
  2394. }
  2395. // check if runtime managed to pick-up operational mode
  2396. if (!runtime.mode) {
  2397. runtime.trigger('Error');
  2398. return;
  2399. }
  2400. runtime.init();
  2401. }
  2402. // check if a particular runtime was requested
  2403. if (Basic.typeOf(options) === 'string') {
  2404. ruid = options;
  2405. } else if (Basic.typeOf(options.ruid) === 'string') {
  2406. ruid = options.ruid;
  2407. }
  2408. if (ruid) {
  2409. runtime = Runtime.getRuntime(ruid);
  2410. if (runtime) {
  2411. comp.ruid = ruid;
  2412. runtime.clients++;
  2413. return runtime;
  2414. } else {
  2415. // there should be a runtime and there's none - weird case
  2416. throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR);
  2417. }
  2418. }
  2419. // initialize a fresh one, that fits runtime list and required features best
  2420. initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/));
  2421. },
  2422. /**
  2423. Disconnects from the runtime. Decrements number of clients connected to the specified runtime.
  2424. @private
  2425. @method disconnectRuntime
  2426. */
  2427. disconnectRuntime: function() {
  2428. if (runtime && --runtime.clients <= 0) {
  2429. runtime.destroy();
  2430. }
  2431. // once the component is disconnected, it shouldn't have access to the runtime
  2432. runtime = null;
  2433. },
  2434. /**
  2435. Returns the runtime to which the client is currently connected.
  2436. @method getRuntime
  2437. @return {Runtime} Runtime or null if client is not connected
  2438. */
  2439. getRuntime: function() {
  2440. if (runtime && runtime.uid) {
  2441. return runtime;
  2442. }
  2443. return runtime = null; // make sure we do not leave zombies rambling around
  2444. },
  2445. /**
  2446. Handy shortcut to safely invoke runtime extension methods.
  2447. @private
  2448. @method exec
  2449. @return {Mixed} Whatever runtime extension method returns
  2450. */
  2451. exec: function() {
  2452. return runtime ? runtime.exec.apply(this, arguments) : null;
  2453. },
  2454. /**
  2455. Test runtime client for specific capability
  2456. @method can
  2457. @param {String} cap
  2458. @return {Bool}
  2459. */
  2460. can: function(cap) {
  2461. return runtime ? runtime.can(cap) : false;
  2462. }
  2463. });
  2464. };
  2465. });
  2466. // Included from: src/javascript/file/Blob.js
  2467. /**
  2468. * Blob.js
  2469. *
  2470. * Copyright 2013, Moxiecode Systems AB
  2471. * Released under GPL License.
  2472. *
  2473. * License: http://www.plupload.com/license
  2474. * Contributing: http://www.plupload.com/contributing
  2475. */
  2476. define('moxie/file/Blob', [
  2477. 'moxie/core/utils/Basic',
  2478. 'moxie/core/utils/Encode',
  2479. 'moxie/runtime/RuntimeClient'
  2480. ], function(Basic, Encode, RuntimeClient) {
  2481. var blobpool = {};
  2482. /**
  2483. @class moxie/file/Blob
  2484. @constructor
  2485. @param {String} ruid Unique id of the runtime, to which this blob belongs to
  2486. @param {Object} blob Object "Native" blob object, as it is represented in the runtime
  2487. */
  2488. function Blob(ruid, blob) {
  2489. function _sliceDetached(start, end, type) {
  2490. var blob, data = blobpool[this.uid];
  2491. if (Basic.typeOf(data) !== 'string' || !data.length) {
  2492. return null; // or throw exception
  2493. }
  2494. blob = new Blob(null, {
  2495. type: type,
  2496. size: end - start
  2497. });
  2498. blob.detach(data.substr(start, blob.size));
  2499. return blob;
  2500. }
  2501. RuntimeClient.call(this);
  2502. if (ruid) {
  2503. this.connectRuntime(ruid);
  2504. }
  2505. if (!blob) {
  2506. blob = {};
  2507. } else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string
  2508. blob = { data: blob };
  2509. }
  2510. Basic.extend(this, {
  2511. /**
  2512. Unique id of the component
  2513. @property uid
  2514. @type {String}
  2515. */
  2516. uid: blob.uid || Basic.guid('uid_'),
  2517. /**
  2518. Unique id of the connected runtime, if falsy, then runtime will have to be initialized
  2519. before this Blob can be used, modified or sent
  2520. @property ruid
  2521. @type {String}
  2522. */
  2523. ruid: ruid,
  2524. /**
  2525. Size of blob
  2526. @property size
  2527. @type {Number}
  2528. @default 0
  2529. */
  2530. size: blob.size || 0,
  2531. /**
  2532. Mime type of blob
  2533. @property type
  2534. @type {String}
  2535. @default ''
  2536. */
  2537. type: blob.type || '',
  2538. /**
  2539. @method slice
  2540. @param {Number} [start=0]
  2541. */
  2542. slice: function(start, end, type) {
  2543. if (this.isDetached()) {
  2544. return _sliceDetached.apply(this, arguments);
  2545. }
  2546. return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type);
  2547. },
  2548. /**
  2549. Returns "native" blob object (as it is represented in connected runtime) or null if not found
  2550. @method getSource
  2551. @return {Blob} Returns "native" blob object or null if not found
  2552. */
  2553. getSource: function() {
  2554. if (!blobpool[this.uid]) {
  2555. return null;
  2556. }
  2557. return blobpool[this.uid];
  2558. },
  2559. /**
  2560. Detaches blob from any runtime that it depends on and initialize with standalone value
  2561. @method detach
  2562. @protected
  2563. @param {DOMString} [data=''] Standalone value
  2564. */
  2565. detach: function(data) {
  2566. if (this.ruid) {
  2567. this.getRuntime().exec.call(this, 'Blob', 'destroy');
  2568. this.disconnectRuntime();
  2569. this.ruid = null;
  2570. }
  2571. data = data || '';
  2572. // if dataUrl, convert to binary string
  2573. if (data.substr(0, 5) == 'data:') {
  2574. var base64Offset = data.indexOf(';base64,');
  2575. this.type = data.substring(5, base64Offset);
  2576. data = Encode.atob(data.substring(base64Offset + 8));
  2577. }
  2578. this.size = data.length;
  2579. blobpool[this.uid] = data;
  2580. },
  2581. /**
  2582. Checks if blob is standalone (detached of any runtime)
  2583. @method isDetached
  2584. @protected
  2585. @return {Boolean}
  2586. */
  2587. isDetached: function() {
  2588. return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string';
  2589. },
  2590. /**
  2591. Destroy Blob and free any resources it was using
  2592. @method destroy
  2593. */
  2594. destroy: function() {
  2595. this.detach();
  2596. delete blobpool[this.uid];
  2597. }
  2598. });
  2599. if (blob.data) {
  2600. this.detach(blob.data); // auto-detach if payload has been passed
  2601. } else {
  2602. blobpool[this.uid] = blob;
  2603. }
  2604. }
  2605. return Blob;
  2606. });
  2607. // Included from: src/javascript/core/I18n.js
  2608. /**
  2609. * I18n.js
  2610. *
  2611. * Copyright 2013, Moxiecode Systems AB
  2612. * Released under GPL License.
  2613. *
  2614. * License: http://www.plupload.com/license
  2615. * Contributing: http://www.plupload.com/contributing
  2616. */
  2617. define("moxie/core/I18n", [
  2618. "moxie/core/utils/Basic"
  2619. ], function(Basic) {
  2620. var i18n = {};
  2621. /**
  2622. @class moxie/core/I18n
  2623. */
  2624. return {
  2625. /**
  2626. * Extends the language pack object with new items.
  2627. *
  2628. * @param {Object} pack Language pack items to add.
  2629. * @return {Object} Extended language pack object.
  2630. */
  2631. addI18n: function(pack) {
  2632. return Basic.extend(i18n, pack);
  2633. },
  2634. /**
  2635. * Translates the specified string by checking for the english string in the language pack lookup.
  2636. *
  2637. * @param {String} str String to look for.
  2638. * @return {String} Translated string or the input string if it wasn't found.
  2639. */
  2640. translate: function(str) {
  2641. return i18n[str] || str;
  2642. },
  2643. /**
  2644. * Shortcut for translate function
  2645. *
  2646. * @param {String} str String to look for.
  2647. * @return {String} Translated string or the input string if it wasn't found.
  2648. */
  2649. _: function(str) {
  2650. return this.translate(str);
  2651. },
  2652. /**
  2653. * Pseudo sprintf implementation - simple way to replace tokens with specified values.
  2654. *
  2655. * @param {String} str String with tokens
  2656. * @return {String} String with replaced tokens
  2657. */
  2658. sprintf: function(str) {
  2659. var args = [].slice.call(arguments, 1);
  2660. return str.replace(/%[a-z]/g, function() {
  2661. var value = args.shift();
  2662. return Basic.typeOf(value) !== 'undefined' ? value : '';
  2663. });
  2664. }
  2665. };
  2666. });
  2667. // Included from: src/javascript/core/utils/Mime.js
  2668. /**
  2669. * Mime.js
  2670. *
  2671. * Copyright 2013, Moxiecode Systems AB
  2672. * Released under GPL License.
  2673. *
  2674. * License: http://www.plupload.com/license
  2675. * Contributing: http://www.plupload.com/contributing
  2676. */
  2677. define("moxie/core/utils/Mime", [
  2678. "moxie/core/utils/Basic",
  2679. "moxie/core/I18n"
  2680. ], function(Basic, I18n) {
  2681. var mimeData = "" +
  2682. "application/msword,doc dot," +
  2683. "application/pdf,pdf," +
  2684. "application/pgp-signature,pgp," +
  2685. "application/postscript,ps ai eps," +
  2686. "application/rtf,rtf," +
  2687. "application/vnd.ms-excel,xls xlb," +
  2688. "application/vnd.ms-powerpoint,ppt pps pot," +
  2689. "application/zip,zip," +
  2690. "application/x-shockwave-flash,swf swfl," +
  2691. "application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," +
  2692. "application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," +
  2693. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," +
  2694. "application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," +
  2695. "application/vnd.openxmlformats-officedocument.presentationml.template,potx," +
  2696. "application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," +
  2697. "application/x-javascript,js," +
  2698. "application/json,json," +
  2699. "audio/mpeg,mp3 mpga mpega mp2," +
  2700. "audio/x-wav,wav," +
  2701. "audio/x-m4a,m4a," +
  2702. "audio/ogg,oga ogg," +
  2703. "audio/aiff,aiff aif," +
  2704. "audio/flac,flac," +
  2705. "audio/aac,aac," +
  2706. "audio/ac3,ac3," +
  2707. "audio/x-ms-wma,wma," +
  2708. "image/bmp,bmp," +
  2709. "image/gif,gif," +
  2710. "image/jpeg,jpg jpeg jpe," +
  2711. "image/photoshop,psd," +
  2712. "image/png,png," +
  2713. "image/svg+xml,svg svgz," +
  2714. "image/tiff,tiff tif," +
  2715. "text/plain,asc txt text diff log," +
  2716. "text/html,htm html xhtml," +
  2717. "text/css,css," +
  2718. "text/csv,csv," +
  2719. "text/rtf,rtf," +
  2720. "video/mpeg,mpeg mpg mpe m2v," +
  2721. "video/quicktime,qt mov," +
  2722. "video/mp4,mp4," +
  2723. "video/x-m4v,m4v," +
  2724. "video/x-flv,flv," +
  2725. "video/x-ms-wmv,wmv," +
  2726. "video/avi,avi," +
  2727. "video/webm,webm," +
  2728. "video/3gpp,3gpp 3gp," +
  2729. "video/3gpp2,3g2," +
  2730. "video/vnd.rn-realvideo,rv," +
  2731. "video/ogg,ogv," +
  2732. "video/x-matroska,mkv," +
  2733. "application/vnd.oasis.opendocument.formula-template,otf," +
  2734. "application/octet-stream,exe";
  2735. var Mime = {
  2736. mimes: {},
  2737. extensions: {},
  2738. // Parses the default mime types string into a mimes and extensions lookup maps
  2739. addMimeType: function (mimeData) {
  2740. var items = mimeData.split(/,/), i, ii, ext;
  2741. for (i = 0; i < items.length; i += 2) {
  2742. ext = items[i + 1].split(/ /);
  2743. // extension to mime lookup
  2744. for (ii = 0; ii < ext.length; ii++) {
  2745. this.mimes[ext[ii]] = items[i];
  2746. }
  2747. // mime to extension lookup
  2748. this.extensions[items[i]] = ext;
  2749. }
  2750. },
  2751. extList2mimes: function (filters, addMissingExtensions) {
  2752. var self = this, ext, i, ii, type, mimes = [];
  2753. // convert extensions to mime types list
  2754. for (i = 0; i < filters.length; i++) {
  2755. ext = filters[i].extensions.split(/\s*,\s*/);
  2756. for (ii = 0; ii < ext.length; ii++) {
  2757. // if there's an asterisk in the list, then accept attribute is not required
  2758. if (ext[ii] === '*') {
  2759. return [];
  2760. }
  2761. type = self.mimes[ext[ii]];
  2762. if (type && Basic.inArray(type, mimes) === -1) {
  2763. mimes.push(type);
  2764. }
  2765. // future browsers should filter by extension, finally
  2766. if (addMissingExtensions && /^\w+$/.test(ext[ii])) {
  2767. mimes.push('.' + ext[ii]);
  2768. } else if (!type) {
  2769. // if we have no type in our map, then accept all
  2770. return [];
  2771. }
  2772. }
  2773. }
  2774. return mimes;
  2775. },
  2776. mimes2exts: function(mimes) {
  2777. var self = this, exts = [];
  2778. Basic.each(mimes, function(mime) {
  2779. if (mime === '*') {
  2780. exts = [];
  2781. return false;
  2782. }
  2783. // check if this thing looks like mime type
  2784. var m = mime.match(/^(\w+)\/(\*|\w+)$/);
  2785. if (m) {
  2786. if (m[2] === '*') {
  2787. // wildcard mime type detected
  2788. Basic.each(self.extensions, function(arr, mime) {
  2789. if ((new RegExp('^' + m[1] + '/')).test(mime)) {
  2790. [].push.apply(exts, self.extensions[mime]);
  2791. }
  2792. });
  2793. } else if (self.extensions[mime]) {
  2794. [].push.apply(exts, self.extensions[mime]);
  2795. }
  2796. }
  2797. });
  2798. return exts;
  2799. },
  2800. mimes2extList: function(mimes) {
  2801. var accept = [], exts = [];
  2802. if (Basic.typeOf(mimes) === 'string') {
  2803. mimes = Basic.trim(mimes).split(/\s*,\s*/);
  2804. }
  2805. exts = this.mimes2exts(mimes);
  2806. accept.push({
  2807. title: I18n.translate('Files'),
  2808. extensions: exts.length ? exts.join(',') : '*'
  2809. });
  2810. // save original mimes string
  2811. accept.mimes = mimes;
  2812. return accept;
  2813. },
  2814. getFileExtension: function(fileName) {
  2815. var matches = fileName && fileName.match(/\.([^.]+)$/);
  2816. if (matches) {
  2817. return matches[1].toLowerCase();
  2818. }
  2819. return '';
  2820. },
  2821. getFileMime: function(fileName) {
  2822. return this.mimes[this.getFileExtension(fileName)] || '';
  2823. }
  2824. };
  2825. Mime.addMimeType(mimeData);
  2826. return Mime;
  2827. });
  2828. // Included from: src/javascript/file/FileInput.js
  2829. /**
  2830. * FileInput.js
  2831. *
  2832. * Copyright 2013, Moxiecode Systems AB
  2833. * Released under GPL License.
  2834. *
  2835. * License: http://www.plupload.com/license
  2836. * Contributing: http://www.plupload.com/contributing
  2837. */
  2838. define('moxie/file/FileInput', [
  2839. 'moxie/core/utils/Basic',
  2840. 'moxie/core/utils/Env',
  2841. 'moxie/core/utils/Mime',
  2842. 'moxie/core/utils/Dom',
  2843. 'moxie/core/Exceptions',
  2844. 'moxie/core/EventTarget',
  2845. 'moxie/core/I18n',
  2846. 'moxie/runtime/Runtime',
  2847. 'moxie/runtime/RuntimeClient'
  2848. ], function(Basic, Env, Mime, Dom, x, EventTarget, I18n, Runtime, RuntimeClient) {
  2849. /**
  2850. Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click,
  2851. converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory
  2852. with _FileReader_ or uploaded to a server through _XMLHttpRequest_.
  2853. @class moxie/file/FileInput
  2854. @constructor
  2855. @extends EventTarget
  2856. @uses RuntimeClient
  2857. @param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_.
  2858. @param {String|DOMElement} options.browse_button DOM Element to turn into file picker.
  2859. @param {Array} [options.accept] Array of mime types to accept. By default accepts all.
  2860. @param {Boolean} [options.multiple=false] Enable selection of multiple files.
  2861. @param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time).
  2862. @param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode
  2863. for _browse\_button_.
  2864. @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support.
  2865. @example
  2866. <div id="container">
  2867. <a id="file-picker" href="javascript:;">Browse...</a>
  2868. </div>
  2869. <script>
  2870. var fileInput = new mOxie.FileInput({
  2871. browse_button: 'file-picker', // or document.getElementById('file-picker')
  2872. container: 'container',
  2873. accept: [
  2874. {title: "Image files", extensions: "jpg,gif,png"} // accept only images
  2875. ],
  2876. multiple: true // allow multiple file selection
  2877. });
  2878. fileInput.onchange = function(e) {
  2879. // do something to files array
  2880. console.info(e.target.files); // or this.files or fileInput.files
  2881. };
  2882. fileInput.init(); // initialize
  2883. </script>
  2884. */
  2885. var dispatches = [
  2886. /**
  2887. Dispatched when runtime is connected and file-picker is ready to be used.
  2888. @event ready
  2889. @param {Object} event
  2890. */
  2891. 'ready',
  2892. /**
  2893. Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked.
  2894. Check [corresponding documentation entry](#method_refresh) for more info.
  2895. @event refresh
  2896. @param {Object} event
  2897. */
  2898. /**
  2899. Dispatched when selection of files in the dialog is complete.
  2900. @event change
  2901. @param {Object} event
  2902. */
  2903. 'change',
  2904. 'cancel', // TODO: might be useful
  2905. /**
  2906. Dispatched when mouse cursor enters file-picker area. Can be used to style element
  2907. accordingly.
  2908. @event mouseenter
  2909. @param {Object} event
  2910. */
  2911. 'mouseenter',
  2912. /**
  2913. Dispatched when mouse cursor leaves file-picker area. Can be used to style element
  2914. accordingly.
  2915. @event mouseleave
  2916. @param {Object} event
  2917. */
  2918. 'mouseleave',
  2919. /**
  2920. Dispatched when functional mouse button is pressed on top of file-picker area.
  2921. @event mousedown
  2922. @param {Object} event
  2923. */
  2924. 'mousedown',
  2925. /**
  2926. Dispatched when functional mouse button is released on top of file-picker area.
  2927. @event mouseup
  2928. @param {Object} event
  2929. */
  2930. 'mouseup'
  2931. ];
  2932. function FileInput(options) {
  2933. if (MXI_DEBUG) {
  2934. Env.log("Instantiating FileInput...");
  2935. }
  2936. var container, browseButton, defaults;
  2937. // if flat argument passed it should be browse_button id
  2938. if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) {
  2939. options = { browse_button : options };
  2940. }
  2941. // this will help us to find proper default container
  2942. browseButton = Dom.get(options.browse_button);
  2943. if (!browseButton) {
  2944. // browse button is required
  2945. throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
  2946. }
  2947. // figure out the options
  2948. defaults = {
  2949. accept: [{
  2950. title: I18n.translate('All Files'),
  2951. extensions: '*'
  2952. }],
  2953. multiple: false,
  2954. required_caps: false,
  2955. container: browseButton.parentNode || document.body
  2956. };
  2957. options = Basic.extend({}, defaults, options);
  2958. // convert to object representation
  2959. if (typeof(options.required_caps) === 'string') {
  2960. options.required_caps = Runtime.parseCaps(options.required_caps);
  2961. }
  2962. // normalize accept option (could be list of mime types or array of title/extensions pairs)
  2963. if (typeof(options.accept) === 'string') {
  2964. options.accept = Mime.mimes2extList(options.accept);
  2965. }
  2966. container = Dom.get(options.container);
  2967. // make sure we have container
  2968. if (!container) {
  2969. container = document.body;
  2970. }
  2971. // make container relative, if it's not
  2972. if (Dom.getStyle(container, 'position') === 'static') {
  2973. container.style.position = 'relative';
  2974. }
  2975. container = browseButton = null; // IE
  2976. RuntimeClient.call(this);
  2977. Basic.extend(this, {
  2978. /**
  2979. Unique id of the component
  2980. @property uid
  2981. @protected
  2982. @readOnly
  2983. @type {String}
  2984. @default UID
  2985. */
  2986. uid: Basic.guid('uid_'),
  2987. /**
  2988. Unique id of the connected runtime, if any.
  2989. @property ruid
  2990. @protected
  2991. @type {String}
  2992. */
  2993. ruid: null,
  2994. /**
  2995. Unique id of the runtime container. Useful to get hold of it for various manipulations.
  2996. @property shimid
  2997. @protected
  2998. @type {String}
  2999. */
  3000. shimid: null,
  3001. /**
  3002. Array of selected mOxie.File objects
  3003. @property files
  3004. @type {Array}
  3005. @default null
  3006. */
  3007. files: null,
  3008. /**
  3009. Initializes the file-picker, connects it to runtime and dispatches event ready when done.
  3010. @method init
  3011. */
  3012. init: function() {
  3013. var self = this;
  3014. self.bind('RuntimeInit', function(e, runtime) {
  3015. self.ruid = runtime.uid;
  3016. self.shimid = runtime.shimid;
  3017. self.bind("Ready", function() {
  3018. self.trigger("Refresh");
  3019. }, 999);
  3020. // re-position and resize shim container
  3021. self.bind('Refresh', function() {
  3022. var pos, size, browseButton, shimContainer, zIndex;
  3023. browseButton = Dom.get(options.browse_button);
  3024. shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist
  3025. if (browseButton) {
  3026. pos = Dom.getPos(browseButton, Dom.get(options.container));
  3027. size = Dom.getSize(browseButton);
  3028. zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 0;
  3029. if (shimContainer) {
  3030. Basic.extend(shimContainer.style, {
  3031. top: pos.y + 'px',
  3032. left: pos.x + 'px',
  3033. width: size.w + 'px',
  3034. height: size.h + 'px',
  3035. zIndex: zIndex + 1
  3036. });
  3037. }
  3038. }
  3039. shimContainer = browseButton = null;
  3040. });
  3041. runtime.exec.call(self, 'FileInput', 'init', options);
  3042. });
  3043. // runtime needs: options.required_features, options.runtime_order and options.container
  3044. self.connectRuntime(Basic.extend({}, options, {
  3045. required_caps: {
  3046. select_file: true
  3047. }
  3048. }));
  3049. },
  3050. /**
  3051. * Get current option value by its name
  3052. *
  3053. * @method getOption
  3054. * @param name
  3055. * @return {Mixed}
  3056. */
  3057. getOption: function(name) {
  3058. return options[name];
  3059. },
  3060. /**
  3061. * Sets a new value for the option specified by name
  3062. *
  3063. * @method setOption
  3064. * @param name
  3065. * @param value
  3066. */
  3067. setOption: function(name, value) {
  3068. if (!options.hasOwnProperty(name)) {
  3069. return;
  3070. }
  3071. var oldValue = options[name];
  3072. switch (name) {
  3073. case 'accept':
  3074. if (typeof(value) === 'string') {
  3075. value = Mime.mimes2extList(value);
  3076. }
  3077. break;
  3078. case 'container':
  3079. case 'required_caps':
  3080. throw new x.FileException(x.FileException.NO_MODIFICATION_ALLOWED_ERR);
  3081. }
  3082. options[name] = value;
  3083. this.exec('FileInput', 'setOption', name, value);
  3084. this.trigger('OptionChanged', name, value, oldValue);
  3085. },
  3086. /**
  3087. Disables file-picker element, so that it doesn't react to mouse clicks.
  3088. @method disable
  3089. @param {Boolean} [state=true] Disable component if - true, enable if - false
  3090. */
  3091. disable: function(state) {
  3092. var runtime = this.getRuntime();
  3093. if (runtime) {
  3094. this.exec('FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state);
  3095. }
  3096. },
  3097. /**
  3098. Reposition and resize dialog trigger to match the position and size of browse_button element.
  3099. @method refresh
  3100. */
  3101. refresh: function() {
  3102. this.trigger("Refresh");
  3103. },
  3104. /**
  3105. Destroy component.
  3106. @method destroy
  3107. */
  3108. destroy: function() {
  3109. var runtime = this.getRuntime();
  3110. if (runtime) {
  3111. runtime.exec.call(this, 'FileInput', 'destroy');
  3112. this.disconnectRuntime();
  3113. }
  3114. if (Basic.typeOf(this.files) === 'array') {
  3115. // no sense in leaving associated files behind
  3116. Basic.each(this.files, function(file) {
  3117. file.destroy();
  3118. });
  3119. }
  3120. this.files = null;
  3121. this.unbindAll();
  3122. }
  3123. });
  3124. this.handleEventProps(dispatches);
  3125. }
  3126. FileInput.prototype = EventTarget.instance;
  3127. return FileInput;
  3128. });
  3129. // Included from: src/javascript/file/File.js
  3130. /**
  3131. * File.js
  3132. *
  3133. * Copyright 2013, Moxiecode Systems AB
  3134. * Released under GPL License.
  3135. *
  3136. * License: http://www.plupload.com/license
  3137. * Contributing: http://www.plupload.com/contributing
  3138. */
  3139. define('moxie/file/File', [
  3140. 'moxie/core/utils/Basic',
  3141. 'moxie/core/utils/Mime',
  3142. 'moxie/file/Blob'
  3143. ], function(Basic, Mime, Blob) {
  3144. /**
  3145. @class moxie/file/File
  3146. @extends Blob
  3147. @constructor
  3148. @param {String} ruid Unique id of the runtime, to which this blob belongs to
  3149. @param {Object} file Object "Native" file object, as it is represented in the runtime
  3150. */
  3151. function File(ruid, file) {
  3152. if (!file) { // avoid extra errors in case we overlooked something
  3153. file = {};
  3154. }
  3155. Blob.apply(this, arguments);
  3156. if (!this.type) {
  3157. this.type = Mime.getFileMime(file.name);
  3158. }
  3159. // sanitize file name or generate new one
  3160. var name;
  3161. if (file.name) {
  3162. name = file.name.replace(/\\/g, '/');
  3163. name = name.substr(name.lastIndexOf('/') + 1);
  3164. } else if (this.type) {
  3165. var prefix = this.type.split('/')[0];
  3166. name = Basic.guid((prefix !== '' ? prefix : 'file') + '_');
  3167. if (Mime.extensions[this.type]) {
  3168. name += '.' + Mime.extensions[this.type][0]; // append proper extension if possible
  3169. }
  3170. }
  3171. Basic.extend(this, {
  3172. /**
  3173. File name
  3174. @property name
  3175. @type {String}
  3176. @default UID
  3177. */
  3178. name: name || Basic.guid('file_'),
  3179. /**
  3180. Relative path to the file inside a directory
  3181. @property relativePath
  3182. @type {String}
  3183. @default ''
  3184. */
  3185. relativePath: '',
  3186. /**
  3187. Date of last modification
  3188. @property lastModifiedDate
  3189. @type {String}
  3190. @default now
  3191. */
  3192. lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET)
  3193. });
  3194. }
  3195. File.prototype = Blob.prototype;
  3196. return File;
  3197. });
  3198. // Included from: src/javascript/file/FileDrop.js
  3199. /**
  3200. * FileDrop.js
  3201. *
  3202. * Copyright 2013, Moxiecode Systems AB
  3203. * Released under GPL License.
  3204. *
  3205. * License: http://www.plupload.com/license
  3206. * Contributing: http://www.plupload.com/contributing
  3207. */
  3208. define('moxie/file/FileDrop', [
  3209. 'moxie/core/I18n',
  3210. 'moxie/core/utils/Dom',
  3211. 'moxie/core/Exceptions',
  3212. 'moxie/core/utils/Basic',
  3213. 'moxie/core/utils/Env',
  3214. 'moxie/file/File',
  3215. 'moxie/runtime/RuntimeClient',
  3216. 'moxie/core/EventTarget',
  3217. 'moxie/core/utils/Mime'
  3218. ], function(I18n, Dom, x, Basic, Env, File, RuntimeClient, EventTarget, Mime) {
  3219. /**
  3220. Turn arbitrary DOM element to a drop zone accepting files. Converts selected files to _File_ objects, to be used
  3221. in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through
  3222. _XMLHttpRequest_.
  3223. @example
  3224. <div id="drop_zone">
  3225. Drop files here
  3226. </div>
  3227. <br />
  3228. <div id="filelist"></div>
  3229. <script type="text/javascript">
  3230. var fileDrop = new mOxie.FileDrop('drop_zone'), fileList = mOxie.get('filelist');
  3231. fileDrop.ondrop = function() {
  3232. mOxie.each(this.files, function(file) {
  3233. fileList.innerHTML += '<div>' + file.name + '</div>';
  3234. });
  3235. };
  3236. fileDrop.init();
  3237. </script>
  3238. @class moxie/file/FileDrop
  3239. @constructor
  3240. @extends EventTarget
  3241. @uses RuntimeClient
  3242. @param {Object|String} options If options has typeof string, argument is considered as options.drop_zone
  3243. @param {String|DOMElement} options.drop_zone DOM Element to turn into a drop zone
  3244. @param {Array} [options.accept] Array of mime types to accept. By default accepts all
  3245. @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support
  3246. */
  3247. var dispatches = [
  3248. /**
  3249. Dispatched when runtime is connected and drop zone is ready to accept files.
  3250. @event ready
  3251. @param {Object} event
  3252. */
  3253. 'ready',
  3254. /**
  3255. Dispatched when dragging cursor enters the drop zone.
  3256. @event dragenter
  3257. @param {Object} event
  3258. */
  3259. 'dragenter',
  3260. /**
  3261. Dispatched when dragging cursor leaves the drop zone.
  3262. @event dragleave
  3263. @param {Object} event
  3264. */
  3265. 'dragleave',
  3266. /**
  3267. Dispatched when file is dropped onto the drop zone.
  3268. @event drop
  3269. @param {Object} event
  3270. */
  3271. 'drop',
  3272. /**
  3273. Dispatched if error occurs.
  3274. @event error
  3275. @param {Object} event
  3276. */
  3277. 'error'
  3278. ];
  3279. function FileDrop(options) {
  3280. if (MXI_DEBUG) {
  3281. Env.log("Instantiating FileDrop...");
  3282. }
  3283. var self = this, defaults;
  3284. // if flat argument passed it should be drop_zone id
  3285. if (typeof(options) === 'string') {
  3286. options = { drop_zone : options };
  3287. }
  3288. // figure out the options
  3289. defaults = {
  3290. accept: [{
  3291. title: I18n.translate('All Files'),
  3292. extensions: '*'
  3293. }],
  3294. required_caps: {
  3295. drag_and_drop: true
  3296. }
  3297. };
  3298. options = typeof(options) === 'object' ? Basic.extend({}, defaults, options) : defaults;
  3299. // this will help us to find proper default container
  3300. options.container = Dom.get(options.drop_zone) || document.body;
  3301. // make container relative, if it is not
  3302. if (Dom.getStyle(options.container, 'position') === 'static') {
  3303. options.container.style.position = 'relative';
  3304. }
  3305. // normalize accept option (could be list of mime types or array of title/extensions pairs)
  3306. if (typeof(options.accept) === 'string') {
  3307. options.accept = Mime.mimes2extList(options.accept);
  3308. }
  3309. RuntimeClient.call(self);
  3310. Basic.extend(self, {
  3311. uid: Basic.guid('uid_'),
  3312. ruid: null,
  3313. files: null,
  3314. init: function() {
  3315. self.bind('RuntimeInit', function(e, runtime) {
  3316. self.ruid = runtime.uid;
  3317. runtime.exec.call(self, 'FileDrop', 'init', options);
  3318. self.dispatchEvent('ready');
  3319. });
  3320. // runtime needs: options.required_features, options.runtime_order and options.container
  3321. self.connectRuntime(options); // throws RuntimeError
  3322. },
  3323. destroy: function() {
  3324. var runtime = this.getRuntime();
  3325. if (runtime) {
  3326. runtime.exec.call(this, 'FileDrop', 'destroy');
  3327. this.disconnectRuntime();
  3328. }
  3329. this.files = null;
  3330. this.unbindAll();
  3331. }
  3332. });
  3333. this.handleEventProps(dispatches);
  3334. }
  3335. FileDrop.prototype = EventTarget.instance;
  3336. return FileDrop;
  3337. });
  3338. // Included from: src/javascript/file/FileReader.js
  3339. /**
  3340. * FileReader.js
  3341. *
  3342. * Copyright 2013, Moxiecode Systems AB
  3343. * Released under GPL License.
  3344. *
  3345. * License: http://www.plupload.com/license
  3346. * Contributing: http://www.plupload.com/contributing
  3347. */
  3348. define('moxie/file/FileReader', [
  3349. 'moxie/core/utils/Basic',
  3350. 'moxie/core/utils/Encode',
  3351. 'moxie/core/Exceptions',
  3352. 'moxie/core/EventTarget',
  3353. 'moxie/file/Blob',
  3354. 'moxie/runtime/RuntimeClient'
  3355. ], function(Basic, Encode, x, EventTarget, Blob, RuntimeClient) {
  3356. /**
  3357. Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader)
  3358. interface. Where possible uses native FileReader, where - not falls back to shims.
  3359. @class moxie/file/FileReader
  3360. @constructor FileReader
  3361. @extends EventTarget
  3362. @uses RuntimeClient
  3363. */
  3364. var dispatches = [
  3365. /**
  3366. Dispatched when the read starts.
  3367. @event loadstart
  3368. @param {Object} event
  3369. */
  3370. 'loadstart',
  3371. /**
  3372. Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total).
  3373. @event progress
  3374. @param {Object} event
  3375. */
  3376. 'progress',
  3377. /**
  3378. Dispatched when the read has successfully completed.
  3379. @event load
  3380. @param {Object} event
  3381. */
  3382. 'load',
  3383. /**
  3384. Dispatched when the read has been aborted. For instance, by invoking the abort() method.
  3385. @event abort
  3386. @param {Object} event
  3387. */
  3388. 'abort',
  3389. /**
  3390. Dispatched when the read has failed.
  3391. @event error
  3392. @param {Object} event
  3393. */
  3394. 'error',
  3395. /**
  3396. Dispatched when the request has completed (either in success or failure).
  3397. @event loadend
  3398. @param {Object} event
  3399. */
  3400. 'loadend'
  3401. ];
  3402. function FileReader() {
  3403. RuntimeClient.call(this);
  3404. Basic.extend(this, {
  3405. /**
  3406. UID of the component instance.
  3407. @property uid
  3408. @type {String}
  3409. */
  3410. uid: Basic.guid('uid_'),
  3411. /**
  3412. Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING
  3413. and FileReader.DONE.
  3414. @property readyState
  3415. @type {Number}
  3416. @default FileReader.EMPTY
  3417. */
  3418. readyState: FileReader.EMPTY,
  3419. /**
  3420. Result of the successful read operation.
  3421. @property result
  3422. @type {String}
  3423. */
  3424. result: null,
  3425. /**
  3426. Stores the error of failed asynchronous read operation.
  3427. @property error
  3428. @type {DOMError}
  3429. */
  3430. error: null,
  3431. /**
  3432. Initiates reading of File/Blob object contents to binary string.
  3433. @method readAsBinaryString
  3434. @param {Blob|File} blob Object to preload
  3435. */
  3436. readAsBinaryString: function(blob) {
  3437. _read.call(this, 'readAsBinaryString', blob);
  3438. },
  3439. /**
  3440. Initiates reading of File/Blob object contents to dataURL string.
  3441. @method readAsDataURL
  3442. @param {Blob|File} blob Object to preload
  3443. */
  3444. readAsDataURL: function(blob) {
  3445. _read.call(this, 'readAsDataURL', blob);
  3446. },
  3447. /**
  3448. Initiates reading of File/Blob object contents to string.
  3449. @method readAsText
  3450. @param {Blob|File} blob Object to preload
  3451. */
  3452. readAsText: function(blob) {
  3453. _read.call(this, 'readAsText', blob);
  3454. },
  3455. /**
  3456. Aborts preloading process.
  3457. @method abort
  3458. */
  3459. abort: function() {
  3460. this.result = null;
  3461. if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) {
  3462. return;
  3463. } else if (this.readyState === FileReader.LOADING) {
  3464. this.readyState = FileReader.DONE;
  3465. }
  3466. this.exec('FileReader', 'abort');
  3467. this.trigger('abort');
  3468. this.trigger('loadend');
  3469. },
  3470. /**
  3471. Destroy component and release resources.
  3472. @method destroy
  3473. */
  3474. destroy: function() {
  3475. this.abort();
  3476. this.exec('FileReader', 'destroy');
  3477. this.disconnectRuntime();
  3478. this.unbindAll();
  3479. }
  3480. });
  3481. // uid must already be assigned
  3482. this.handleEventProps(dispatches);
  3483. this.bind('Error', function(e, err) {
  3484. this.readyState = FileReader.DONE;
  3485. this.error = err;
  3486. }, 999);
  3487. this.bind('Load', function(e) {
  3488. this.readyState = FileReader.DONE;
  3489. }, 999);
  3490. function _read(op, blob) {
  3491. var self = this;
  3492. this.trigger('loadstart');
  3493. if (this.readyState === FileReader.LOADING) {
  3494. this.trigger('error', new x.DOMException(x.DOMException.INVALID_STATE_ERR));
  3495. this.trigger('loadend');
  3496. return;
  3497. }
  3498. // if source is not o.Blob/o.File
  3499. if (!(blob instanceof Blob)) {
  3500. this.trigger('error', new x.DOMException(x.DOMException.NOT_FOUND_ERR));
  3501. this.trigger('loadend');
  3502. return;
  3503. }
  3504. this.result = null;
  3505. this.readyState = FileReader.LOADING;
  3506. if (blob.isDetached()) {
  3507. var src = blob.getSource();
  3508. switch (op) {
  3509. case 'readAsText':
  3510. case 'readAsBinaryString':
  3511. this.result = src;
  3512. break;
  3513. case 'readAsDataURL':
  3514. this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src);
  3515. break;
  3516. }
  3517. this.readyState = FileReader.DONE;
  3518. this.trigger('load');
  3519. this.trigger('loadend');
  3520. } else {
  3521. this.connectRuntime(blob.ruid);
  3522. this.exec('FileReader', 'read', op, blob);
  3523. }
  3524. }
  3525. }
  3526. /**
  3527. Initial FileReader state
  3528. @property EMPTY
  3529. @type {Number}
  3530. @final
  3531. @static
  3532. @default 0
  3533. */
  3534. FileReader.EMPTY = 0;
  3535. /**
  3536. FileReader switches to this state when it is preloading the source
  3537. @property LOADING
  3538. @type {Number}
  3539. @final
  3540. @static
  3541. @default 1
  3542. */
  3543. FileReader.LOADING = 1;
  3544. /**
  3545. Preloading is complete, this is a final state
  3546. @property DONE
  3547. @type {Number}
  3548. @final
  3549. @static
  3550. @default 2
  3551. */
  3552. FileReader.DONE = 2;
  3553. FileReader.prototype = EventTarget.instance;
  3554. return FileReader;
  3555. });
  3556. // Included from: src/javascript/core/utils/Url.js
  3557. /**
  3558. * Url.js
  3559. *
  3560. * Copyright 2013, Moxiecode Systems AB
  3561. * Released under GPL License.
  3562. *
  3563. * License: http://www.plupload.com/license
  3564. * Contributing: http://www.plupload.com/contributing
  3565. */
  3566. define('moxie/core/utils/Url', [], function() {
  3567. /**
  3568. Parse url into separate components and fill in absent parts with parts from current url,
  3569. based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js
  3570. @method parseUrl
  3571. @for Utils
  3572. @static
  3573. @param {String} url Url to parse (defaults to empty string if undefined)
  3574. @return {Object} Hash containing extracted uri components
  3575. */
  3576. var parseUrl = function(url, currentUrl) {
  3577. var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment']
  3578. , i = key.length
  3579. , ports = {
  3580. http: 80,
  3581. https: 443
  3582. }
  3583. , uri = {}
  3584. , regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/
  3585. , m = regex.exec(url || '')
  3586. ;
  3587. while (i--) {
  3588. if (m[i]) {
  3589. uri[key[i]] = m[i];
  3590. }
  3591. }
  3592. // when url is relative, we set the origin and the path ourselves
  3593. if (!uri.scheme) {
  3594. // come up with defaults
  3595. if (!currentUrl || typeof(currentUrl) === 'string') {
  3596. currentUrl = parseUrl(currentUrl || document.location.href);
  3597. }
  3598. uri.scheme = currentUrl.scheme;
  3599. uri.host = currentUrl.host;
  3600. uri.port = currentUrl.port;
  3601. var path = '';
  3602. // for urls without trailing slash we need to figure out the path
  3603. if (/^[^\/]/.test(uri.path)) {
  3604. path = currentUrl.path;
  3605. // if path ends with a filename, strip it
  3606. if (/\/[^\/]*\.[^\/]*$/.test(path)) {
  3607. path = path.replace(/\/[^\/]+$/, '/');
  3608. } else {
  3609. // avoid double slash at the end (see #127)
  3610. path = path.replace(/\/?$/, '/');
  3611. }
  3612. }
  3613. uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir
  3614. }
  3615. if (!uri.port) {
  3616. uri.port = ports[uri.scheme] || 80;
  3617. }
  3618. uri.port = parseInt(uri.port, 10);
  3619. if (!uri.path) {
  3620. uri.path = "/";
  3621. }
  3622. delete uri.source;
  3623. return uri;
  3624. };
  3625. /**
  3626. Resolve url - among other things will turn relative url to absolute
  3627. @method resolveUrl
  3628. @static
  3629. @param {String|Object} url Either absolute or relative, or a result of parseUrl call
  3630. @return {String} Resolved, absolute url
  3631. */
  3632. var resolveUrl = function(url) {
  3633. var ports = { // we ignore default ports
  3634. http: 80,
  3635. https: 443
  3636. }
  3637. , urlp = typeof(url) === 'object' ? url : parseUrl(url);
  3638. ;
  3639. return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : '');
  3640. };
  3641. /**
  3642. Check if specified url has the same origin as the current document
  3643. @method hasSameOrigin
  3644. @param {String|Object} url
  3645. @return {Boolean}
  3646. */
  3647. var hasSameOrigin = function(url) {
  3648. function origin(url) {
  3649. return [url.scheme, url.host, url.port].join('/');
  3650. }
  3651. if (typeof url === 'string') {
  3652. url = parseUrl(url);
  3653. }
  3654. return origin(parseUrl()) === origin(url);
  3655. };
  3656. return {
  3657. parseUrl: parseUrl,
  3658. resolveUrl: resolveUrl,
  3659. hasSameOrigin: hasSameOrigin
  3660. };
  3661. });
  3662. // Included from: src/javascript/runtime/RuntimeTarget.js
  3663. /**
  3664. * RuntimeTarget.js
  3665. *
  3666. * Copyright 2013, Moxiecode Systems AB
  3667. * Released under GPL License.
  3668. *
  3669. * License: http://www.plupload.com/license
  3670. * Contributing: http://www.plupload.com/contributing
  3671. */
  3672. define('moxie/runtime/RuntimeTarget', [
  3673. 'moxie/core/utils/Basic',
  3674. 'moxie/runtime/RuntimeClient',
  3675. "moxie/core/EventTarget"
  3676. ], function(Basic, RuntimeClient, EventTarget) {
  3677. /**
  3678. Instance of this class can be used as a target for the events dispatched by shims,
  3679. when allowing them onto components is for either reason inappropriate
  3680. @class moxie/runtime/RuntimeTarget
  3681. @constructor
  3682. @protected
  3683. @extends EventTarget
  3684. */
  3685. function RuntimeTarget() {
  3686. this.uid = Basic.guid('uid_');
  3687. RuntimeClient.call(this);
  3688. this.destroy = function() {
  3689. this.disconnectRuntime();
  3690. this.unbindAll();
  3691. };
  3692. }
  3693. RuntimeTarget.prototype = EventTarget.instance;
  3694. return RuntimeTarget;
  3695. });
  3696. // Included from: src/javascript/file/FileReaderSync.js
  3697. /**
  3698. * FileReaderSync.js
  3699. *
  3700. * Copyright 2013, Moxiecode Systems AB
  3701. * Released under GPL License.
  3702. *
  3703. * License: http://www.plupload.com/license
  3704. * Contributing: http://www.plupload.com/contributing
  3705. */
  3706. define('moxie/file/FileReaderSync', [
  3707. 'moxie/core/utils/Basic',
  3708. 'moxie/runtime/RuntimeClient',
  3709. 'moxie/core/utils/Encode'
  3710. ], function(Basic, RuntimeClient, Encode) {
  3711. /**
  3712. Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here
  3713. it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be,
  3714. but probably < 1mb). Not meant to be used directly by user.
  3715. @class moxie/file/FileReaderSync
  3716. @private
  3717. @constructor
  3718. */
  3719. return function() {
  3720. RuntimeClient.call(this);
  3721. Basic.extend(this, {
  3722. uid: Basic.guid('uid_'),
  3723. readAsBinaryString: function(blob) {
  3724. return _read.call(this, 'readAsBinaryString', blob);
  3725. },
  3726. readAsDataURL: function(blob) {
  3727. return _read.call(this, 'readAsDataURL', blob);
  3728. },
  3729. /*readAsArrayBuffer: function(blob) {
  3730. return _read.call(this, 'readAsArrayBuffer', blob);
  3731. },*/
  3732. readAsText: function(blob) {
  3733. return _read.call(this, 'readAsText', blob);
  3734. }
  3735. });
  3736. function _read(op, blob) {
  3737. if (blob.isDetached()) {
  3738. var src = blob.getSource();
  3739. switch (op) {
  3740. case 'readAsBinaryString':
  3741. return src;
  3742. case 'readAsDataURL':
  3743. return 'data:' + blob.type + ';base64,' + Encode.btoa(src);
  3744. case 'readAsText':
  3745. var txt = '';
  3746. for (var i = 0, length = src.length; i < length; i++) {
  3747. txt += String.fromCharCode(src[i]);
  3748. }
  3749. return txt;
  3750. }
  3751. } else {
  3752. var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob);
  3753. this.disconnectRuntime();
  3754. return result;
  3755. }
  3756. }
  3757. };
  3758. });
  3759. // Included from: src/javascript/xhr/FormData.js
  3760. /**
  3761. * FormData.js
  3762. *
  3763. * Copyright 2013, Moxiecode Systems AB
  3764. * Released under GPL License.
  3765. *
  3766. * License: http://www.plupload.com/license
  3767. * Contributing: http://www.plupload.com/contributing
  3768. */
  3769. define("moxie/xhr/FormData", [
  3770. "moxie/core/Exceptions",
  3771. "moxie/core/utils/Basic",
  3772. "moxie/file/Blob"
  3773. ], function(x, Basic, Blob) {
  3774. /**
  3775. FormData
  3776. @class moxie/xhr/FormData
  3777. @constructor
  3778. */
  3779. function FormData() {
  3780. var _blob, _fields = [];
  3781. Basic.extend(this, {
  3782. /**
  3783. Append another key-value pair to the FormData object
  3784. @method append
  3785. @param {String} name Name for the new field
  3786. @param {String|Blob|Array|Object} value Value for the field
  3787. */
  3788. append: function(name, value) {
  3789. var self = this, valueType = Basic.typeOf(value);
  3790. // according to specs value might be either Blob or String
  3791. if (value instanceof Blob) {
  3792. _blob = {
  3793. name: name,
  3794. value: value // unfortunately we can only send single Blob in one FormData
  3795. };
  3796. } else if ('array' === valueType) {
  3797. name += '[]';
  3798. Basic.each(value, function(value) {
  3799. self.append(name, value);
  3800. });
  3801. } else if ('object' === valueType) {
  3802. Basic.each(value, function(value, key) {
  3803. self.append(name + '[' + key + ']', value);
  3804. });
  3805. } else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) {
  3806. self.append(name, "false");
  3807. } else {
  3808. _fields.push({
  3809. name: name,
  3810. value: value.toString()
  3811. });
  3812. }
  3813. },
  3814. /**
  3815. Checks if FormData contains Blob.
  3816. @method hasBlob
  3817. @return {Boolean}
  3818. */
  3819. hasBlob: function() {
  3820. return !!this.getBlob();
  3821. },
  3822. /**
  3823. Retrieves blob.
  3824. @method getBlob
  3825. @return {Object} Either Blob if found or null
  3826. */
  3827. getBlob: function() {
  3828. return _blob && _blob.value || null;
  3829. },
  3830. /**
  3831. Retrieves blob field name.
  3832. @method getBlobName
  3833. @return {String} Either Blob field name or null
  3834. */
  3835. getBlobName: function() {
  3836. return _blob && _blob.name || null;
  3837. },
  3838. /**
  3839. Loop over the fields in FormData and invoke the callback for each of them.
  3840. @method each
  3841. @param {Function} cb Callback to call for each field
  3842. */
  3843. each: function(cb) {
  3844. Basic.each(_fields, function(field) {
  3845. cb(field.value, field.name);
  3846. });
  3847. if (_blob) {
  3848. cb(_blob.value, _blob.name);
  3849. }
  3850. },
  3851. destroy: function() {
  3852. _blob = null;
  3853. _fields = [];
  3854. }
  3855. });
  3856. }
  3857. return FormData;
  3858. });
  3859. // Included from: src/javascript/xhr/XMLHttpRequest.js
  3860. /**
  3861. * XMLHttpRequest.js
  3862. *
  3863. * Copyright 2013, Moxiecode Systems AB
  3864. * Released under GPL License.
  3865. *
  3866. * License: http://www.plupload.com/license
  3867. * Contributing: http://www.plupload.com/contributing
  3868. */
  3869. define("moxie/xhr/XMLHttpRequest", [
  3870. "moxie/core/utils/Basic",
  3871. "moxie/core/Exceptions",
  3872. "moxie/core/EventTarget",
  3873. "moxie/core/utils/Encode",
  3874. "moxie/core/utils/Url",
  3875. "moxie/runtime/Runtime",
  3876. "moxie/runtime/RuntimeTarget",
  3877. "moxie/file/Blob",
  3878. "moxie/file/FileReaderSync",
  3879. "moxie/xhr/FormData",
  3880. "moxie/core/utils/Env",
  3881. "moxie/core/utils/Mime"
  3882. ], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) {
  3883. var httpCode = {
  3884. 100: 'Continue',
  3885. 101: 'Switching Protocols',
  3886. 102: 'Processing',
  3887. 200: 'OK',
  3888. 201: 'Created',
  3889. 202: 'Accepted',
  3890. 203: 'Non-Authoritative Information',
  3891. 204: 'No Content',
  3892. 205: 'Reset Content',
  3893. 206: 'Partial Content',
  3894. 207: 'Multi-Status',
  3895. 226: 'IM Used',
  3896. 300: 'Multiple Choices',
  3897. 301: 'Moved Permanently',
  3898. 302: 'Found',
  3899. 303: 'See Other',
  3900. 304: 'Not Modified',
  3901. 305: 'Use Proxy',
  3902. 306: 'Reserved',
  3903. 307: 'Temporary Redirect',
  3904. 400: 'Bad Request',
  3905. 401: 'Unauthorized',
  3906. 402: 'Payment Required',
  3907. 403: 'Forbidden',
  3908. 404: 'Not Found',
  3909. 405: 'Method Not Allowed',
  3910. 406: 'Not Acceptable',
  3911. 407: 'Proxy Authentication Required',
  3912. 408: 'Request Timeout',
  3913. 409: 'Conflict',
  3914. 410: 'Gone',
  3915. 411: 'Length Required',
  3916. 412: 'Precondition Failed',
  3917. 413: 'Request Entity Too Large',
  3918. 414: 'Request-URI Too Long',
  3919. 415: 'Unsupported Media Type',
  3920. 416: 'Requested Range Not Satisfiable',
  3921. 417: 'Expectation Failed',
  3922. 422: 'Unprocessable Entity',
  3923. 423: 'Locked',
  3924. 424: 'Failed Dependency',
  3925. 426: 'Upgrade Required',
  3926. 500: 'Internal Server Error',
  3927. 501: 'Not Implemented',
  3928. 502: 'Bad Gateway',
  3929. 503: 'Service Unavailable',
  3930. 504: 'Gateway Timeout',
  3931. 505: 'HTTP Version Not Supported',
  3932. 506: 'Variant Also Negotiates',
  3933. 507: 'Insufficient Storage',
  3934. 510: 'Not Extended'
  3935. };
  3936. function XMLHttpRequestUpload() {
  3937. this.uid = Basic.guid('uid_');
  3938. }
  3939. XMLHttpRequestUpload.prototype = EventTarget.instance;
  3940. /**
  3941. Implementation of XMLHttpRequest
  3942. @class moxie/xhr/XMLHttpRequest
  3943. @constructor
  3944. @uses RuntimeClient
  3945. @extends EventTarget
  3946. */
  3947. var dispatches = [
  3948. 'loadstart',
  3949. 'progress',
  3950. 'abort',
  3951. 'error',
  3952. 'load',
  3953. 'timeout',
  3954. 'loadend'
  3955. // readystatechange (for historical reasons)
  3956. ];
  3957. var NATIVE = 1, RUNTIME = 2;
  3958. function XMLHttpRequest() {
  3959. var self = this,
  3960. // this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible
  3961. props = {
  3962. /**
  3963. The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout.
  3964. @property timeout
  3965. @type Number
  3966. @default 0
  3967. */
  3968. timeout: 0,
  3969. /**
  3970. Current state, can take following values:
  3971. UNSENT (numeric value 0)
  3972. The object has been constructed.
  3973. OPENED (numeric value 1)
  3974. The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.
  3975. HEADERS_RECEIVED (numeric value 2)
  3976. All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
  3977. LOADING (numeric value 3)
  3978. The response entity body is being received.
  3979. DONE (numeric value 4)
  3980. @property readyState
  3981. @type Number
  3982. @default 0 (UNSENT)
  3983. */
  3984. readyState: XMLHttpRequest.UNSENT,
  3985. /**
  3986. True when user credentials are to be included in a cross-origin request. False when they are to be excluded
  3987. in a cross-origin request and when cookies are to be ignored in its response. Initially false.
  3988. @property withCredentials
  3989. @type Boolean
  3990. @default false
  3991. */
  3992. withCredentials: false,
  3993. /**
  3994. Returns the HTTP status code.
  3995. @property status
  3996. @type Number
  3997. @default 0
  3998. */
  3999. status: 0,
  4000. /**
  4001. Returns the HTTP status text.
  4002. @property statusText
  4003. @type String
  4004. */
  4005. statusText: "",
  4006. /**
  4007. Returns the response type. Can be set to change the response type. Values are:
  4008. the empty string (default), "arraybuffer", "blob", "document", "json", and "text".
  4009. @property responseType
  4010. @type String
  4011. */
  4012. responseType: "",
  4013. /**
  4014. Returns the document response entity body.
  4015. Throws an "InvalidStateError" exception if responseType is not the empty string or "document".
  4016. @property responseXML
  4017. @type Document
  4018. */
  4019. responseXML: null,
  4020. /**
  4021. Returns the text response entity body.
  4022. Throws an "InvalidStateError" exception if responseType is not the empty string or "text".
  4023. @property responseText
  4024. @type String
  4025. */
  4026. responseText: null,
  4027. /**
  4028. Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body).
  4029. Can become: ArrayBuffer, Blob, Document, JSON, Text
  4030. @property response
  4031. @type Mixed
  4032. */
  4033. response: null
  4034. },
  4035. _async = true,
  4036. _url,
  4037. _method,
  4038. _headers = {},
  4039. _user,
  4040. _password,
  4041. _encoding = null,
  4042. _mimeType = null,
  4043. // flags
  4044. _sync_flag = false,
  4045. _send_flag = false,
  4046. _upload_events_flag = false,
  4047. _upload_complete_flag = false,
  4048. _error_flag = false,
  4049. _same_origin_flag = false,
  4050. // times
  4051. _start_time,
  4052. _timeoutset_time,
  4053. _finalMime = null,
  4054. _finalCharset = null,
  4055. _options = {},
  4056. _xhr,
  4057. _responseHeaders = '',
  4058. _responseHeadersBag
  4059. ;
  4060. Basic.extend(this, props, {
  4061. /**
  4062. Unique id of the component
  4063. @property uid
  4064. @type String
  4065. */
  4066. uid: Basic.guid('uid_'),
  4067. /**
  4068. Target for Upload events
  4069. @property upload
  4070. @type XMLHttpRequestUpload
  4071. */
  4072. upload: new XMLHttpRequestUpload(),
  4073. /**
  4074. Sets the request method, request URL, synchronous flag, request username, and request password.
  4075. Throws a "SyntaxError" exception if one of the following is true:
  4076. method is not a valid HTTP method.
  4077. url cannot be resolved.
  4078. url contains the "user:password" format in the userinfo production.
  4079. Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK.
  4080. Throws an "InvalidAccessError" exception if one of the following is true:
  4081. Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin.
  4082. There is an associated XMLHttpRequest document and either the timeout attribute is not zero,
  4083. the withCredentials attribute is true, or the responseType attribute is not the empty string.
  4084. @method open
  4085. @param {String} method HTTP method to use on request
  4086. @param {String} url URL to request
  4087. @param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default.
  4088. @param {String} [user] Username to use in HTTP authentication process on server-side
  4089. @param {String} [password] Password to use in HTTP authentication process on server-side
  4090. */
  4091. open: function(method, url, async, user, password) {
  4092. var urlp;
  4093. // first two arguments are required
  4094. if (!method || !url) {
  4095. throw new x.DOMException(x.DOMException.SYNTAX_ERR);
  4096. }
  4097. // 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method
  4098. if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) {
  4099. throw new x.DOMException(x.DOMException.SYNTAX_ERR);
  4100. }
  4101. // 3
  4102. if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) {
  4103. _method = method.toUpperCase();
  4104. }
  4105. // 4 - allowing these methods poses a security risk
  4106. if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) {
  4107. throw new x.DOMException(x.DOMException.SECURITY_ERR);
  4108. }
  4109. // 5
  4110. url = Encode.utf8_encode(url);
  4111. // 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError".
  4112. urlp = Url.parseUrl(url);
  4113. _same_origin_flag = Url.hasSameOrigin(urlp);
  4114. // 7 - manually build up absolute url
  4115. _url = Url.resolveUrl(url);
  4116. // 9-10, 12-13
  4117. if ((user || password) && !_same_origin_flag) {
  4118. throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
  4119. }
  4120. _user = user || urlp.user;
  4121. _password = password || urlp.pass;
  4122. // 11
  4123. _async = async || true;
  4124. if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) {
  4125. throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
  4126. }
  4127. // 14 - terminate abort()
  4128. // 15 - terminate send()
  4129. // 18
  4130. _sync_flag = !_async;
  4131. _send_flag = false;
  4132. _headers = {};
  4133. _reset.call(this);
  4134. // 19
  4135. _p('readyState', XMLHttpRequest.OPENED);
  4136. // 20
  4137. this.dispatchEvent('readystatechange');
  4138. },
  4139. /**
  4140. Appends an header to the list of author request headers, or if header is already
  4141. in the list of author request headers, combines its value with value.
  4142. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
  4143. Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value
  4144. is not a valid HTTP header field value.
  4145. @method setRequestHeader
  4146. @param {String} header
  4147. @param {String|Number} value
  4148. */
  4149. setRequestHeader: function(header, value) {
  4150. var uaHeaders = [ // these headers are controlled by the user agent
  4151. "accept-charset",
  4152. "accept-encoding",
  4153. "access-control-request-headers",
  4154. "access-control-request-method",
  4155. "connection",
  4156. "content-length",
  4157. "cookie",
  4158. "cookie2",
  4159. "content-transfer-encoding",
  4160. "date",
  4161. "expect",
  4162. "host",
  4163. "keep-alive",
  4164. "origin",
  4165. "referer",
  4166. "te",
  4167. "trailer",
  4168. "transfer-encoding",
  4169. "upgrade",
  4170. "user-agent",
  4171. "via"
  4172. ];
  4173. // 1-2
  4174. if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) {
  4175. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4176. }
  4177. // 3
  4178. if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) {
  4179. throw new x.DOMException(x.DOMException.SYNTAX_ERR);
  4180. }
  4181. // 4
  4182. /* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values
  4183. if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) {
  4184. throw new x.DOMException(x.DOMException.SYNTAX_ERR);
  4185. }*/
  4186. header = Basic.trim(header).toLowerCase();
  4187. // setting of proxy-* and sec-* headers is prohibited by spec
  4188. if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) {
  4189. return false;
  4190. }
  4191. // camelize
  4192. // browsers lowercase header names (at least for custom ones)
  4193. // header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); });
  4194. if (!_headers[header]) {
  4195. _headers[header] = value;
  4196. } else {
  4197. // http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph)
  4198. _headers[header] += ', ' + value;
  4199. }
  4200. return true;
  4201. },
  4202. /**
  4203. * Test if the specified header is already set on this request.
  4204. * Returns a header value or boolean false if it's not yet set.
  4205. *
  4206. * @method hasRequestHeader
  4207. * @param {String} header Name of the header to test
  4208. * @return {Boolean|String}
  4209. */
  4210. hasRequestHeader: function(header) {
  4211. return header && _headers[header.toLowerCase()] || false;
  4212. },
  4213. /**
  4214. Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
  4215. @method getAllResponseHeaders
  4216. @return {String} reponse headers or empty string
  4217. */
  4218. getAllResponseHeaders: function() {
  4219. return _responseHeaders || '';
  4220. },
  4221. /**
  4222. Returns the header field value from the response of which the field name matches header,
  4223. unless the field name is Set-Cookie or Set-Cookie2.
  4224. @method getResponseHeader
  4225. @param {String} header
  4226. @return {String} value(s) for the specified header or null
  4227. */
  4228. getResponseHeader: function(header) {
  4229. header = header.toLowerCase();
  4230. if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) {
  4231. return null;
  4232. }
  4233. if (_responseHeaders && _responseHeaders !== '') {
  4234. // if we didn't parse response headers until now, do it and keep for later
  4235. if (!_responseHeadersBag) {
  4236. _responseHeadersBag = {};
  4237. Basic.each(_responseHeaders.split(/\r\n/), function(line) {
  4238. var pair = line.split(/:\s+/);
  4239. if (pair.length === 2) { // last line might be empty, omit
  4240. pair[0] = Basic.trim(pair[0]); // just in case
  4241. _responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form
  4242. header: pair[0],
  4243. value: Basic.trim(pair[1])
  4244. };
  4245. }
  4246. });
  4247. }
  4248. if (_responseHeadersBag.hasOwnProperty(header)) {
  4249. return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value;
  4250. }
  4251. }
  4252. return null;
  4253. },
  4254. /**
  4255. Sets the Content-Type header for the response to mime.
  4256. Throws an "InvalidStateError" exception if the state is LOADING or DONE.
  4257. Throws a "SyntaxError" exception if mime is not a valid media type.
  4258. @method overrideMimeType
  4259. @param String mime Mime type to set
  4260. */
  4261. overrideMimeType: function(mime) {
  4262. var matches, charset;
  4263. // 1
  4264. if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
  4265. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4266. }
  4267. // 2
  4268. mime = Basic.trim(mime.toLowerCase());
  4269. if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) {
  4270. mime = matches[1];
  4271. if (matches[2]) {
  4272. charset = matches[2];
  4273. }
  4274. }
  4275. if (!Mime.mimes[mime]) {
  4276. throw new x.DOMException(x.DOMException.SYNTAX_ERR);
  4277. }
  4278. // 3-4
  4279. _finalMime = mime;
  4280. _finalCharset = charset;
  4281. },
  4282. /**
  4283. Initiates the request. The optional argument provides the request entity body.
  4284. The argument is ignored if request method is GET or HEAD.
  4285. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
  4286. @method send
  4287. @param {Blob|Document|String|FormData} [data] Request entity body
  4288. @param {Object} [options] Set of requirements and pre-requisities for runtime initialization
  4289. */
  4290. send: function(data, options) {
  4291. if (Basic.typeOf(options) === 'string') {
  4292. _options = { ruid: options };
  4293. } else if (!options) {
  4294. _options = {};
  4295. } else {
  4296. _options = options;
  4297. }
  4298. // 1-2
  4299. if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) {
  4300. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4301. }
  4302. // 3
  4303. // sending Blob
  4304. if (data instanceof Blob) {
  4305. _options.ruid = data.ruid;
  4306. _mimeType = data.type || 'application/octet-stream';
  4307. }
  4308. // FormData
  4309. else if (data instanceof FormData) {
  4310. if (data.hasBlob()) {
  4311. var blob = data.getBlob();
  4312. _options.ruid = blob.ruid;
  4313. _mimeType = blob.type || 'application/octet-stream';
  4314. }
  4315. }
  4316. // DOMString
  4317. else if (typeof data === 'string') {
  4318. _encoding = 'UTF-8';
  4319. _mimeType = 'text/plain;charset=UTF-8';
  4320. // data should be converted to Unicode and encoded as UTF-8
  4321. data = Encode.utf8_encode(data);
  4322. }
  4323. // if withCredentials not set, but requested, set it automatically
  4324. if (!this.withCredentials) {
  4325. this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag;
  4326. }
  4327. // 4 - storage mutex
  4328. // 5
  4329. _upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP
  4330. // 6
  4331. _error_flag = false;
  4332. // 7
  4333. _upload_complete_flag = !data;
  4334. // 8 - Asynchronous steps
  4335. if (!_sync_flag) {
  4336. // 8.1
  4337. _send_flag = true;
  4338. // 8.2
  4339. // this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
  4340. // 8.3
  4341. //if (!_upload_complete_flag) {
  4342. // this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
  4343. //}
  4344. }
  4345. // 8.5 - Return the send() method call, but continue running the steps in this algorithm.
  4346. _doXHR.call(this, data);
  4347. },
  4348. /**
  4349. Cancels any network activity.
  4350. @method abort
  4351. */
  4352. abort: function() {
  4353. _error_flag = true;
  4354. _sync_flag = false;
  4355. if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) {
  4356. _p('readyState', XMLHttpRequest.DONE);
  4357. _send_flag = false;
  4358. if (_xhr) {
  4359. _xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag);
  4360. } else {
  4361. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4362. }
  4363. _upload_complete_flag = true;
  4364. } else {
  4365. _p('readyState', XMLHttpRequest.UNSENT);
  4366. }
  4367. },
  4368. destroy: function() {
  4369. if (_xhr) {
  4370. if (Basic.typeOf(_xhr.destroy) === 'function') {
  4371. _xhr.destroy();
  4372. }
  4373. _xhr = null;
  4374. }
  4375. this.unbindAll();
  4376. if (this.upload) {
  4377. this.upload.unbindAll();
  4378. this.upload = null;
  4379. }
  4380. }
  4381. });
  4382. this.handleEventProps(dispatches.concat(['readystatechange'])); // for historical reasons
  4383. this.upload.handleEventProps(dispatches);
  4384. /* this is nice, but maybe too lengthy
  4385. // if supported by JS version, set getters/setters for specific properties
  4386. o.defineProperty(this, 'readyState', {
  4387. configurable: false,
  4388. get: function() {
  4389. return _p('readyState');
  4390. }
  4391. });
  4392. o.defineProperty(this, 'timeout', {
  4393. configurable: false,
  4394. get: function() {
  4395. return _p('timeout');
  4396. },
  4397. set: function(value) {
  4398. if (_sync_flag) {
  4399. throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
  4400. }
  4401. // timeout still should be measured relative to the start time of request
  4402. _timeoutset_time = (new Date).getTime();
  4403. _p('timeout', value);
  4404. }
  4405. });
  4406. // the withCredentials attribute has no effect when fetching same-origin resources
  4407. o.defineProperty(this, 'withCredentials', {
  4408. configurable: false,
  4409. get: function() {
  4410. return _p('withCredentials');
  4411. },
  4412. set: function(value) {
  4413. // 1-2
  4414. if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) {
  4415. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4416. }
  4417. // 3-4
  4418. if (_anonymous_flag || _sync_flag) {
  4419. throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
  4420. }
  4421. // 5
  4422. _p('withCredentials', value);
  4423. }
  4424. });
  4425. o.defineProperty(this, 'status', {
  4426. configurable: false,
  4427. get: function() {
  4428. return _p('status');
  4429. }
  4430. });
  4431. o.defineProperty(this, 'statusText', {
  4432. configurable: false,
  4433. get: function() {
  4434. return _p('statusText');
  4435. }
  4436. });
  4437. o.defineProperty(this, 'responseType', {
  4438. configurable: false,
  4439. get: function() {
  4440. return _p('responseType');
  4441. },
  4442. set: function(value) {
  4443. // 1
  4444. if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
  4445. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4446. }
  4447. // 2
  4448. if (_sync_flag) {
  4449. throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
  4450. }
  4451. // 3
  4452. _p('responseType', value.toLowerCase());
  4453. }
  4454. });
  4455. o.defineProperty(this, 'responseText', {
  4456. configurable: false,
  4457. get: function() {
  4458. // 1
  4459. if (!~o.inArray(_p('responseType'), ['', 'text'])) {
  4460. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4461. }
  4462. // 2-3
  4463. if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
  4464. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4465. }
  4466. return _p('responseText');
  4467. }
  4468. });
  4469. o.defineProperty(this, 'responseXML', {
  4470. configurable: false,
  4471. get: function() {
  4472. // 1
  4473. if (!~o.inArray(_p('responseType'), ['', 'document'])) {
  4474. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4475. }
  4476. // 2-3
  4477. if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
  4478. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4479. }
  4480. return _p('responseXML');
  4481. }
  4482. });
  4483. o.defineProperty(this, 'response', {
  4484. configurable: false,
  4485. get: function() {
  4486. if (!!~o.inArray(_p('responseType'), ['', 'text'])) {
  4487. if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
  4488. return '';
  4489. }
  4490. }
  4491. if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
  4492. return null;
  4493. }
  4494. return _p('response');
  4495. }
  4496. });
  4497. */
  4498. function _p(prop, value) {
  4499. if (!props.hasOwnProperty(prop)) {
  4500. return;
  4501. }
  4502. if (arguments.length === 1) { // get
  4503. return Env.can('define_property') ? props[prop] : self[prop];
  4504. } else { // set
  4505. if (Env.can('define_property')) {
  4506. props[prop] = value;
  4507. } else {
  4508. self[prop] = value;
  4509. }
  4510. }
  4511. }
  4512. /*
  4513. function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) {
  4514. // TODO: http://tools.ietf.org/html/rfc3490#section-4.1
  4515. return str.toLowerCase();
  4516. }
  4517. */
  4518. function _doXHR(data) {
  4519. var self = this;
  4520. _start_time = new Date().getTime();
  4521. _xhr = new RuntimeTarget();
  4522. function loadEnd() {
  4523. if (_xhr) { // it could have been destroyed by now
  4524. _xhr.destroy();
  4525. _xhr = null;
  4526. }
  4527. self.dispatchEvent('loadend');
  4528. self = null;
  4529. }
  4530. function exec(runtime) {
  4531. _xhr.bind('LoadStart', function(e) {
  4532. _p('readyState', XMLHttpRequest.LOADING);
  4533. self.dispatchEvent('readystatechange');
  4534. self.dispatchEvent(e);
  4535. if (_upload_events_flag) {
  4536. self.upload.dispatchEvent(e);
  4537. }
  4538. });
  4539. _xhr.bind('Progress', function(e) {
  4540. if (_p('readyState') !== XMLHttpRequest.LOADING) {
  4541. _p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example)
  4542. self.dispatchEvent('readystatechange');
  4543. }
  4544. self.dispatchEvent(e);
  4545. });
  4546. _xhr.bind('UploadProgress', function(e) {
  4547. if (_upload_events_flag) {
  4548. self.upload.dispatchEvent({
  4549. type: 'progress',
  4550. lengthComputable: false,
  4551. total: e.total,
  4552. loaded: e.loaded
  4553. });
  4554. }
  4555. });
  4556. _xhr.bind('Load', function(e) {
  4557. _p('readyState', XMLHttpRequest.DONE);
  4558. _p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0));
  4559. _p('statusText', httpCode[_p('status')] || "");
  4560. _p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType')));
  4561. if (!!~Basic.inArray(_p('responseType'), ['text', ''])) {
  4562. _p('responseText', _p('response'));
  4563. } else if (_p('responseType') === 'document') {
  4564. _p('responseXML', _p('response'));
  4565. }
  4566. _responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders');
  4567. self.dispatchEvent('readystatechange');
  4568. if (_p('status') > 0) { // status 0 usually means that server is unreachable
  4569. if (_upload_events_flag) {
  4570. self.upload.dispatchEvent(e);
  4571. }
  4572. self.dispatchEvent(e);
  4573. } else {
  4574. _error_flag = true;
  4575. self.dispatchEvent('error');
  4576. }
  4577. loadEnd();
  4578. });
  4579. _xhr.bind('Abort', function(e) {
  4580. self.dispatchEvent(e);
  4581. loadEnd();
  4582. });
  4583. _xhr.bind('Error', function(e) {
  4584. _error_flag = true;
  4585. _p('readyState', XMLHttpRequest.DONE);
  4586. self.dispatchEvent('readystatechange');
  4587. _upload_complete_flag = true;
  4588. self.dispatchEvent(e);
  4589. loadEnd();
  4590. });
  4591. runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', {
  4592. url: _url,
  4593. method: _method,
  4594. async: _async,
  4595. user: _user,
  4596. password: _password,
  4597. headers: _headers,
  4598. mimeType: _mimeType,
  4599. encoding: _encoding,
  4600. responseType: self.responseType,
  4601. withCredentials: self.withCredentials,
  4602. options: _options
  4603. }, data);
  4604. }
  4605. // clarify our requirements
  4606. if (typeof(_options.required_caps) === 'string') {
  4607. _options.required_caps = Runtime.parseCaps(_options.required_caps);
  4608. }
  4609. _options.required_caps = Basic.extend({}, _options.required_caps, {
  4610. return_response_type: self.responseType
  4611. });
  4612. if (data instanceof FormData) {
  4613. _options.required_caps.send_multipart = true;
  4614. }
  4615. if (!Basic.isEmptyObj(_headers)) {
  4616. _options.required_caps.send_custom_headers = true;
  4617. }
  4618. if (!_same_origin_flag) {
  4619. _options.required_caps.do_cors = true;
  4620. }
  4621. if (_options.ruid) { // we do not need to wait if we can connect directly
  4622. exec(_xhr.connectRuntime(_options));
  4623. } else {
  4624. _xhr.bind('RuntimeInit', function(e, runtime) {
  4625. exec(runtime);
  4626. });
  4627. _xhr.bind('RuntimeError', function(e, err) {
  4628. self.dispatchEvent('RuntimeError', err);
  4629. });
  4630. _xhr.connectRuntime(_options);
  4631. }
  4632. }
  4633. function _reset() {
  4634. _p('responseText', "");
  4635. _p('responseXML', null);
  4636. _p('response', null);
  4637. _p('status', 0);
  4638. _p('statusText', "");
  4639. _start_time = _timeoutset_time = null;
  4640. }
  4641. }
  4642. XMLHttpRequest.UNSENT = 0;
  4643. XMLHttpRequest.OPENED = 1;
  4644. XMLHttpRequest.HEADERS_RECEIVED = 2;
  4645. XMLHttpRequest.LOADING = 3;
  4646. XMLHttpRequest.DONE = 4;
  4647. XMLHttpRequest.prototype = EventTarget.instance;
  4648. return XMLHttpRequest;
  4649. });
  4650. // Included from: src/javascript/runtime/Transporter.js
  4651. /**
  4652. * Transporter.js
  4653. *
  4654. * Copyright 2013, Moxiecode Systems AB
  4655. * Released under GPL License.
  4656. *
  4657. * License: http://www.plupload.com/license
  4658. * Contributing: http://www.plupload.com/contributing
  4659. */
  4660. define("moxie/runtime/Transporter", [
  4661. "moxie/core/utils/Basic",
  4662. "moxie/core/utils/Encode",
  4663. "moxie/runtime/RuntimeClient",
  4664. "moxie/core/EventTarget"
  4665. ], function(Basic, Encode, RuntimeClient, EventTarget) {
  4666. /**
  4667. @class moxie/runtime/Transporter
  4668. @constructor
  4669. */
  4670. function Transporter() {
  4671. var mod, _runtime, _data, _size, _pos, _chunk_size;
  4672. RuntimeClient.call(this);
  4673. Basic.extend(this, {
  4674. uid: Basic.guid('uid_'),
  4675. state: Transporter.IDLE,
  4676. result: null,
  4677. transport: function(data, type, options) {
  4678. var self = this;
  4679. options = Basic.extend({
  4680. chunk_size: 204798
  4681. }, options);
  4682. // should divide by three, base64 requires this
  4683. if ((mod = options.chunk_size % 3)) {
  4684. options.chunk_size += 3 - mod;
  4685. }
  4686. _chunk_size = options.chunk_size;
  4687. _reset.call(this);
  4688. _data = data;
  4689. _size = data.length;
  4690. if (Basic.typeOf(options) === 'string' || options.ruid) {
  4691. _run.call(self, type, this.connectRuntime(options));
  4692. } else {
  4693. // we require this to run only once
  4694. var cb = function(e, runtime) {
  4695. self.unbind("RuntimeInit", cb);
  4696. _run.call(self, type, runtime);
  4697. };
  4698. this.bind("RuntimeInit", cb);
  4699. this.connectRuntime(options);
  4700. }
  4701. },
  4702. abort: function() {
  4703. var self = this;
  4704. self.state = Transporter.IDLE;
  4705. if (_runtime) {
  4706. _runtime.exec.call(self, 'Transporter', 'clear');
  4707. self.trigger("TransportingAborted");
  4708. }
  4709. _reset.call(self);
  4710. },
  4711. destroy: function() {
  4712. this.unbindAll();
  4713. _runtime = null;
  4714. this.disconnectRuntime();
  4715. _reset.call(this);
  4716. }
  4717. });
  4718. function _reset() {
  4719. _size = _pos = 0;
  4720. _data = this.result = null;
  4721. }
  4722. function _run(type, runtime) {
  4723. var self = this;
  4724. _runtime = runtime;
  4725. //self.unbind("RuntimeInit");
  4726. self.bind("TransportingProgress", function(e) {
  4727. _pos = e.loaded;
  4728. if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) {
  4729. _transport.call(self);
  4730. }
  4731. }, 999);
  4732. self.bind("TransportingComplete", function() {
  4733. _pos = _size;
  4734. self.state = Transporter.DONE;
  4735. _data = null; // clean a bit
  4736. self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || '');
  4737. }, 999);
  4738. self.state = Transporter.BUSY;
  4739. self.trigger("TransportingStarted");
  4740. _transport.call(self);
  4741. }
  4742. function _transport() {
  4743. var self = this,
  4744. chunk,
  4745. bytesLeft = _size - _pos;
  4746. if (_chunk_size > bytesLeft) {
  4747. _chunk_size = bytesLeft;
  4748. }
  4749. chunk = Encode.btoa(_data.substr(_pos, _chunk_size));
  4750. _runtime.exec.call(self, 'Transporter', 'receive', chunk, _size);
  4751. }
  4752. }
  4753. Transporter.IDLE = 0;
  4754. Transporter.BUSY = 1;
  4755. Transporter.DONE = 2;
  4756. Transporter.prototype = EventTarget.instance;
  4757. return Transporter;
  4758. });
  4759. // Included from: src/javascript/image/Image.js
  4760. /**
  4761. * Image.js
  4762. *
  4763. * Copyright 2013, Moxiecode Systems AB
  4764. * Released under GPL License.
  4765. *
  4766. * License: http://www.plupload.com/license
  4767. * Contributing: http://www.plupload.com/contributing
  4768. */
  4769. define("moxie/image/Image", [
  4770. "moxie/core/utils/Basic",
  4771. "moxie/core/utils/Dom",
  4772. "moxie/core/Exceptions",
  4773. "moxie/file/FileReaderSync",
  4774. "moxie/xhr/XMLHttpRequest",
  4775. "moxie/runtime/Runtime",
  4776. "moxie/runtime/RuntimeClient",
  4777. "moxie/runtime/Transporter",
  4778. "moxie/core/utils/Env",
  4779. "moxie/core/EventTarget",
  4780. "moxie/file/Blob",
  4781. "moxie/file/File",
  4782. "moxie/core/utils/Encode"
  4783. ], function(Basic, Dom, x, FileReaderSync, XMLHttpRequest, Runtime, RuntimeClient, Transporter, Env, EventTarget, Blob, File, Encode) {
  4784. /**
  4785. Image preloading and manipulation utility. Additionally it provides access to image meta info (Exif, GPS) and raw binary data.
  4786. @class moxie/image/Image
  4787. @constructor
  4788. @extends EventTarget
  4789. */
  4790. var dispatches = [
  4791. 'progress',
  4792. /**
  4793. Dispatched when loading is complete.
  4794. @event load
  4795. @param {Object} event
  4796. */
  4797. 'load',
  4798. 'error',
  4799. /**
  4800. Dispatched when resize operation is complete.
  4801. @event resize
  4802. @param {Object} event
  4803. */
  4804. 'resize',
  4805. /**
  4806. Dispatched when visual representation of the image is successfully embedded
  4807. into the corresponsing container.
  4808. @event embedded
  4809. @param {Object} event
  4810. */
  4811. 'embedded'
  4812. ];
  4813. function Image() {
  4814. RuntimeClient.call(this);
  4815. Basic.extend(this, {
  4816. /**
  4817. Unique id of the component
  4818. @property uid
  4819. @type {String}
  4820. */
  4821. uid: Basic.guid('uid_'),
  4822. /**
  4823. Unique id of the connected runtime, if any.
  4824. @property ruid
  4825. @type {String}
  4826. */
  4827. ruid: null,
  4828. /**
  4829. Name of the file, that was used to create an image, if available. If not equals to empty string.
  4830. @property name
  4831. @type {String}
  4832. @default ""
  4833. */
  4834. name: "",
  4835. /**
  4836. Size of the image in bytes. Actual value is set only after image is preloaded.
  4837. @property size
  4838. @type {Number}
  4839. @default 0
  4840. */
  4841. size: 0,
  4842. /**
  4843. Width of the image. Actual value is set only after image is preloaded.
  4844. @property width
  4845. @type {Number}
  4846. @default 0
  4847. */
  4848. width: 0,
  4849. /**
  4850. Height of the image. Actual value is set only after image is preloaded.
  4851. @property height
  4852. @type {Number}
  4853. @default 0
  4854. */
  4855. height: 0,
  4856. /**
  4857. Mime type of the image. Currently only image/jpeg and image/png are supported. Actual value is set only after image is preloaded.
  4858. @property type
  4859. @type {String}
  4860. @default ""
  4861. */
  4862. type: "",
  4863. /**
  4864. Holds meta info (Exif, GPS). Is populated only for image/jpeg. Actual value is set only after image is preloaded.
  4865. @property meta
  4866. @type {Object}
  4867. @default {}
  4868. */
  4869. meta: {},
  4870. /**
  4871. Alias for load method, that takes another mOxie.Image object as a source (see load).
  4872. @method clone
  4873. @param {Image} src Source for the image
  4874. @param {Boolean} [exact=false] Whether to activate in-depth clone mode
  4875. */
  4876. clone: function() {
  4877. this.load.apply(this, arguments);
  4878. },
  4879. /**
  4880. Loads image from various sources. Currently the source for new image can be: mOxie.Image, mOxie.Blob/mOxie.File,
  4881. native Blob/File, dataUrl or URL. Depending on the type of the source, arguments - differ. When source is URL,
  4882. Image will be downloaded from remote destination and loaded in memory.
  4883. @example
  4884. var img = new mOxie.Image();
  4885. img.onload = function() {
  4886. var blob = img.getAsBlob();
  4887. var formData = new mOxie.FormData();
  4888. formData.append('file', blob);
  4889. var xhr = new mOxie.XMLHttpRequest();
  4890. xhr.onload = function() {
  4891. // upload complete
  4892. };
  4893. xhr.open('post', 'upload.php');
  4894. xhr.send(formData);
  4895. };
  4896. img.load("http://www.moxiecode.com/images/mox-logo.jpg"); // notice file extension (.jpg)
  4897. @method load
  4898. @param {Image|Blob|File|String} src Source for the image
  4899. @param {Boolean|Object} [mixed]
  4900. */
  4901. load: function() {
  4902. _load.apply(this, arguments);
  4903. },
  4904. /**
  4905. Resizes the image to fit the specified width/height. If crop is specified, image will also be
  4906. cropped to the exact dimensions.
  4907. @method resize
  4908. @since 3.0
  4909. @param {Object} options
  4910. @param {Number} options.width Resulting width
  4911. @param {Number} [options.height=width] Resulting height (optional, if not supplied will default to width)
  4912. @param {String} [options.type='image/jpeg'] MIME type of the resulting image
  4913. @param {Number} [options.quality=90] In the case of JPEG, controls the quality of resulting image
  4914. @param {Boolean} [options.crop='cc'] If not falsy, image will be cropped, by default from center
  4915. @param {Boolean} [options.fit=true] In case of crop whether to upscale the image to fit the exact dimensions
  4916. @param {Boolean} [options.preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize)
  4917. @param {String} [options.resample='default'] Resampling algorithm to use during resize
  4918. @param {Boolean} [options.multipass=true] Whether to scale the image in steps (results in better quality)
  4919. */
  4920. resize: function(options) {
  4921. var self = this;
  4922. var orientation;
  4923. var scale;
  4924. var srcRect = {
  4925. x: 0,
  4926. y: 0,
  4927. width: self.width,
  4928. height: self.height
  4929. };
  4930. var opts = Basic.extendIf({
  4931. width: self.width,
  4932. height: self.height,
  4933. type: self.type || 'image/jpeg',
  4934. quality: 90,
  4935. crop: false,
  4936. fit: true,
  4937. preserveHeaders: true,
  4938. resample: 'default',
  4939. multipass: true
  4940. }, options);
  4941. try {
  4942. if (!self.size) { // only preloaded image objects can be used as source
  4943. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4944. }
  4945. // no way to reliably intercept the crash due to high resolution, so we simply avoid it
  4946. if (self.width > Image.MAX_RESIZE_WIDTH || self.height > Image.MAX_RESIZE_HEIGHT) {
  4947. throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR);
  4948. }
  4949. // take into account orientation tag
  4950. orientation = (self.meta && self.meta.tiff && self.meta.tiff.Orientation) || 1;
  4951. if (Basic.inArray(orientation, [5,6,7,8]) !== -1) { // values that require 90 degree rotation
  4952. var tmp = opts.width;
  4953. opts.width = opts.height;
  4954. opts.height = tmp;
  4955. }
  4956. if (opts.crop) {
  4957. scale = Math.max(opts.width/self.width, opts.height/self.height);
  4958. if (options.fit) {
  4959. // first scale it up or down to fit the original image
  4960. srcRect.width = Math.min(Math.ceil(opts.width/scale), self.width);
  4961. srcRect.height = Math.min(Math.ceil(opts.height/scale), self.height);
  4962. // recalculate the scale for adapted dimensions
  4963. scale = opts.width/srcRect.width;
  4964. } else {
  4965. srcRect.width = Math.min(opts.width, self.width);
  4966. srcRect.height = Math.min(opts.height, self.height);
  4967. // now we do not need to scale it any further
  4968. scale = 1;
  4969. }
  4970. if (typeof(opts.crop) === 'boolean') {
  4971. opts.crop = 'cc';
  4972. }
  4973. switch (opts.crop.toLowerCase().replace(/_/, '-')) {
  4974. case 'rb':
  4975. case 'right-bottom':
  4976. srcRect.x = self.width - srcRect.width;
  4977. srcRect.y = self.height - srcRect.height;
  4978. break;
  4979. case 'cb':
  4980. case 'center-bottom':
  4981. srcRect.x = Math.floor((self.width - srcRect.width) / 2);
  4982. srcRect.y = self.height - srcRect.height;
  4983. break;
  4984. case 'lb':
  4985. case 'left-bottom':
  4986. srcRect.x = 0;
  4987. srcRect.y = self.height - srcRect.height;
  4988. break;
  4989. case 'lt':
  4990. case 'left-top':
  4991. srcRect.x = 0;
  4992. srcRect.y = 0;
  4993. break;
  4994. case 'ct':
  4995. case 'center-top':
  4996. srcRect.x = Math.floor((self.width - srcRect.width) / 2);
  4997. srcRect.y = 0;
  4998. break;
  4999. case 'rt':
  5000. case 'right-top':
  5001. srcRect.x = self.width - srcRect.width;
  5002. srcRect.y = 0;
  5003. break;
  5004. case 'rc':
  5005. case 'right-center':
  5006. case 'right-middle':
  5007. srcRect.x = self.width - srcRect.width;
  5008. srcRect.y = Math.floor((self.height - srcRect.height) / 2);
  5009. break;
  5010. case 'lc':
  5011. case 'left-center':
  5012. case 'left-middle':
  5013. srcRect.x = 0;
  5014. srcRect.y = Math.floor((self.height - srcRect.height) / 2);
  5015. break;
  5016. case 'cc':
  5017. case 'center-center':
  5018. case 'center-middle':
  5019. default:
  5020. srcRect.x = Math.floor((self.width - srcRect.width) / 2);
  5021. srcRect.y = Math.floor((self.height - srcRect.height) / 2);
  5022. }
  5023. // original image might be smaller than requested crop, so - avoid negative values
  5024. srcRect.x = Math.max(srcRect.x, 0);
  5025. srcRect.y = Math.max(srcRect.y, 0);
  5026. } else {
  5027. scale = Math.min(opts.width/self.width, opts.height/self.height);
  5028. }
  5029. this.exec('Image', 'resize', srcRect, scale, opts);
  5030. } catch(ex) {
  5031. // for now simply trigger error event
  5032. self.trigger('error', ex.code);
  5033. }
  5034. },
  5035. /**
  5036. Downsizes the image to fit the specified width/height. If crop is supplied, image will be cropped to exact dimensions.
  5037. @method downsize
  5038. @deprecated use resize()
  5039. */
  5040. downsize: function(options) {
  5041. var defaults = {
  5042. width: this.width,
  5043. height: this.height,
  5044. type: this.type || 'image/jpeg',
  5045. quality: 90,
  5046. crop: false,
  5047. preserveHeaders: true,
  5048. resample: 'default'
  5049. }, opts;
  5050. if (typeof(options) === 'object') {
  5051. opts = Basic.extend(defaults, options);
  5052. } else {
  5053. // for backward compatibility
  5054. opts = Basic.extend(defaults, {
  5055. width: arguments[0],
  5056. height: arguments[1],
  5057. crop: arguments[2],
  5058. preserveHeaders: arguments[3]
  5059. });
  5060. }
  5061. this.resize(opts);
  5062. },
  5063. /**
  5064. Alias for downsize(width, height, true). (see downsize)
  5065. @method crop
  5066. @param {Number} width Resulting width
  5067. @param {Number} [height=width] Resulting height (optional, if not supplied will default to width)
  5068. @param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize)
  5069. */
  5070. crop: function(width, height, preserveHeaders) {
  5071. this.downsize(width, height, true, preserveHeaders);
  5072. },
  5073. getAsCanvas: function() {
  5074. if (!Env.can('create_canvas')) {
  5075. throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
  5076. }
  5077. var runtime = this.connectRuntime(this.ruid);
  5078. return runtime.exec.call(this, 'Image', 'getAsCanvas');
  5079. },
  5080. /**
  5081. Retrieves image in it's current state as mOxie.Blob object. Cannot be run on empty or image in progress (throws
  5082. DOMException.INVALID_STATE_ERR).
  5083. @method getAsBlob
  5084. @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
  5085. @param {Number} [quality=90] Applicable only together with mime type image/jpeg
  5086. @return {Blob} Image as Blob
  5087. */
  5088. getAsBlob: function(type, quality) {
  5089. if (!this.size) {
  5090. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  5091. }
  5092. return this.exec('Image', 'getAsBlob', type || 'image/jpeg', quality || 90);
  5093. },
  5094. /**
  5095. Retrieves image in it's current state as dataURL string. Cannot be run on empty or image in progress (throws
  5096. DOMException.INVALID_STATE_ERR).
  5097. @method getAsDataURL
  5098. @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
  5099. @param {Number} [quality=90] Applicable only together with mime type image/jpeg
  5100. @return {String} Image as dataURL string
  5101. */
  5102. getAsDataURL: function(type, quality) {
  5103. if (!this.size) {
  5104. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  5105. }
  5106. return this.exec('Image', 'getAsDataURL', type || 'image/jpeg', quality || 90);
  5107. },
  5108. /**
  5109. Retrieves image in it's current state as binary string. Cannot be run on empty or image in progress (throws
  5110. DOMException.INVALID_STATE_ERR).
  5111. @method getAsBinaryString
  5112. @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
  5113. @param {Number} [quality=90] Applicable only together with mime type image/jpeg
  5114. @return {String} Image as binary string
  5115. */
  5116. getAsBinaryString: function(type, quality) {
  5117. var dataUrl = this.getAsDataURL(type, quality);
  5118. return Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7));
  5119. },
  5120. /**
  5121. Embeds a visual representation of the image into the specified node. Depending on the runtime,
  5122. it might be a canvas, an img node or a thrid party shim object (Flash or SilverLight - very rare,
  5123. can be used in legacy browsers that do not have canvas or proper dataURI support).
  5124. @method embed
  5125. @param {DOMElement} el DOM element to insert the image object into
  5126. @param {Object} [options]
  5127. @param {Number} [options.width] The width of an embed (defaults to the image width)
  5128. @param {Number} [options.height] The height of an embed (defaults to the image height)
  5129. @param {String} [options.type="image/jpeg"] Mime type
  5130. @param {Number} [options.quality=90] Quality of an embed, if mime type is image/jpeg
  5131. @param {Boolean} [options.crop=false] Whether to crop an embed to the specified dimensions
  5132. */
  5133. embed: function(el, options) {
  5134. var self = this
  5135. , runtime // this has to be outside of all the closures to contain proper runtime
  5136. ;
  5137. var opts = Basic.extend({
  5138. width: this.width,
  5139. height: this.height,
  5140. type: this.type || 'image/jpeg',
  5141. quality: 90
  5142. }, options);
  5143. function render(type, quality) {
  5144. var img = this;
  5145. // if possible, embed a canvas element directly
  5146. if (Env.can('create_canvas')) {
  5147. var canvas = img.getAsCanvas();
  5148. if (canvas) {
  5149. el.appendChild(canvas);
  5150. canvas = null;
  5151. img.destroy();
  5152. self.trigger('embedded');
  5153. return;
  5154. }
  5155. }
  5156. var dataUrl = img.getAsDataURL(type, quality);
  5157. if (!dataUrl) {
  5158. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  5159. }
  5160. if (Env.can('use_data_uri_of', dataUrl.length)) {
  5161. el.innerHTML = '<img src="' + dataUrl + '" width="' + img.width + '" height="' + img.height + '" />';
  5162. img.destroy();
  5163. self.trigger('embedded');
  5164. } else {
  5165. var tr = new Transporter();
  5166. tr.bind("TransportingComplete", function() {
  5167. runtime = self.connectRuntime(this.result.ruid);
  5168. self.bind("Embedded", function() {
  5169. // position and size properly
  5170. Basic.extend(runtime.getShimContainer().style, {
  5171. //position: 'relative',
  5172. top: '0px',
  5173. left: '0px',
  5174. width: img.width + 'px',
  5175. height: img.height + 'px'
  5176. });
  5177. // some shims (Flash/SilverLight) reinitialize, if parent element is hidden, reordered or it's
  5178. // position type changes (in Gecko), but since we basically need this only in IEs 6/7 and
  5179. // sometimes 8 and they do not have this problem, we can comment this for now
  5180. /*tr.bind("RuntimeInit", function(e, runtime) {
  5181. tr.destroy();
  5182. runtime.destroy();
  5183. onResize.call(self); // re-feed our image data
  5184. });*/
  5185. runtime = null; // release
  5186. }, 999);
  5187. runtime.exec.call(self, "ImageView", "display", this.result.uid, width, height);
  5188. img.destroy();
  5189. });
  5190. tr.transport(Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)), type, {
  5191. required_caps: {
  5192. display_media: true
  5193. },
  5194. runtime_order: 'flash,silverlight',
  5195. container: el
  5196. });
  5197. }
  5198. }
  5199. try {
  5200. if (!(el = Dom.get(el))) {
  5201. throw new x.DOMException(x.DOMException.INVALID_NODE_TYPE_ERR);
  5202. }
  5203. if (!this.size) { // only preloaded image objects can be used as source
  5204. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  5205. }
  5206. // high-resolution images cannot be consistently handled across the runtimes
  5207. if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) {
  5208. //throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR);
  5209. }
  5210. var imgCopy = new Image();
  5211. imgCopy.bind("Resize", function() {
  5212. render.call(this, opts.type, opts.quality);
  5213. });
  5214. imgCopy.bind("Load", function() {
  5215. imgCopy.downsize(opts);
  5216. });
  5217. // if embedded thumb data is available and dimensions are big enough, use it
  5218. if (this.meta.thumb && this.meta.thumb.width >= opts.width && this.meta.thumb.height >= opts.height) {
  5219. imgCopy.load(this.meta.thumb.data);
  5220. } else {
  5221. imgCopy.clone(this, false);
  5222. }
  5223. return imgCopy;
  5224. } catch(ex) {
  5225. // for now simply trigger error event
  5226. this.trigger('error', ex.code);
  5227. }
  5228. },
  5229. /**
  5230. Properly destroys the image and frees resources in use. If any. Recommended way to dispose mOxie.Image object.
  5231. @method destroy
  5232. */
  5233. destroy: function() {
  5234. if (this.ruid) {
  5235. this.getRuntime().exec.call(this, 'Image', 'destroy');
  5236. this.disconnectRuntime();
  5237. }
  5238. this.unbindAll();
  5239. }
  5240. });
  5241. // this is here, because in order to bind properly, we need uid, which is created above
  5242. this.handleEventProps(dispatches);
  5243. this.bind('Load Resize', function() {
  5244. return _updateInfo.call(this); // if operation fails (e.g. image is neither PNG nor JPEG) cancel all pending events
  5245. }, 999);
  5246. function _updateInfo(info) {
  5247. try {
  5248. if (!info) {
  5249. info = this.exec('Image', 'getInfo');
  5250. }
  5251. this.size = info.size;
  5252. this.width = info.width;
  5253. this.height = info.height;
  5254. this.type = info.type;
  5255. this.meta = info.meta;
  5256. // update file name, only if empty
  5257. if (this.name === '') {
  5258. this.name = info.name;
  5259. }
  5260. return true;
  5261. } catch(ex) {
  5262. this.trigger('error', ex.code);
  5263. return false;
  5264. }
  5265. }
  5266. function _load(src) {
  5267. var srcType = Basic.typeOf(src);
  5268. try {
  5269. // if source is Image
  5270. if (src instanceof Image) {
  5271. if (!src.size) { // only preloaded image objects can be used as source
  5272. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  5273. }
  5274. _loadFromImage.apply(this, arguments);
  5275. }
  5276. // if source is o.Blob/o.File
  5277. else if (src instanceof Blob) {
  5278. if (!~Basic.inArray(src.type, ['image/jpeg', 'image/png'])) {
  5279. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  5280. }
  5281. _loadFromBlob.apply(this, arguments);
  5282. }
  5283. // if native blob/file
  5284. else if (Basic.inArray(srcType, ['blob', 'file']) !== -1) {
  5285. _load.call(this, new File(null, src), arguments[1]);
  5286. }
  5287. // if String
  5288. else if (srcType === 'string') {
  5289. // if dataUrl String
  5290. if (src.substr(0, 5) === 'data:') {
  5291. _load.call(this, new Blob(null, { data: src }), arguments[1]);
  5292. }
  5293. // else assume Url, either relative or absolute
  5294. else {
  5295. _loadFromUrl.apply(this, arguments);
  5296. }
  5297. }
  5298. // if source seems to be an img node
  5299. else if (srcType === 'node' && src.nodeName.toLowerCase() === 'img') {
  5300. _load.call(this, src.src, arguments[1]);
  5301. }
  5302. else {
  5303. throw new x.DOMException(x.DOMException.TYPE_MISMATCH_ERR);
  5304. }
  5305. } catch(ex) {
  5306. // for now simply trigger error event
  5307. this.trigger('error', ex.code);
  5308. }
  5309. }
  5310. function _loadFromImage(img, exact) {
  5311. var runtime = this.connectRuntime(img.ruid);
  5312. this.ruid = runtime.uid;
  5313. runtime.exec.call(this, 'Image', 'loadFromImage', img, (Basic.typeOf(exact) === 'undefined' ? true : exact));
  5314. }
  5315. function _loadFromBlob(blob, options) {
  5316. var self = this;
  5317. self.name = blob.name || '';
  5318. function exec(runtime) {
  5319. self.ruid = runtime.uid;
  5320. runtime.exec.call(self, 'Image', 'loadFromBlob', blob);
  5321. }
  5322. if (blob.isDetached()) {
  5323. this.bind('RuntimeInit', function(e, runtime) {
  5324. exec(runtime);
  5325. });
  5326. // convert to object representation
  5327. if (options && typeof(options.required_caps) === 'string') {
  5328. options.required_caps = Runtime.parseCaps(options.required_caps);
  5329. }
  5330. this.connectRuntime(Basic.extend({
  5331. required_caps: {
  5332. access_image_binary: true,
  5333. resize_image: true
  5334. }
  5335. }, options));
  5336. } else {
  5337. exec(this.connectRuntime(blob.ruid));
  5338. }
  5339. }
  5340. function _loadFromUrl(url, options) {
  5341. var self = this, xhr;
  5342. xhr = new XMLHttpRequest();
  5343. xhr.open('get', url);
  5344. xhr.responseType = 'blob';
  5345. xhr.onprogress = function(e) {
  5346. self.trigger(e);
  5347. };
  5348. xhr.onload = function() {
  5349. _loadFromBlob.call(self, xhr.response, true);
  5350. };
  5351. xhr.onerror = function(e) {
  5352. self.trigger(e);
  5353. };
  5354. xhr.onloadend = function() {
  5355. xhr.destroy();
  5356. };
  5357. xhr.bind('RuntimeError', function(e, err) {
  5358. self.trigger('RuntimeError', err);
  5359. });
  5360. xhr.send(null, options);
  5361. }
  5362. }
  5363. // virtual world will crash on you if image has a resolution higher than this:
  5364. Image.MAX_RESIZE_WIDTH = 8192;
  5365. Image.MAX_RESIZE_HEIGHT = 8192;
  5366. Image.prototype = EventTarget.instance;
  5367. return Image;
  5368. });
  5369. // Included from: src/javascript/runtime/html5/Runtime.js
  5370. /**
  5371. * Runtime.js
  5372. *
  5373. * Copyright 2013, Moxiecode Systems AB
  5374. * Released under GPL License.
  5375. *
  5376. * License: http://www.plupload.com/license
  5377. * Contributing: http://www.plupload.com/contributing
  5378. */
  5379. /*global File:true */
  5380. /**
  5381. Defines constructor for HTML5 runtime.
  5382. @class moxie/runtime/html5/Runtime
  5383. @private
  5384. */
  5385. define("moxie/runtime/html5/Runtime", [
  5386. "moxie/core/utils/Basic",
  5387. "moxie/core/Exceptions",
  5388. "moxie/runtime/Runtime",
  5389. "moxie/core/utils/Env"
  5390. ], function(Basic, x, Runtime, Env) {
  5391. var type = "html5", extensions = {};
  5392. function Html5Runtime(options) {
  5393. var I = this
  5394. , Test = Runtime.capTest
  5395. , True = Runtime.capTrue
  5396. ;
  5397. var caps = Basic.extend({
  5398. access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL),
  5399. access_image_binary: function() {
  5400. return I.can('access_binary') && !!extensions.Image;
  5401. },
  5402. display_media: Test(
  5403. (Env.can('create_canvas') || Env.can('use_data_uri_over32kb')) &&
  5404. defined('moxie/image/Image')
  5405. ),
  5406. do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()),
  5407. drag_and_drop: Test(function() {
  5408. // this comes directly from Modernizr: http://www.modernizr.com/
  5409. var div = document.createElement('div');
  5410. // IE has support for drag and drop since version 5, but doesn't support dropping files from desktop
  5411. return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) &&
  5412. (Env.browser !== 'IE' || Env.verComp(Env.version, 9, '>'));
  5413. }()),
  5414. filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
  5415. return !(
  5416. (Env.browser === 'Chrome' && Env.verComp(Env.version, 28, '<')) ||
  5417. (Env.browser === 'IE' && Env.verComp(Env.version, 10, '<')) ||
  5418. (Env.browser === 'Safari' && Env.verComp(Env.version, 7, '<')) ||
  5419. (Env.browser === 'Firefox' && Env.verComp(Env.version, 37, '<'))
  5420. );
  5421. }()),
  5422. return_response_headers: True,
  5423. return_response_type: function(responseType) {
  5424. if (responseType === 'json' && !!window.JSON) { // we can fake this one even if it's not supported
  5425. return true;
  5426. }
  5427. return Env.can('return_response_type', responseType);
  5428. },
  5429. return_status_code: True,
  5430. report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload),
  5431. resize_image: function() {
  5432. return I.can('access_binary') && Env.can('create_canvas');
  5433. },
  5434. select_file: function() {
  5435. return Env.can('use_fileinput') && window.File;
  5436. },
  5437. select_folder: function() {
  5438. return I.can('select_file') && (
  5439. Env.browser === 'Chrome' && Env.verComp(Env.version, 21, '>=') ||
  5440. Env.browser === 'Firefox' && Env.verComp(Env.version, 42, '>=') // https://developer.mozilla.org/en-US/Firefox/Releases/42
  5441. );
  5442. },
  5443. select_multiple: function() {
  5444. // it is buggy on Safari Windows and iOS
  5445. return I.can('select_file') &&
  5446. !(Env.browser === 'Safari' && Env.os === 'Windows') &&
  5447. !(Env.os === 'iOS' && Env.verComp(Env.osVersion, "7.0.0", '>') && Env.verComp(Env.osVersion, "8.0.0", '<'));
  5448. },
  5449. send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))),
  5450. send_custom_headers: Test(window.XMLHttpRequest),
  5451. send_multipart: function() {
  5452. return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string');
  5453. },
  5454. slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)),
  5455. stream_upload: function(){
  5456. return I.can('slice_blob') && I.can('send_multipart');
  5457. },
  5458. summon_file_dialog: function() { // yeah... some dirty sniffing here...
  5459. return I.can('select_file') && (
  5460. (Env.browser === 'Firefox' && Env.verComp(Env.version, 4, '>=')) ||
  5461. (Env.browser === 'Opera' && Env.verComp(Env.version, 12, '>=')) ||
  5462. (Env.browser === 'IE' && Env.verComp(Env.version, 10, '>=')) ||
  5463. !!~Basic.inArray(Env.browser, ['Chrome', 'Safari', 'Edge'])
  5464. );
  5465. },
  5466. upload_filesize: True,
  5467. use_http_method: True
  5468. },
  5469. arguments[2]
  5470. );
  5471. Runtime.call(this, options, (arguments[1] || type), caps);
  5472. Basic.extend(this, {
  5473. init : function() {
  5474. this.trigger("Init");
  5475. },
  5476. destroy: (function(destroy) { // extend default destroy method
  5477. return function() {
  5478. destroy.call(I);
  5479. destroy = I = null;
  5480. };
  5481. }(this.destroy))
  5482. });
  5483. Basic.extend(this.getShim(), extensions);
  5484. }
  5485. Runtime.addConstructor(type, Html5Runtime);
  5486. return extensions;
  5487. });
  5488. // Included from: src/javascript/runtime/html5/file/Blob.js
  5489. /**
  5490. * Blob.js
  5491. *
  5492. * Copyright 2013, Moxiecode Systems AB
  5493. * Released under GPL License.
  5494. *
  5495. * License: http://www.plupload.com/license
  5496. * Contributing: http://www.plupload.com/contributing
  5497. */
  5498. /**
  5499. @class moxie/runtime/html5/file/Blob
  5500. @private
  5501. */
  5502. define("moxie/runtime/html5/file/Blob", [
  5503. "moxie/runtime/html5/Runtime",
  5504. "moxie/file/Blob"
  5505. ], function(extensions, Blob) {
  5506. function HTML5Blob() {
  5507. function w3cBlobSlice(blob, start, end) {
  5508. var blobSlice;
  5509. if (window.File.prototype.slice) {
  5510. try {
  5511. blob.slice(); // depricated version will throw WRONG_ARGUMENTS_ERR exception
  5512. return blob.slice(start, end);
  5513. } catch (e) {
  5514. // depricated slice method
  5515. return blob.slice(start, end - start);
  5516. }
  5517. // slice method got prefixed: https://bugzilla.mozilla.org/show_bug.cgi?id=649672
  5518. } else if ((blobSlice = window.File.prototype.webkitSlice || window.File.prototype.mozSlice)) {
  5519. return blobSlice.call(blob, start, end);
  5520. } else {
  5521. return null; // or throw some exception
  5522. }
  5523. }
  5524. this.slice = function() {
  5525. return new Blob(this.getRuntime().uid, w3cBlobSlice.apply(this, arguments));
  5526. };
  5527. }
  5528. return (extensions.Blob = HTML5Blob);
  5529. });
  5530. // Included from: src/javascript/core/utils/Events.js
  5531. /**
  5532. * Events.js
  5533. *
  5534. * Copyright 2013, Moxiecode Systems AB
  5535. * Released under GPL License.
  5536. *
  5537. * License: http://www.plupload.com/license
  5538. * Contributing: http://www.plupload.com/contributing
  5539. */
  5540. define('moxie/core/utils/Events', [
  5541. 'moxie/core/utils/Basic'
  5542. ], function(Basic) {
  5543. var eventhash = {}, uid = 'moxie_' + Basic.guid();
  5544. // IE W3C like event funcs
  5545. function preventDefault() {
  5546. this.returnValue = false;
  5547. }
  5548. function stopPropagation() {
  5549. this.cancelBubble = true;
  5550. }
  5551. /**
  5552. Adds an event handler to the specified object and store reference to the handler
  5553. in objects internal Plupload registry (@see removeEvent).
  5554. @method addEvent
  5555. @for Utils
  5556. @static
  5557. @param {Object} obj DOM element like object to add handler to.
  5558. @param {String} name Name to add event listener to.
  5559. @param {Function} callback Function to call when event occurs.
  5560. @param {String} [key] that might be used to add specifity to the event record.
  5561. */
  5562. var addEvent = function(obj, name, callback, key) {
  5563. var func, events;
  5564. name = name.toLowerCase();
  5565. // Add event listener
  5566. if (obj.addEventListener) {
  5567. func = callback;
  5568. obj.addEventListener(name, func, false);
  5569. } else if (obj.attachEvent) {
  5570. func = function() {
  5571. var evt = window.event;
  5572. if (!evt.target) {
  5573. evt.target = evt.srcElement;
  5574. }
  5575. evt.preventDefault = preventDefault;
  5576. evt.stopPropagation = stopPropagation;
  5577. callback(evt);
  5578. };
  5579. obj.attachEvent('on' + name, func);
  5580. }
  5581. // Log event handler to objects internal mOxie registry
  5582. if (!obj[uid]) {
  5583. obj[uid] = Basic.guid();
  5584. }
  5585. if (!eventhash.hasOwnProperty(obj[uid])) {
  5586. eventhash[obj[uid]] = {};
  5587. }
  5588. events = eventhash[obj[uid]];
  5589. if (!events.hasOwnProperty(name)) {
  5590. events[name] = [];
  5591. }
  5592. events[name].push({
  5593. func: func,
  5594. orig: callback, // store original callback for IE
  5595. key: key
  5596. });
  5597. };
  5598. /**
  5599. Remove event handler from the specified object. If third argument (callback)
  5600. is not specified remove all events with the specified name.
  5601. @method removeEvent
  5602. @static
  5603. @param {Object} obj DOM element to remove event listener(s) from.
  5604. @param {String} name Name of event listener to remove.
  5605. @param {Function|String} [callback] might be a callback or unique key to match.
  5606. */
  5607. var removeEvent = function(obj, name, callback) {
  5608. var type, undef;
  5609. name = name.toLowerCase();
  5610. if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) {
  5611. type = eventhash[obj[uid]][name];
  5612. } else {
  5613. return;
  5614. }
  5615. for (var i = type.length - 1; i >= 0; i--) {
  5616. // undefined or not, key should match
  5617. if (type[i].orig === callback || type[i].key === callback) {
  5618. if (obj.removeEventListener) {
  5619. obj.removeEventListener(name, type[i].func, false);
  5620. } else if (obj.detachEvent) {
  5621. obj.detachEvent('on'+name, type[i].func);
  5622. }
  5623. type[i].orig = null;
  5624. type[i].func = null;
  5625. type.splice(i, 1);
  5626. // If callback was passed we are done here, otherwise proceed
  5627. if (callback !== undef) {
  5628. break;
  5629. }
  5630. }
  5631. }
  5632. // If event array got empty, remove it
  5633. if (!type.length) {
  5634. delete eventhash[obj[uid]][name];
  5635. }
  5636. // If mOxie registry has become empty, remove it
  5637. if (Basic.isEmptyObj(eventhash[obj[uid]])) {
  5638. delete eventhash[obj[uid]];
  5639. // IE doesn't let you remove DOM object property with - delete
  5640. try {
  5641. delete obj[uid];
  5642. } catch(e) {
  5643. obj[uid] = undef;
  5644. }
  5645. }
  5646. };
  5647. /**
  5648. Remove all kind of events from the specified object
  5649. @method removeAllEvents
  5650. @static
  5651. @param {Object} obj DOM element to remove event listeners from.
  5652. @param {String} [key] unique key to match, when removing events.
  5653. */
  5654. var removeAllEvents = function(obj, key) {
  5655. if (!obj || !obj[uid]) {
  5656. return;
  5657. }
  5658. Basic.each(eventhash[obj[uid]], function(events, name) {
  5659. removeEvent(obj, name, key);
  5660. });
  5661. };
  5662. return {
  5663. addEvent: addEvent,
  5664. removeEvent: removeEvent,
  5665. removeAllEvents: removeAllEvents
  5666. };
  5667. });
  5668. // Included from: src/javascript/runtime/html5/file/FileInput.js
  5669. /**
  5670. * FileInput.js
  5671. *
  5672. * Copyright 2013, Moxiecode Systems AB
  5673. * Released under GPL License.
  5674. *
  5675. * License: http://www.plupload.com/license
  5676. * Contributing: http://www.plupload.com/contributing
  5677. */
  5678. /**
  5679. @class moxie/runtime/html5/file/FileInput
  5680. @private
  5681. */
  5682. define("moxie/runtime/html5/file/FileInput", [
  5683. "moxie/runtime/html5/Runtime",
  5684. "moxie/file/File",
  5685. "moxie/core/utils/Basic",
  5686. "moxie/core/utils/Dom",
  5687. "moxie/core/utils/Events",
  5688. "moxie/core/utils/Mime",
  5689. "moxie/core/utils/Env"
  5690. ], function(extensions, File, Basic, Dom, Events, Mime, Env) {
  5691. function FileInput() {
  5692. var _options, _browseBtnZIndex; // save original z-index
  5693. Basic.extend(this, {
  5694. init: function(options) {
  5695. var comp = this, I = comp.getRuntime(), input, shimContainer, mimes, browseButton, zIndex, top;
  5696. _options = options;
  5697. // figure out accept string
  5698. mimes = _options.accept.mimes || Mime.extList2mimes(_options.accept, I.can('filter_by_extension'));
  5699. shimContainer = I.getShimContainer();
  5700. shimContainer.innerHTML = '<input id="' + I.uid +'" type="file" style="font-size:999px;opacity:0;"' +
  5701. (_options.multiple && I.can('select_multiple') ? 'multiple' : '') +
  5702. (_options.directory && I.can('select_folder') ? 'webkitdirectory directory' : '') + // Chrome 11+
  5703. (mimes ? ' accept="' + mimes.join(',') + '"' : '') + ' />';
  5704. input = Dom.get(I.uid);
  5705. // prepare file input to be placed underneath the browse_button element
  5706. Basic.extend(input.style, {
  5707. position: 'absolute',
  5708. top: 0,
  5709. left: 0,
  5710. width: '100%',
  5711. height: '100%'
  5712. });
  5713. browseButton = Dom.get(_options.browse_button);
  5714. _browseBtnZIndex = Dom.getStyle(browseButton, 'z-index') || 'auto';
  5715. // Route click event to the input[type=file] element for browsers that support such behavior
  5716. if (I.can('summon_file_dialog')) {
  5717. if (Dom.getStyle(browseButton, 'position') === 'static') {
  5718. browseButton.style.position = 'relative';
  5719. }
  5720. Events.addEvent(browseButton, 'click', function(e) {
  5721. var input = Dom.get(I.uid);
  5722. if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file]
  5723. input.click();
  5724. }
  5725. e.preventDefault();
  5726. }, comp.uid);
  5727. comp.bind('Refresh', function() {
  5728. zIndex = parseInt(_browseBtnZIndex, 10) || 1;
  5729. Dom.get(_options.browse_button).style.zIndex = zIndex;
  5730. this.getRuntime().getShimContainer().style.zIndex = zIndex - 1;
  5731. });
  5732. }
  5733. /* Since we have to place input[type=file] on top of the browse_button for some browsers,
  5734. browse_button loses interactivity, so we restore it here */
  5735. top = I.can('summon_file_dialog') ? browseButton : shimContainer;
  5736. Events.addEvent(top, 'mouseover', function() {
  5737. comp.trigger('mouseenter');
  5738. }, comp.uid);
  5739. Events.addEvent(top, 'mouseout', function() {
  5740. comp.trigger('mouseleave');
  5741. }, comp.uid);
  5742. Events.addEvent(top, 'mousedown', function() {
  5743. comp.trigger('mousedown');
  5744. }, comp.uid);
  5745. Events.addEvent(Dom.get(_options.container), 'mouseup', function() {
  5746. comp.trigger('mouseup');
  5747. }, comp.uid);
  5748. input.onchange = function onChange(e) { // there should be only one handler for this
  5749. comp.files = [];
  5750. Basic.each(this.files, function(file) {
  5751. var relativePath = '';
  5752. if (_options.directory) {
  5753. // folders are represented by dots, filter them out (Chrome 11+)
  5754. if (file.name == ".") {
  5755. // if it looks like a folder...
  5756. return true;
  5757. }
  5758. }
  5759. if (file.webkitRelativePath) {
  5760. relativePath = '/' + file.webkitRelativePath.replace(/^\//, '');
  5761. }
  5762. file = new File(I.uid, file);
  5763. file.relativePath = relativePath;
  5764. comp.files.push(file);
  5765. });
  5766. // clearing the value enables the user to select the same file again if they want to
  5767. if (Env.browser !== 'IE' && Env.browser !== 'IEMobile') {
  5768. this.value = '';
  5769. } else {
  5770. // in IE input[type="file"] is read-only so the only way to reset it is to re-insert it
  5771. var clone = this.cloneNode(true);
  5772. this.parentNode.replaceChild(clone, this);
  5773. clone.onchange = onChange;
  5774. }
  5775. if (comp.files.length) {
  5776. comp.trigger('change');
  5777. }
  5778. };
  5779. // ready event is perfectly asynchronous
  5780. comp.trigger({
  5781. type: 'ready',
  5782. async: true
  5783. });
  5784. shimContainer = null;
  5785. },
  5786. setOption: function(name, value) {
  5787. var I = this.getRuntime();
  5788. var input = Dom.get(I.uid);
  5789. switch (name) {
  5790. case 'accept':
  5791. if (value) {
  5792. var mimes = value.mimes || Mime.extList2mimes(value, I.can('filter_by_extension'));
  5793. input.setAttribute('accept', mimes.join(','));
  5794. } else {
  5795. input.removeAttribute('accept');
  5796. }
  5797. break;
  5798. case 'directory':
  5799. if (value && I.can('select_folder')) {
  5800. input.setAttribute('directory', '');
  5801. input.setAttribute('webkitdirectory', '');
  5802. } else {
  5803. input.removeAttribute('directory');
  5804. input.removeAttribute('webkitdirectory');
  5805. }
  5806. break;
  5807. case 'multiple':
  5808. if (value && I.can('select_multiple')) {
  5809. input.setAttribute('multiple', '');
  5810. } else {
  5811. input.removeAttribute('multiple');
  5812. }
  5813. }
  5814. },
  5815. disable: function(state) {
  5816. var I = this.getRuntime(), input;
  5817. if ((input = Dom.get(I.uid))) {
  5818. input.disabled = !!state;
  5819. }
  5820. },
  5821. destroy: function() {
  5822. var I = this.getRuntime()
  5823. , shim = I.getShim()
  5824. , shimContainer = I.getShimContainer()
  5825. , container = _options && Dom.get(_options.container)
  5826. , browseButton = _options && Dom.get(_options.browse_button)
  5827. ;
  5828. if (container) {
  5829. Events.removeAllEvents(container, this.uid);
  5830. }
  5831. if (browseButton) {
  5832. Events.removeAllEvents(browseButton, this.uid);
  5833. browseButton.style.zIndex = _browseBtnZIndex; // reset to original value
  5834. }
  5835. if (shimContainer) {
  5836. Events.removeAllEvents(shimContainer, this.uid);
  5837. shimContainer.innerHTML = '';
  5838. }
  5839. shim.removeInstance(this.uid);
  5840. _options = shimContainer = container = browseButton = shim = null;
  5841. }
  5842. });
  5843. }
  5844. return (extensions.FileInput = FileInput);
  5845. });
  5846. // Included from: src/javascript/runtime/html5/file/FileDrop.js
  5847. /**
  5848. * FileDrop.js
  5849. *
  5850. * Copyright 2013, Moxiecode Systems AB
  5851. * Released under GPL License.
  5852. *
  5853. * License: http://www.plupload.com/license
  5854. * Contributing: http://www.plupload.com/contributing
  5855. */
  5856. /**
  5857. @class moxie/runtime/html5/file/FileDrop
  5858. @private
  5859. */
  5860. define("moxie/runtime/html5/file/FileDrop", [
  5861. "moxie/runtime/html5/Runtime",
  5862. 'moxie/file/File',
  5863. "moxie/core/utils/Basic",
  5864. "moxie/core/utils/Dom",
  5865. "moxie/core/utils/Events",
  5866. "moxie/core/utils/Mime"
  5867. ], function(extensions, File, Basic, Dom, Events, Mime) {
  5868. function FileDrop() {
  5869. var _files = [], _allowedExts = [], _options, _ruid;
  5870. Basic.extend(this, {
  5871. init: function(options) {
  5872. var comp = this, dropZone;
  5873. _options = options;
  5874. _ruid = comp.ruid; // every dropped-in file should have a reference to the runtime
  5875. _allowedExts = _extractExts(_options.accept);
  5876. dropZone = _options.container;
  5877. Events.addEvent(dropZone, 'dragover', function(e) {
  5878. if (!_hasFiles(e)) {
  5879. return;
  5880. }
  5881. e.preventDefault();
  5882. e.dataTransfer.dropEffect = 'copy';
  5883. }, comp.uid);
  5884. Events.addEvent(dropZone, 'drop', function(e) {
  5885. if (!_hasFiles(e)) {
  5886. return;
  5887. }
  5888. e.preventDefault();
  5889. _files = [];
  5890. // Chrome 21+ accepts folders via Drag'n'Drop
  5891. if (e.dataTransfer.items && e.dataTransfer.items[0].webkitGetAsEntry) {
  5892. _readItems(e.dataTransfer.items, function() {
  5893. comp.files = _files;
  5894. comp.trigger("drop");
  5895. });
  5896. } else {
  5897. Basic.each(e.dataTransfer.files, function(file) {
  5898. _addFile(file);
  5899. });
  5900. comp.files = _files;
  5901. comp.trigger("drop");
  5902. }
  5903. }, comp.uid);
  5904. Events.addEvent(dropZone, 'dragenter', function(e) {
  5905. comp.trigger("dragenter");
  5906. }, comp.uid);
  5907. Events.addEvent(dropZone, 'dragleave', function(e) {
  5908. comp.trigger("dragleave");
  5909. }, comp.uid);
  5910. },
  5911. destroy: function() {
  5912. Events.removeAllEvents(_options && Dom.get(_options.container), this.uid);
  5913. _ruid = _files = _allowedExts = _options = null;
  5914. }
  5915. });
  5916. function _hasFiles(e) {
  5917. if (!e.dataTransfer || !e.dataTransfer.types) { // e.dataTransfer.files is not available in Gecko during dragover
  5918. return false;
  5919. }
  5920. var types = Basic.toArray(e.dataTransfer.types || []);
  5921. return Basic.inArray("Files", types) !== -1 ||
  5922. Basic.inArray("public.file-url", types) !== -1 || // Safari < 5
  5923. Basic.inArray("application/x-moz-file", types) !== -1 // Gecko < 1.9.2 (< Firefox 3.6)
  5924. ;
  5925. }
  5926. function _addFile(file, relativePath) {
  5927. if (_isAcceptable(file)) {
  5928. var fileObj = new File(_ruid, file);
  5929. fileObj.relativePath = relativePath || '';
  5930. _files.push(fileObj);
  5931. }
  5932. }
  5933. function _extractExts(accept) {
  5934. var exts = [];
  5935. for (var i = 0; i < accept.length; i++) {
  5936. [].push.apply(exts, accept[i].extensions.split(/\s*,\s*/));
  5937. }
  5938. return Basic.inArray('*', exts) === -1 ? exts : [];
  5939. }
  5940. function _isAcceptable(file) {
  5941. if (!_allowedExts.length) {
  5942. return true;
  5943. }
  5944. var ext = Mime.getFileExtension(file.name);
  5945. return !ext || Basic.inArray(ext, _allowedExts) !== -1;
  5946. }
  5947. function _readItems(items, cb) {
  5948. var entries = [];
  5949. Basic.each(items, function(item) {
  5950. var entry = item.webkitGetAsEntry();
  5951. // Address #998 (https://code.google.com/p/chromium/issues/detail?id=332579)
  5952. if (entry) {
  5953. // file() fails on OSX when the filename contains a special character (e.g. umlaut): see #61
  5954. if (entry.isFile) {
  5955. _addFile(item.getAsFile(), entry.fullPath);
  5956. } else {
  5957. entries.push(entry);
  5958. }
  5959. }
  5960. });
  5961. if (entries.length) {
  5962. _readEntries(entries, cb);
  5963. } else {
  5964. cb();
  5965. }
  5966. }
  5967. function _readEntries(entries, cb) {
  5968. var queue = [];
  5969. Basic.each(entries, function(entry) {
  5970. queue.push(function(cbcb) {
  5971. _readEntry(entry, cbcb);
  5972. });
  5973. });
  5974. Basic.inSeries(queue, function() {
  5975. cb();
  5976. });
  5977. }
  5978. function _readEntry(entry, cb) {
  5979. if (entry.isFile) {
  5980. entry.file(function(file) {
  5981. _addFile(file, entry.fullPath);
  5982. cb();
  5983. }, function() {
  5984. // fire an error event maybe
  5985. cb();
  5986. });
  5987. } else if (entry.isDirectory) {
  5988. _readDirEntry(entry, cb);
  5989. } else {
  5990. cb(); // not file, not directory? what then?..
  5991. }
  5992. }
  5993. function _readDirEntry(dirEntry, cb) {
  5994. var entries = [], dirReader = dirEntry.createReader();
  5995. // keep quering recursively till no more entries
  5996. function getEntries(cbcb) {
  5997. dirReader.readEntries(function(moreEntries) {
  5998. if (moreEntries.length) {
  5999. [].push.apply(entries, moreEntries);
  6000. getEntries(cbcb);
  6001. } else {
  6002. cbcb();
  6003. }
  6004. }, cbcb);
  6005. }
  6006. // ...and you thought FileReader was crazy...
  6007. getEntries(function() {
  6008. _readEntries(entries, cb);
  6009. });
  6010. }
  6011. }
  6012. return (extensions.FileDrop = FileDrop);
  6013. });
  6014. // Included from: src/javascript/runtime/html5/file/FileReader.js
  6015. /**
  6016. * FileReader.js
  6017. *
  6018. * Copyright 2013, Moxiecode Systems AB
  6019. * Released under GPL License.
  6020. *
  6021. * License: http://www.plupload.com/license
  6022. * Contributing: http://www.plupload.com/contributing
  6023. */
  6024. /**
  6025. @class moxie/runtime/html5/file/FileReader
  6026. @private
  6027. */
  6028. define("moxie/runtime/html5/file/FileReader", [
  6029. "moxie/runtime/html5/Runtime",
  6030. "moxie/core/utils/Encode",
  6031. "moxie/core/utils/Basic"
  6032. ], function(extensions, Encode, Basic) {
  6033. function FileReader() {
  6034. var _fr, _convertToBinary = false;
  6035. Basic.extend(this, {
  6036. read: function(op, blob) {
  6037. var comp = this;
  6038. comp.result = '';
  6039. _fr = new window.FileReader();
  6040. _fr.addEventListener('progress', function(e) {
  6041. comp.trigger(e);
  6042. });
  6043. _fr.addEventListener('load', function(e) {
  6044. comp.result = _convertToBinary ? _toBinary(_fr.result) : _fr.result;
  6045. comp.trigger(e);
  6046. });
  6047. _fr.addEventListener('error', function(e) {
  6048. comp.trigger(e, _fr.error);
  6049. });
  6050. _fr.addEventListener('loadend', function(e) {
  6051. _fr = null;
  6052. comp.trigger(e);
  6053. });
  6054. if (Basic.typeOf(_fr[op]) === 'function') {
  6055. _convertToBinary = false;
  6056. _fr[op](blob.getSource());
  6057. } else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+
  6058. _convertToBinary = true;
  6059. _fr.readAsDataURL(blob.getSource());
  6060. }
  6061. },
  6062. abort: function() {
  6063. if (_fr) {
  6064. _fr.abort();
  6065. }
  6066. },
  6067. destroy: function() {
  6068. _fr = null;
  6069. }
  6070. });
  6071. function _toBinary(str) {
  6072. return Encode.atob(str.substring(str.indexOf('base64,') + 7));
  6073. }
  6074. }
  6075. return (extensions.FileReader = FileReader);
  6076. });
  6077. // Included from: src/javascript/runtime/html5/xhr/XMLHttpRequest.js
  6078. /**
  6079. * XMLHttpRequest.js
  6080. *
  6081. * Copyright 2013, Moxiecode Systems AB
  6082. * Released under GPL License.
  6083. *
  6084. * License: http://www.plupload.com/license
  6085. * Contributing: http://www.plupload.com/contributing
  6086. */
  6087. /*global ActiveXObject:true */
  6088. /**
  6089. @class moxie/runtime/html5/xhr/XMLHttpRequest
  6090. @private
  6091. */
  6092. define("moxie/runtime/html5/xhr/XMLHttpRequest", [
  6093. "moxie/runtime/html5/Runtime",
  6094. "moxie/core/utils/Basic",
  6095. "moxie/core/utils/Mime",
  6096. "moxie/core/utils/Url",
  6097. "moxie/file/File",
  6098. "moxie/file/Blob",
  6099. "moxie/xhr/FormData",
  6100. "moxie/core/Exceptions",
  6101. "moxie/core/utils/Env"
  6102. ], function(extensions, Basic, Mime, Url, File, Blob, FormData, x, Env) {
  6103. function XMLHttpRequest() {
  6104. var self = this
  6105. , _xhr
  6106. , _filename
  6107. ;
  6108. Basic.extend(this, {
  6109. send: function(meta, data) {
  6110. var target = this
  6111. , isGecko2_5_6 = (Env.browser === 'Mozilla' && Env.verComp(Env.version, 4, '>=') && Env.verComp(Env.version, 7, '<'))
  6112. , isAndroidBrowser = Env.browser === 'Android Browser'
  6113. , mustSendAsBinary = false
  6114. ;
  6115. // extract file name
  6116. _filename = meta.url.replace(/^.+?\/([\w\-\.]+)$/, '$1').toLowerCase();
  6117. _xhr = _getNativeXHR();
  6118. _xhr.open(meta.method, meta.url, meta.async, meta.user, meta.password);
  6119. // prepare data to be sent
  6120. if (data instanceof Blob) {
  6121. if (data.isDetached()) {
  6122. mustSendAsBinary = true;
  6123. }
  6124. data = data.getSource();
  6125. } else if (data instanceof FormData) {
  6126. if (data.hasBlob()) {
  6127. if (data.getBlob().isDetached()) {
  6128. data = _prepareMultipart.call(target, data); // _xhr must be instantiated and be in OPENED state
  6129. mustSendAsBinary = true;
  6130. } else if ((isGecko2_5_6 || isAndroidBrowser) && Basic.typeOf(data.getBlob().getSource()) === 'blob' && window.FileReader) {
  6131. // Gecko 2/5/6 can't send blob in FormData: https://bugzilla.mozilla.org/show_bug.cgi?id=649150
  6132. // Android browsers (default one and Dolphin) seem to have the same issue, see: #613
  6133. _preloadAndSend.call(target, meta, data);
  6134. return; // _preloadAndSend will reinvoke send() with transmutated FormData =%D
  6135. }
  6136. }
  6137. // transfer fields to real FormData
  6138. if (data instanceof FormData) { // if still a FormData, e.g. not mangled by _prepareMultipart()
  6139. var fd = new window.FormData();
  6140. data.each(function(value, name) {
  6141. if (value instanceof Blob) {
  6142. fd.append(name, value.getSource());
  6143. } else {
  6144. fd.append(name, value);
  6145. }
  6146. });
  6147. data = fd;
  6148. }
  6149. }
  6150. // if XHR L2
  6151. if (_xhr.upload) {
  6152. if (meta.withCredentials) {
  6153. _xhr.withCredentials = true;
  6154. }
  6155. _xhr.addEventListener('load', function(e) {
  6156. target.trigger(e);
  6157. });
  6158. _xhr.addEventListener('error', function(e) {
  6159. target.trigger(e);
  6160. });
  6161. // additionally listen to progress events
  6162. _xhr.addEventListener('progress', function(e) {
  6163. target.trigger(e);
  6164. });
  6165. _xhr.upload.addEventListener('progress', function(e) {
  6166. target.trigger({
  6167. type: 'UploadProgress',
  6168. loaded: e.loaded,
  6169. total: e.total
  6170. });
  6171. });
  6172. // ... otherwise simulate XHR L2
  6173. } else {
  6174. _xhr.onreadystatechange = function onReadyStateChange() {
  6175. // fake Level 2 events
  6176. switch (_xhr.readyState) {
  6177. case 1: // XMLHttpRequest.OPENED
  6178. // readystatechanged is fired twice for OPENED state (in IE and Mozilla) - neu
  6179. break;
  6180. // looks like HEADERS_RECEIVED (state 2) is not reported in Opera (or it's old versions) - neu
  6181. case 2: // XMLHttpRequest.HEADERS_RECEIVED
  6182. break;
  6183. case 3: // XMLHttpRequest.LOADING
  6184. // try to fire progress event for not XHR L2
  6185. var total, loaded;
  6186. try {
  6187. if (Url.hasSameOrigin(meta.url)) { // Content-Length not accessible for cross-domain on some browsers
  6188. total = _xhr.getResponseHeader('Content-Length') || 0; // old Safari throws an exception here
  6189. }
  6190. if (_xhr.responseText) { // responseText was introduced in IE7
  6191. loaded = _xhr.responseText.length;
  6192. }
  6193. } catch(ex) {
  6194. total = loaded = 0;
  6195. }
  6196. target.trigger({
  6197. type: 'progress',
  6198. lengthComputable: !!total,
  6199. total: parseInt(total, 10),
  6200. loaded: loaded
  6201. });
  6202. break;
  6203. case 4: // XMLHttpRequest.DONE
  6204. // release readystatechange handler (mostly for IE)
  6205. _xhr.onreadystatechange = function() {};
  6206. // usually status 0 is returned when server is unreachable, but FF also fails to status 0 for 408 timeout
  6207. if (_xhr.status === 0) {
  6208. target.trigger('error');
  6209. } else {
  6210. target.trigger('load');
  6211. }
  6212. break;
  6213. }
  6214. };
  6215. }
  6216. // set request headers
  6217. if (!Basic.isEmptyObj(meta.headers)) {
  6218. Basic.each(meta.headers, function(value, header) {
  6219. _xhr.setRequestHeader(header, value);
  6220. });
  6221. }
  6222. // request response type
  6223. if ("" !== meta.responseType && 'responseType' in _xhr) {
  6224. if ('json' === meta.responseType && !Env.can('return_response_type', 'json')) { // we can fake this one
  6225. _xhr.responseType = 'text';
  6226. } else {
  6227. _xhr.responseType = meta.responseType;
  6228. }
  6229. }
  6230. // send ...
  6231. if (!mustSendAsBinary) {
  6232. _xhr.send(data);
  6233. } else {
  6234. if (_xhr.sendAsBinary) { // Gecko
  6235. _xhr.sendAsBinary(data);
  6236. } else { // other browsers having support for typed arrays
  6237. (function() {
  6238. // mimic Gecko's sendAsBinary
  6239. var ui8a = new Uint8Array(data.length);
  6240. for (var i = 0; i < data.length; i++) {
  6241. ui8a[i] = (data.charCodeAt(i) & 0xff);
  6242. }
  6243. _xhr.send(ui8a.buffer);
  6244. }());
  6245. }
  6246. }
  6247. target.trigger('loadstart');
  6248. },
  6249. getStatus: function() {
  6250. // according to W3C spec it should return 0 for readyState < 3, but instead it throws an exception
  6251. try {
  6252. if (_xhr) {
  6253. return _xhr.status;
  6254. }
  6255. } catch(ex) {}
  6256. return 0;
  6257. },
  6258. getResponse: function(responseType) {
  6259. var I = this.getRuntime();
  6260. try {
  6261. switch (responseType) {
  6262. case 'blob':
  6263. var file = new File(I.uid, _xhr.response);
  6264. // try to extract file name from content-disposition if possible (might be - not, if CORS for example)
  6265. var disposition = _xhr.getResponseHeader('Content-Disposition');
  6266. if (disposition) {
  6267. // extract filename from response header if available
  6268. var match = disposition.match(/filename=([\'\"'])([^\1]+)\1/);
  6269. if (match) {
  6270. _filename = match[2];
  6271. }
  6272. }
  6273. file.name = _filename;
  6274. // pre-webkit Opera doesn't set type property on the blob response
  6275. if (!file.type) {
  6276. file.type = Mime.getFileMime(_filename);
  6277. }
  6278. return file;
  6279. case 'json':
  6280. if (!Env.can('return_response_type', 'json')) {
  6281. return _xhr.status === 200 && !!window.JSON ? JSON.parse(_xhr.responseText) : null;
  6282. }
  6283. return _xhr.response;
  6284. case 'document':
  6285. return _getDocument(_xhr);
  6286. default:
  6287. return _xhr.responseText !== '' ? _xhr.responseText : null; // against the specs, but for consistency across the runtimes
  6288. }
  6289. } catch(ex) {
  6290. return null;
  6291. }
  6292. },
  6293. getAllResponseHeaders: function() {
  6294. try {
  6295. return _xhr.getAllResponseHeaders();
  6296. } catch(ex) {}
  6297. return '';
  6298. },
  6299. abort: function() {
  6300. if (_xhr) {
  6301. _xhr.abort();
  6302. }
  6303. },
  6304. destroy: function() {
  6305. self = _filename = null;
  6306. }
  6307. });
  6308. // here we go... ugly fix for ugly bug
  6309. function _preloadAndSend(meta, data) {
  6310. var target = this, blob, fr;
  6311. // get original blob
  6312. blob = data.getBlob().getSource();
  6313. // preload blob in memory to be sent as binary string
  6314. fr = new window.FileReader();
  6315. fr.onload = function() {
  6316. // overwrite original blob
  6317. data.append(data.getBlobName(), new Blob(null, {
  6318. type: blob.type,
  6319. data: fr.result
  6320. }));
  6321. // invoke send operation again
  6322. self.send.call(target, meta, data);
  6323. };
  6324. fr.readAsBinaryString(blob);
  6325. }
  6326. function _getNativeXHR() {
  6327. if (window.XMLHttpRequest && !(Env.browser === 'IE' && Env.verComp(Env.version, 8, '<'))) { // IE7 has native XHR but it's buggy
  6328. return new window.XMLHttpRequest();
  6329. } else {
  6330. return (function() {
  6331. var progIDs = ['Msxml2.XMLHTTP.6.0', 'Microsoft.XMLHTTP']; // if 6.0 available, use it, otherwise failback to default 3.0
  6332. for (var i = 0; i < progIDs.length; i++) {
  6333. try {
  6334. return new ActiveXObject(progIDs[i]);
  6335. } catch (ex) {}
  6336. }
  6337. })();
  6338. }
  6339. }
  6340. // @credits Sergey Ilinsky (http://www.ilinsky.com/)
  6341. function _getDocument(xhr) {
  6342. var rXML = xhr.responseXML;
  6343. var rText = xhr.responseText;
  6344. // Try parsing responseText (@see: http://www.ilinsky.com/articles/XMLHttpRequest/#bugs-ie-responseXML-content-type)
  6345. if (Env.browser === 'IE' && rText && rXML && !rXML.documentElement && /[^\/]+\/[^\+]+\+xml/.test(xhr.getResponseHeader("Content-Type"))) {
  6346. rXML = new window.ActiveXObject("Microsoft.XMLDOM");
  6347. rXML.async = false;
  6348. rXML.validateOnParse = false;
  6349. rXML.loadXML(rText);
  6350. }
  6351. // Check if there is no error in document
  6352. if (rXML) {
  6353. if ((Env.browser === 'IE' && rXML.parseError !== 0) || !rXML.documentElement || rXML.documentElement.tagName === "parsererror") {
  6354. return null;
  6355. }
  6356. }
  6357. return rXML;
  6358. }
  6359. function _prepareMultipart(fd) {
  6360. var boundary = '----moxieboundary' + new Date().getTime()
  6361. , dashdash = '--'
  6362. , crlf = '\r\n'
  6363. , multipart = ''
  6364. , I = this.getRuntime()
  6365. ;
  6366. if (!I.can('send_binary_string')) {
  6367. throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
  6368. }
  6369. _xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
  6370. // append multipart parameters
  6371. fd.each(function(value, name) {
  6372. // Firefox 3.6 failed to convert multibyte characters to UTF-8 in sendAsBinary(),
  6373. // so we try it here ourselves with: unescape(encodeURIComponent(value))
  6374. if (value instanceof Blob) {
  6375. // Build RFC2388 blob
  6376. multipart += dashdash + boundary + crlf +
  6377. 'Content-Disposition: form-data; name="' + name + '"; filename="' + unescape(encodeURIComponent(value.name || 'blob')) + '"' + crlf +
  6378. 'Content-Type: ' + (value.type || 'application/octet-stream') + crlf + crlf +
  6379. value.getSource() + crlf;
  6380. } else {
  6381. multipart += dashdash + boundary + crlf +
  6382. 'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf +
  6383. unescape(encodeURIComponent(value)) + crlf;
  6384. }
  6385. });
  6386. multipart += dashdash + boundary + dashdash + crlf;
  6387. return multipart;
  6388. }
  6389. }
  6390. return (extensions.XMLHttpRequest = XMLHttpRequest);
  6391. });
  6392. // Included from: src/javascript/runtime/html5/utils/BinaryReader.js
  6393. /**
  6394. * BinaryReader.js
  6395. *
  6396. * Copyright 2013, Moxiecode Systems AB
  6397. * Released under GPL License.
  6398. *
  6399. * License: http://www.plupload.com/license
  6400. * Contributing: http://www.plupload.com/contributing
  6401. */
  6402. /**
  6403. @class moxie/runtime/html5/utils/BinaryReader
  6404. @private
  6405. */
  6406. define("moxie/runtime/html5/utils/BinaryReader", [
  6407. "moxie/core/utils/Basic"
  6408. ], function(Basic) {
  6409. function BinaryReader(data) {
  6410. if (data instanceof ArrayBuffer) {
  6411. ArrayBufferReader.apply(this, arguments);
  6412. } else {
  6413. UTF16StringReader.apply(this, arguments);
  6414. }
  6415. }
  6416. Basic.extend(BinaryReader.prototype, {
  6417. littleEndian: false,
  6418. read: function(idx, size) {
  6419. var sum, mv, i;
  6420. if (idx + size > this.length()) {
  6421. throw new Error("You are trying to read outside the source boundaries.");
  6422. }
  6423. mv = this.littleEndian
  6424. ? 0
  6425. : -8 * (size - 1)
  6426. ;
  6427. for (i = 0, sum = 0; i < size; i++) {
  6428. sum |= (this.readByteAt(idx + i) << Math.abs(mv + i*8));
  6429. }
  6430. return sum;
  6431. },
  6432. write: function(idx, num, size) {
  6433. var mv, i, str = '';
  6434. if (idx > this.length()) {
  6435. throw new Error("You are trying to write outside the source boundaries.");
  6436. }
  6437. mv = this.littleEndian
  6438. ? 0
  6439. : -8 * (size - 1)
  6440. ;
  6441. for (i = 0; i < size; i++) {
  6442. this.writeByteAt(idx + i, (num >> Math.abs(mv + i*8)) & 255);
  6443. }
  6444. },
  6445. BYTE: function(idx) {
  6446. return this.read(idx, 1);
  6447. },
  6448. SHORT: function(idx) {
  6449. return this.read(idx, 2);
  6450. },
  6451. LONG: function(idx) {
  6452. return this.read(idx, 4);
  6453. },
  6454. SLONG: function(idx) { // 2's complement notation
  6455. var num = this.read(idx, 4);
  6456. return (num > 2147483647 ? num - 4294967296 : num);
  6457. },
  6458. CHAR: function(idx) {
  6459. return String.fromCharCode(this.read(idx, 1));
  6460. },
  6461. STRING: function(idx, count) {
  6462. return this.asArray('CHAR', idx, count).join('');
  6463. },
  6464. asArray: function(type, idx, count) {
  6465. var values = [];
  6466. for (var i = 0; i < count; i++) {
  6467. values[i] = this[type](idx + i);
  6468. }
  6469. return values;
  6470. }
  6471. });
  6472. function ArrayBufferReader(data) {
  6473. var _dv = new DataView(data);
  6474. Basic.extend(this, {
  6475. readByteAt: function(idx) {
  6476. return _dv.getUint8(idx);
  6477. },
  6478. writeByteAt: function(idx, value) {
  6479. _dv.setUint8(idx, value);
  6480. },
  6481. SEGMENT: function(idx, size, value) {
  6482. switch (arguments.length) {
  6483. case 2:
  6484. return data.slice(idx, idx + size);
  6485. case 1:
  6486. return data.slice(idx);
  6487. case 3:
  6488. if (value === null) {
  6489. value = new ArrayBuffer();
  6490. }
  6491. if (value instanceof ArrayBuffer) {
  6492. var arr = new Uint8Array(this.length() - size + value.byteLength);
  6493. if (idx > 0) {
  6494. arr.set(new Uint8Array(data.slice(0, idx)), 0);
  6495. }
  6496. arr.set(new Uint8Array(value), idx);
  6497. arr.set(new Uint8Array(data.slice(idx + size)), idx + value.byteLength);
  6498. this.clear();
  6499. data = arr.buffer;
  6500. _dv = new DataView(data);
  6501. break;
  6502. }
  6503. default: return data;
  6504. }
  6505. },
  6506. length: function() {
  6507. return data ? data.byteLength : 0;
  6508. },
  6509. clear: function() {
  6510. _dv = data = null;
  6511. }
  6512. });
  6513. }
  6514. function UTF16StringReader(data) {
  6515. Basic.extend(this, {
  6516. readByteAt: function(idx) {
  6517. return data.charCodeAt(idx);
  6518. },
  6519. writeByteAt: function(idx, value) {
  6520. putstr(String.fromCharCode(value), idx, 1);
  6521. },
  6522. SEGMENT: function(idx, length, segment) {
  6523. switch (arguments.length) {
  6524. case 1:
  6525. return data.substr(idx);
  6526. case 2:
  6527. return data.substr(idx, length);
  6528. case 3:
  6529. putstr(segment !== null ? segment : '', idx, length);
  6530. break;
  6531. default: return data;
  6532. }
  6533. },
  6534. length: function() {
  6535. return data ? data.length : 0;
  6536. },
  6537. clear: function() {
  6538. data = null;
  6539. }
  6540. });
  6541. function putstr(segment, idx, length) {
  6542. length = arguments.length === 3 ? length : data.length - idx - 1;
  6543. data = data.substr(0, idx) + segment + data.substr(length + idx);
  6544. }
  6545. }
  6546. return BinaryReader;
  6547. });
  6548. // Included from: src/javascript/runtime/html5/image/JPEGHeaders.js
  6549. /**
  6550. * JPEGHeaders.js
  6551. *
  6552. * Copyright 2013, Moxiecode Systems AB
  6553. * Released under GPL License.
  6554. *
  6555. * License: http://www.plupload.com/license
  6556. * Contributing: http://www.plupload.com/contributing
  6557. */
  6558. /**
  6559. @class moxie/runtime/html5/image/JPEGHeaders
  6560. @private
  6561. */
  6562. define("moxie/runtime/html5/image/JPEGHeaders", [
  6563. "moxie/runtime/html5/utils/BinaryReader",
  6564. "moxie/core/Exceptions"
  6565. ], function(BinaryReader, x) {
  6566. return function JPEGHeaders(data) {
  6567. var headers = [], _br, idx, marker, length = 0;
  6568. _br = new BinaryReader(data);
  6569. // Check if data is jpeg
  6570. if (_br.SHORT(0) !== 0xFFD8) {
  6571. _br.clear();
  6572. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  6573. }
  6574. idx = 2;
  6575. while (idx <= _br.length()) {
  6576. marker = _br.SHORT(idx);
  6577. // omit RST (restart) markers
  6578. if (marker >= 0xFFD0 && marker <= 0xFFD7) {
  6579. idx += 2;
  6580. continue;
  6581. }
  6582. // no headers allowed after SOS marker
  6583. if (marker === 0xFFDA || marker === 0xFFD9) {
  6584. break;
  6585. }
  6586. length = _br.SHORT(idx + 2) + 2;
  6587. // APPn marker detected
  6588. if (marker >= 0xFFE1 && marker <= 0xFFEF) {
  6589. headers.push({
  6590. hex: marker,
  6591. name: 'APP' + (marker & 0x000F),
  6592. start: idx,
  6593. length: length,
  6594. segment: _br.SEGMENT(idx, length)
  6595. });
  6596. }
  6597. idx += length;
  6598. }
  6599. _br.clear();
  6600. return {
  6601. headers: headers,
  6602. restore: function(data) {
  6603. var max, i, br;
  6604. br = new BinaryReader(data);
  6605. idx = br.SHORT(2) == 0xFFE0 ? 4 + br.SHORT(4) : 2;
  6606. for (i = 0, max = headers.length; i < max; i++) {
  6607. br.SEGMENT(idx, 0, headers[i].segment);
  6608. idx += headers[i].length;
  6609. }
  6610. data = br.SEGMENT();
  6611. br.clear();
  6612. return data;
  6613. },
  6614. strip: function(data) {
  6615. var br, headers, jpegHeaders, i;
  6616. jpegHeaders = new JPEGHeaders(data);
  6617. headers = jpegHeaders.headers;
  6618. jpegHeaders.purge();
  6619. br = new BinaryReader(data);
  6620. i = headers.length;
  6621. while (i--) {
  6622. br.SEGMENT(headers[i].start, headers[i].length, '');
  6623. }
  6624. data = br.SEGMENT();
  6625. br.clear();
  6626. return data;
  6627. },
  6628. get: function(name) {
  6629. var array = [];
  6630. for (var i = 0, max = headers.length; i < max; i++) {
  6631. if (headers[i].name === name.toUpperCase()) {
  6632. array.push(headers[i].segment);
  6633. }
  6634. }
  6635. return array;
  6636. },
  6637. set: function(name, segment) {
  6638. var array = [], i, ii, max;
  6639. if (typeof(segment) === 'string') {
  6640. array.push(segment);
  6641. } else {
  6642. array = segment;
  6643. }
  6644. for (i = ii = 0, max = headers.length; i < max; i++) {
  6645. if (headers[i].name === name.toUpperCase()) {
  6646. headers[i].segment = array[ii];
  6647. headers[i].length = array[ii].length;
  6648. ii++;
  6649. }
  6650. if (ii >= array.length) {
  6651. break;
  6652. }
  6653. }
  6654. },
  6655. purge: function() {
  6656. this.headers = headers = [];
  6657. }
  6658. };
  6659. };
  6660. });
  6661. // Included from: src/javascript/runtime/html5/image/ExifParser.js
  6662. /**
  6663. * ExifParser.js
  6664. *
  6665. * Copyright 2013, Moxiecode Systems AB
  6666. * Released under GPL License.
  6667. *
  6668. * License: http://www.plupload.com/license
  6669. * Contributing: http://www.plupload.com/contributing
  6670. */
  6671. /**
  6672. @class moxie/runtime/html5/image/ExifParser
  6673. @private
  6674. */
  6675. define("moxie/runtime/html5/image/ExifParser", [
  6676. "moxie/core/utils/Basic",
  6677. "moxie/runtime/html5/utils/BinaryReader",
  6678. "moxie/core/Exceptions"
  6679. ], function(Basic, BinaryReader, x) {
  6680. function ExifParser(data) {
  6681. var __super__, tags, tagDescs, offsets, idx, Tiff;
  6682. BinaryReader.call(this, data);
  6683. tags = {
  6684. tiff: {
  6685. /*
  6686. The image orientation viewed in terms of rows and columns.
  6687. 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
  6688. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
  6689. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
  6690. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
  6691. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
  6692. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
  6693. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
  6694. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
  6695. */
  6696. 0x0112: 'Orientation',
  6697. 0x010E: 'ImageDescription',
  6698. 0x010F: 'Make',
  6699. 0x0110: 'Model',
  6700. 0x0131: 'Software',
  6701. 0x8769: 'ExifIFDPointer',
  6702. 0x8825: 'GPSInfoIFDPointer'
  6703. },
  6704. exif: {
  6705. 0x9000: 'ExifVersion',
  6706. 0xA001: 'ColorSpace',
  6707. 0xA002: 'PixelXDimension',
  6708. 0xA003: 'PixelYDimension',
  6709. 0x9003: 'DateTimeOriginal',
  6710. 0x829A: 'ExposureTime',
  6711. 0x829D: 'FNumber',
  6712. 0x8827: 'ISOSpeedRatings',
  6713. 0x9201: 'ShutterSpeedValue',
  6714. 0x9202: 'ApertureValue' ,
  6715. 0x9207: 'MeteringMode',
  6716. 0x9208: 'LightSource',
  6717. 0x9209: 'Flash',
  6718. 0x920A: 'FocalLength',
  6719. 0xA402: 'ExposureMode',
  6720. 0xA403: 'WhiteBalance',
  6721. 0xA406: 'SceneCaptureType',
  6722. 0xA404: 'DigitalZoomRatio',
  6723. 0xA408: 'Contrast',
  6724. 0xA409: 'Saturation',
  6725. 0xA40A: 'Sharpness'
  6726. },
  6727. gps: {
  6728. 0x0000: 'GPSVersionID',
  6729. 0x0001: 'GPSLatitudeRef',
  6730. 0x0002: 'GPSLatitude',
  6731. 0x0003: 'GPSLongitudeRef',
  6732. 0x0004: 'GPSLongitude'
  6733. },
  6734. thumb: {
  6735. 0x0201: 'JPEGInterchangeFormat',
  6736. 0x0202: 'JPEGInterchangeFormatLength'
  6737. }
  6738. };
  6739. tagDescs = {
  6740. 'ColorSpace': {
  6741. 1: 'sRGB',
  6742. 0: 'Uncalibrated'
  6743. },
  6744. 'MeteringMode': {
  6745. 0: 'Unknown',
  6746. 1: 'Average',
  6747. 2: 'CenterWeightedAverage',
  6748. 3: 'Spot',
  6749. 4: 'MultiSpot',
  6750. 5: 'Pattern',
  6751. 6: 'Partial',
  6752. 255: 'Other'
  6753. },
  6754. 'LightSource': {
  6755. 1: 'Daylight',
  6756. 2: 'Fliorescent',
  6757. 3: 'Tungsten',
  6758. 4: 'Flash',
  6759. 9: 'Fine weather',
  6760. 10: 'Cloudy weather',
  6761. 11: 'Shade',
  6762. 12: 'Daylight fluorescent (D 5700 - 7100K)',
  6763. 13: 'Day white fluorescent (N 4600 -5400K)',
  6764. 14: 'Cool white fluorescent (W 3900 - 4500K)',
  6765. 15: 'White fluorescent (WW 3200 - 3700K)',
  6766. 17: 'Standard light A',
  6767. 18: 'Standard light B',
  6768. 19: 'Standard light C',
  6769. 20: 'D55',
  6770. 21: 'D65',
  6771. 22: 'D75',
  6772. 23: 'D50',
  6773. 24: 'ISO studio tungsten',
  6774. 255: 'Other'
  6775. },
  6776. 'Flash': {
  6777. 0x0000: 'Flash did not fire',
  6778. 0x0001: 'Flash fired',
  6779. 0x0005: 'Strobe return light not detected',
  6780. 0x0007: 'Strobe return light detected',
  6781. 0x0009: 'Flash fired, compulsory flash mode',
  6782. 0x000D: 'Flash fired, compulsory flash mode, return light not detected',
  6783. 0x000F: 'Flash fired, compulsory flash mode, return light detected',
  6784. 0x0010: 'Flash did not fire, compulsory flash mode',
  6785. 0x0018: 'Flash did not fire, auto mode',
  6786. 0x0019: 'Flash fired, auto mode',
  6787. 0x001D: 'Flash fired, auto mode, return light not detected',
  6788. 0x001F: 'Flash fired, auto mode, return light detected',
  6789. 0x0020: 'No flash function',
  6790. 0x0041: 'Flash fired, red-eye reduction mode',
  6791. 0x0045: 'Flash fired, red-eye reduction mode, return light not detected',
  6792. 0x0047: 'Flash fired, red-eye reduction mode, return light detected',
  6793. 0x0049: 'Flash fired, compulsory flash mode, red-eye reduction mode',
  6794. 0x004D: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected',
  6795. 0x004F: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected',
  6796. 0x0059: 'Flash fired, auto mode, red-eye reduction mode',
  6797. 0x005D: 'Flash fired, auto mode, return light not detected, red-eye reduction mode',
  6798. 0x005F: 'Flash fired, auto mode, return light detected, red-eye reduction mode'
  6799. },
  6800. 'ExposureMode': {
  6801. 0: 'Auto exposure',
  6802. 1: 'Manual exposure',
  6803. 2: 'Auto bracket'
  6804. },
  6805. 'WhiteBalance': {
  6806. 0: 'Auto white balance',
  6807. 1: 'Manual white balance'
  6808. },
  6809. 'SceneCaptureType': {
  6810. 0: 'Standard',
  6811. 1: 'Landscape',
  6812. 2: 'Portrait',
  6813. 3: 'Night scene'
  6814. },
  6815. 'Contrast': {
  6816. 0: 'Normal',
  6817. 1: 'Soft',
  6818. 2: 'Hard'
  6819. },
  6820. 'Saturation': {
  6821. 0: 'Normal',
  6822. 1: 'Low saturation',
  6823. 2: 'High saturation'
  6824. },
  6825. 'Sharpness': {
  6826. 0: 'Normal',
  6827. 1: 'Soft',
  6828. 2: 'Hard'
  6829. },
  6830. // GPS related
  6831. 'GPSLatitudeRef': {
  6832. N: 'North latitude',
  6833. S: 'South latitude'
  6834. },
  6835. 'GPSLongitudeRef': {
  6836. E: 'East longitude',
  6837. W: 'West longitude'
  6838. }
  6839. };
  6840. offsets = {
  6841. tiffHeader: 10
  6842. };
  6843. idx = offsets.tiffHeader;
  6844. __super__ = {
  6845. clear: this.clear
  6846. };
  6847. // Public functions
  6848. Basic.extend(this, {
  6849. read: function() {
  6850. try {
  6851. return ExifParser.prototype.read.apply(this, arguments);
  6852. } catch (ex) {
  6853. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  6854. }
  6855. },
  6856. write: function() {
  6857. try {
  6858. return ExifParser.prototype.write.apply(this, arguments);
  6859. } catch (ex) {
  6860. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  6861. }
  6862. },
  6863. UNDEFINED: function() {
  6864. return this.BYTE.apply(this, arguments);
  6865. },
  6866. RATIONAL: function(idx) {
  6867. return this.LONG(idx) / this.LONG(idx + 4)
  6868. },
  6869. SRATIONAL: function(idx) {
  6870. return this.SLONG(idx) / this.SLONG(idx + 4)
  6871. },
  6872. ASCII: function(idx) {
  6873. return this.CHAR(idx);
  6874. },
  6875. TIFF: function() {
  6876. return Tiff || null;
  6877. },
  6878. EXIF: function() {
  6879. var Exif = null;
  6880. if (offsets.exifIFD) {
  6881. try {
  6882. Exif = extractTags.call(this, offsets.exifIFD, tags.exif);
  6883. } catch(ex) {
  6884. return null;
  6885. }
  6886. // Fix formatting of some tags
  6887. if (Exif.ExifVersion && Basic.typeOf(Exif.ExifVersion) === 'array') {
  6888. for (var i = 0, exifVersion = ''; i < Exif.ExifVersion.length; i++) {
  6889. exifVersion += String.fromCharCode(Exif.ExifVersion[i]);
  6890. }
  6891. Exif.ExifVersion = exifVersion;
  6892. }
  6893. }
  6894. return Exif;
  6895. },
  6896. GPS: function() {
  6897. var GPS = null;
  6898. if (offsets.gpsIFD) {
  6899. try {
  6900. GPS = extractTags.call(this, offsets.gpsIFD, tags.gps);
  6901. } catch (ex) {
  6902. return null;
  6903. }
  6904. // iOS devices (and probably some others) do not put in GPSVersionID tag (why?..)
  6905. if (GPS.GPSVersionID && Basic.typeOf(GPS.GPSVersionID) === 'array') {
  6906. GPS.GPSVersionID = GPS.GPSVersionID.join('.');
  6907. }
  6908. }
  6909. return GPS;
  6910. },
  6911. thumb: function() {
  6912. if (offsets.IFD1) {
  6913. try {
  6914. var IFD1Tags = extractTags.call(this, offsets.IFD1, tags.thumb);
  6915. if ('JPEGInterchangeFormat' in IFD1Tags) {
  6916. return this.SEGMENT(offsets.tiffHeader + IFD1Tags.JPEGInterchangeFormat, IFD1Tags.JPEGInterchangeFormatLength);
  6917. }
  6918. } catch (ex) {}
  6919. }
  6920. return null;
  6921. },
  6922. setExif: function(tag, value) {
  6923. // Right now only setting of width/height is possible
  6924. if (tag !== 'PixelXDimension' && tag !== 'PixelYDimension') { return false; }
  6925. return setTag.call(this, 'exif', tag, value);
  6926. },
  6927. clear: function() {
  6928. __super__.clear();
  6929. data = tags = tagDescs = Tiff = offsets = __super__ = null;
  6930. }
  6931. });
  6932. // Check if that's APP1 and that it has EXIF
  6933. if (this.SHORT(0) !== 0xFFE1 || this.STRING(4, 5).toUpperCase() !== "EXIF\0") {
  6934. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  6935. }
  6936. // Set read order of multi-byte data
  6937. this.littleEndian = (this.SHORT(idx) == 0x4949);
  6938. // Check if always present bytes are indeed present
  6939. if (this.SHORT(idx+=2) !== 0x002A) {
  6940. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  6941. }
  6942. offsets.IFD0 = offsets.tiffHeader + this.LONG(idx += 2);
  6943. Tiff = extractTags.call(this, offsets.IFD0, tags.tiff);
  6944. if ('ExifIFDPointer' in Tiff) {
  6945. offsets.exifIFD = offsets.tiffHeader + Tiff.ExifIFDPointer;
  6946. delete Tiff.ExifIFDPointer;
  6947. }
  6948. if ('GPSInfoIFDPointer' in Tiff) {
  6949. offsets.gpsIFD = offsets.tiffHeader + Tiff.GPSInfoIFDPointer;
  6950. delete Tiff.GPSInfoIFDPointer;
  6951. }
  6952. if (Basic.isEmptyObj(Tiff)) {
  6953. Tiff = null;
  6954. }
  6955. // check if we have a thumb as well
  6956. var IFD1Offset = this.LONG(offsets.IFD0 + this.SHORT(offsets.IFD0) * 12 + 2);
  6957. if (IFD1Offset) {
  6958. offsets.IFD1 = offsets.tiffHeader + IFD1Offset;
  6959. }
  6960. function extractTags(IFD_offset, tags2extract) {
  6961. var data = this;
  6962. var length, i, tag, type, count, size, offset, value, values = [], hash = {};
  6963. var types = {
  6964. 1 : 'BYTE',
  6965. 7 : 'UNDEFINED',
  6966. 2 : 'ASCII',
  6967. 3 : 'SHORT',
  6968. 4 : 'LONG',
  6969. 5 : 'RATIONAL',
  6970. 9 : 'SLONG',
  6971. 10: 'SRATIONAL'
  6972. };
  6973. var sizes = {
  6974. 'BYTE' : 1,
  6975. 'UNDEFINED' : 1,
  6976. 'ASCII' : 1,
  6977. 'SHORT' : 2,
  6978. 'LONG' : 4,
  6979. 'RATIONAL' : 8,
  6980. 'SLONG' : 4,
  6981. 'SRATIONAL' : 8
  6982. };
  6983. length = data.SHORT(IFD_offset);
  6984. // The size of APP1 including all these elements shall not exceed the 64 Kbytes specified in the JPEG standard.
  6985. for (i = 0; i < length; i++) {
  6986. values = [];
  6987. // Set binary reader pointer to beginning of the next tag
  6988. offset = IFD_offset + 2 + i*12;
  6989. tag = tags2extract[data.SHORT(offset)];
  6990. if (tag === undefined) {
  6991. continue; // Not the tag we requested
  6992. }
  6993. type = types[data.SHORT(offset+=2)];
  6994. count = data.LONG(offset+=2);
  6995. size = sizes[type];
  6996. if (!size) {
  6997. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  6998. }
  6999. offset += 4;
  7000. // tag can only fit 4 bytes of data, if data is larger we should look outside
  7001. if (size * count > 4) {
  7002. // instead of data tag contains an offset of the data
  7003. offset = data.LONG(offset) + offsets.tiffHeader;
  7004. }
  7005. // in case we left the boundaries of data throw an early exception
  7006. if (offset + size * count >= this.length()) {
  7007. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  7008. }
  7009. // special care for the string
  7010. if (type === 'ASCII') {
  7011. hash[tag] = Basic.trim(data.STRING(offset, count).replace(/\0$/, '')); // strip trailing NULL
  7012. continue;
  7013. } else {
  7014. values = data.asArray(type, offset, count);
  7015. value = (count == 1 ? values[0] : values);
  7016. if (tagDescs.hasOwnProperty(tag) && typeof value != 'object') {
  7017. hash[tag] = tagDescs[tag][value];
  7018. } else {
  7019. hash[tag] = value;
  7020. }
  7021. }
  7022. }
  7023. return hash;
  7024. }
  7025. // At the moment only setting of simple (LONG) values, that do not require offset recalculation, is supported
  7026. function setTag(ifd, tag, value) {
  7027. var offset, length, tagOffset, valueOffset = 0;
  7028. // If tag name passed translate into hex key
  7029. if (typeof(tag) === 'string') {
  7030. var tmpTags = tags[ifd.toLowerCase()];
  7031. for (var hex in tmpTags) {
  7032. if (tmpTags[hex] === tag) {
  7033. tag = hex;
  7034. break;
  7035. }
  7036. }
  7037. }
  7038. offset = offsets[ifd.toLowerCase() + 'IFD'];
  7039. length = this.SHORT(offset);
  7040. for (var i = 0; i < length; i++) {
  7041. tagOffset = offset + 12 * i + 2;
  7042. if (this.SHORT(tagOffset) == tag) {
  7043. valueOffset = tagOffset + 8;
  7044. break;
  7045. }
  7046. }
  7047. if (!valueOffset) {
  7048. return false;
  7049. }
  7050. try {
  7051. this.write(valueOffset, value, 4);
  7052. } catch(ex) {
  7053. return false;
  7054. }
  7055. return true;
  7056. }
  7057. }
  7058. ExifParser.prototype = BinaryReader.prototype;
  7059. return ExifParser;
  7060. });
  7061. // Included from: src/javascript/runtime/html5/image/JPEG.js
  7062. /**
  7063. * JPEG.js
  7064. *
  7065. * Copyright 2013, Moxiecode Systems AB
  7066. * Released under GPL License.
  7067. *
  7068. * License: http://www.plupload.com/license
  7069. * Contributing: http://www.plupload.com/contributing
  7070. */
  7071. /**
  7072. @class moxie/runtime/html5/image/JPEG
  7073. @private
  7074. */
  7075. define("moxie/runtime/html5/image/JPEG", [
  7076. "moxie/core/utils/Basic",
  7077. "moxie/core/Exceptions",
  7078. "moxie/runtime/html5/image/JPEGHeaders",
  7079. "moxie/runtime/html5/utils/BinaryReader",
  7080. "moxie/runtime/html5/image/ExifParser"
  7081. ], function(Basic, x, JPEGHeaders, BinaryReader, ExifParser) {
  7082. function JPEG(data) {
  7083. var _br, _hm, _ep, _info;
  7084. _br = new BinaryReader(data);
  7085. // check if it is jpeg
  7086. if (_br.SHORT(0) !== 0xFFD8) {
  7087. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  7088. }
  7089. // backup headers
  7090. _hm = new JPEGHeaders(data);
  7091. // extract exif info
  7092. try {
  7093. _ep = new ExifParser(_hm.get('app1')[0]);
  7094. } catch(ex) {}
  7095. // get dimensions
  7096. _info = _getDimensions.call(this);
  7097. Basic.extend(this, {
  7098. type: 'image/jpeg',
  7099. size: _br.length(),
  7100. width: _info && _info.width || 0,
  7101. height: _info && _info.height || 0,
  7102. setExif: function(tag, value) {
  7103. if (!_ep) {
  7104. return false; // or throw an exception
  7105. }
  7106. if (Basic.typeOf(tag) === 'object') {
  7107. Basic.each(tag, function(value, tag) {
  7108. _ep.setExif(tag, value);
  7109. });
  7110. } else {
  7111. _ep.setExif(tag, value);
  7112. }
  7113. // update internal headers
  7114. _hm.set('app1', _ep.SEGMENT());
  7115. },
  7116. writeHeaders: function() {
  7117. if (!arguments.length) {
  7118. // if no arguments passed, update headers internally
  7119. return _hm.restore(data);
  7120. }
  7121. return _hm.restore(arguments[0]);
  7122. },
  7123. stripHeaders: function(data) {
  7124. return _hm.strip(data);
  7125. },
  7126. purge: function() {
  7127. _purge.call(this);
  7128. }
  7129. });
  7130. if (_ep) {
  7131. this.meta = {
  7132. tiff: _ep.TIFF(),
  7133. exif: _ep.EXIF(),
  7134. gps: _ep.GPS(),
  7135. thumb: _getThumb()
  7136. };
  7137. }
  7138. function _getDimensions(br) {
  7139. var idx = 0
  7140. , marker
  7141. , length
  7142. ;
  7143. if (!br) {
  7144. br = _br;
  7145. }
  7146. // examine all through the end, since some images might have very large APP segments
  7147. while (idx <= br.length()) {
  7148. marker = br.SHORT(idx += 2);
  7149. if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn
  7150. idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte)
  7151. return {
  7152. height: br.SHORT(idx),
  7153. width: br.SHORT(idx += 2)
  7154. };
  7155. }
  7156. length = br.SHORT(idx += 2);
  7157. idx += length - 2;
  7158. }
  7159. return null;
  7160. }
  7161. function _getThumb() {
  7162. var data = _ep.thumb()
  7163. , br
  7164. , info
  7165. ;
  7166. if (data) {
  7167. br = new BinaryReader(data);
  7168. info = _getDimensions(br);
  7169. br.clear();
  7170. if (info) {
  7171. info.data = data;
  7172. return info;
  7173. }
  7174. }
  7175. return null;
  7176. }
  7177. function _purge() {
  7178. if (!_ep || !_hm || !_br) {
  7179. return; // ignore any repeating purge requests
  7180. }
  7181. _ep.clear();
  7182. _hm.purge();
  7183. _br.clear();
  7184. _info = _hm = _ep = _br = null;
  7185. }
  7186. }
  7187. return JPEG;
  7188. });
  7189. // Included from: src/javascript/runtime/html5/image/PNG.js
  7190. /**
  7191. * PNG.js
  7192. *
  7193. * Copyright 2013, Moxiecode Systems AB
  7194. * Released under GPL License.
  7195. *
  7196. * License: http://www.plupload.com/license
  7197. * Contributing: http://www.plupload.com/contributing
  7198. */
  7199. /**
  7200. @class moxie/runtime/html5/image/PNG
  7201. @private
  7202. */
  7203. define("moxie/runtime/html5/image/PNG", [
  7204. "moxie/core/Exceptions",
  7205. "moxie/core/utils/Basic",
  7206. "moxie/runtime/html5/utils/BinaryReader"
  7207. ], function(x, Basic, BinaryReader) {
  7208. function PNG(data) {
  7209. var _br, _hm, _ep, _info;
  7210. _br = new BinaryReader(data);
  7211. // check if it's png
  7212. (function() {
  7213. var idx = 0, i = 0
  7214. , signature = [0x8950, 0x4E47, 0x0D0A, 0x1A0A]
  7215. ;
  7216. for (i = 0; i < signature.length; i++, idx += 2) {
  7217. if (signature[i] != _br.SHORT(idx)) {
  7218. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  7219. }
  7220. }
  7221. }());
  7222. function _getDimensions() {
  7223. var chunk, idx;
  7224. chunk = _getChunkAt.call(this, 8);
  7225. if (chunk.type == 'IHDR') {
  7226. idx = chunk.start;
  7227. return {
  7228. width: _br.LONG(idx),
  7229. height: _br.LONG(idx += 4)
  7230. };
  7231. }
  7232. return null;
  7233. }
  7234. function _purge() {
  7235. if (!_br) {
  7236. return; // ignore any repeating purge requests
  7237. }
  7238. _br.clear();
  7239. data = _info = _hm = _ep = _br = null;
  7240. }
  7241. _info = _getDimensions.call(this);
  7242. Basic.extend(this, {
  7243. type: 'image/png',
  7244. size: _br.length(),
  7245. width: _info.width,
  7246. height: _info.height,
  7247. purge: function() {
  7248. _purge.call(this);
  7249. }
  7250. });
  7251. // for PNG we can safely trigger purge automatically, as we do not keep any data for later
  7252. _purge.call(this);
  7253. function _getChunkAt(idx) {
  7254. var length, type, start, CRC;
  7255. length = _br.LONG(idx);
  7256. type = _br.STRING(idx += 4, 4);
  7257. start = idx += 4;
  7258. CRC = _br.LONG(idx + length);
  7259. return {
  7260. length: length,
  7261. type: type,
  7262. start: start,
  7263. CRC: CRC
  7264. };
  7265. }
  7266. }
  7267. return PNG;
  7268. });
  7269. // Included from: src/javascript/runtime/html5/image/ImageInfo.js
  7270. /**
  7271. * ImageInfo.js
  7272. *
  7273. * Copyright 2013, Moxiecode Systems AB
  7274. * Released under GPL License.
  7275. *
  7276. * License: http://www.plupload.com/license
  7277. * Contributing: http://www.plupload.com/contributing
  7278. */
  7279. /**
  7280. @class moxie/runtime/html5/image/ImageInfo
  7281. @private
  7282. */
  7283. define("moxie/runtime/html5/image/ImageInfo", [
  7284. "moxie/core/utils/Basic",
  7285. "moxie/core/Exceptions",
  7286. "moxie/runtime/html5/image/JPEG",
  7287. "moxie/runtime/html5/image/PNG"
  7288. ], function(Basic, x, JPEG, PNG) {
  7289. /**
  7290. Optional image investigation tool for HTML5 runtime. Provides the following features:
  7291. - ability to distinguish image type (JPEG or PNG) by signature
  7292. - ability to extract image width/height directly from it's internals, without preloading in memory (fast)
  7293. - ability to extract APP headers from JPEGs (Exif, GPS, etc)
  7294. - ability to replace width/height tags in extracted JPEG headers
  7295. - ability to restore APP headers, that were for example stripped during image manipulation
  7296. @class ImageInfo
  7297. @constructor
  7298. @param {String} data Image source as binary string
  7299. */
  7300. return function(data) {
  7301. var _cs = [JPEG, PNG], _img;
  7302. // figure out the format, throw: ImageError.WRONG_FORMAT if not supported
  7303. _img = (function() {
  7304. for (var i = 0; i < _cs.length; i++) {
  7305. try {
  7306. return new _cs[i](data);
  7307. } catch (ex) {
  7308. // console.info(ex);
  7309. }
  7310. }
  7311. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  7312. }());
  7313. Basic.extend(this, {
  7314. /**
  7315. Image Mime Type extracted from it's depths
  7316. @property type
  7317. @type {String}
  7318. @default ''
  7319. */
  7320. type: '',
  7321. /**
  7322. Image size in bytes
  7323. @property size
  7324. @type {Number}
  7325. @default 0
  7326. */
  7327. size: 0,
  7328. /**
  7329. Image width extracted from image source
  7330. @property width
  7331. @type {Number}
  7332. @default 0
  7333. */
  7334. width: 0,
  7335. /**
  7336. Image height extracted from image source
  7337. @property height
  7338. @type {Number}
  7339. @default 0
  7340. */
  7341. height: 0,
  7342. /**
  7343. Sets Exif tag. Currently applicable only for width and height tags. Obviously works only with JPEGs.
  7344. @method setExif
  7345. @param {String} tag Tag to set
  7346. @param {Mixed} value Value to assign to the tag
  7347. */
  7348. setExif: function() {},
  7349. /**
  7350. Restores headers to the source.
  7351. @method writeHeaders
  7352. @param {String} data Image source as binary string
  7353. @return {String} Updated binary string
  7354. */
  7355. writeHeaders: function(data) {
  7356. return data;
  7357. },
  7358. /**
  7359. Strip all headers from the source.
  7360. @method stripHeaders
  7361. @param {String} data Image source as binary string
  7362. @return {String} Updated binary string
  7363. */
  7364. stripHeaders: function(data) {
  7365. return data;
  7366. },
  7367. /**
  7368. Dispose resources.
  7369. @method purge
  7370. */
  7371. purge: function() {
  7372. data = null;
  7373. }
  7374. });
  7375. Basic.extend(this, _img);
  7376. this.purge = function() {
  7377. _img.purge();
  7378. _img = null;
  7379. };
  7380. };
  7381. });
  7382. // Included from: src/javascript/runtime/html5/image/ResizerCanvas.js
  7383. /**
  7384. * ResizerCanvas.js
  7385. *
  7386. * Copyright 2013, Moxiecode Systems AB
  7387. * Released under GPL License.
  7388. *
  7389. * License: http://www.plupload.com/license
  7390. * Contributing: http://www.plupload.com/contributing
  7391. */
  7392. /**
  7393. * Resizes image/canvas using canvas
  7394. */
  7395. define("moxie/runtime/html5/image/ResizerCanvas", [], function() {
  7396. function scale(image, ratio) {
  7397. var sW = image.width;
  7398. var dW = Math.floor(sW * ratio);
  7399. var scaleCapped = false;
  7400. if (ratio < 0.5 || ratio > 2) {
  7401. ratio = ratio < 0.5 ? 0.5 : 2;
  7402. scaleCapped = true;
  7403. }
  7404. var tCanvas = _scale(image, ratio);
  7405. if (scaleCapped) {
  7406. return scale(tCanvas, dW / tCanvas.width);
  7407. } else {
  7408. return tCanvas;
  7409. }
  7410. }
  7411. function _scale(image, ratio) {
  7412. var sW = image.width;
  7413. var sH = image.height;
  7414. var dW = Math.floor(sW * ratio);
  7415. var dH = Math.floor(sH * ratio);
  7416. var canvas = document.createElement('canvas');
  7417. canvas.width = dW;
  7418. canvas.height = dH;
  7419. canvas.getContext("2d").drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
  7420. image = null; // just in case
  7421. return canvas;
  7422. }
  7423. return {
  7424. scale: scale
  7425. };
  7426. });
  7427. // Included from: src/javascript/runtime/html5/image/Image.js
  7428. /**
  7429. * Image.js
  7430. *
  7431. * Copyright 2013, Moxiecode Systems AB
  7432. * Released under GPL License.
  7433. *
  7434. * License: http://www.plupload.com/license
  7435. * Contributing: http://www.plupload.com/contributing
  7436. */
  7437. /**
  7438. @class moxie/runtime/html5/image/Image
  7439. @private
  7440. */
  7441. define("moxie/runtime/html5/image/Image", [
  7442. "moxie/runtime/html5/Runtime",
  7443. "moxie/core/utils/Basic",
  7444. "moxie/core/Exceptions",
  7445. "moxie/core/utils/Encode",
  7446. "moxie/file/Blob",
  7447. "moxie/file/File",
  7448. "moxie/runtime/html5/image/ImageInfo",
  7449. "moxie/runtime/html5/image/ResizerCanvas",
  7450. "moxie/core/utils/Mime",
  7451. "moxie/core/utils/Env"
  7452. ], function(extensions, Basic, x, Encode, Blob, File, ImageInfo, ResizerCanvas, Mime, Env) {
  7453. function HTML5Image() {
  7454. var me = this
  7455. , _img, _imgInfo, _canvas, _binStr, _blob
  7456. , _modified = false // is set true whenever image is modified
  7457. , _preserveHeaders = true
  7458. ;
  7459. Basic.extend(this, {
  7460. loadFromBlob: function(blob) {
  7461. var comp = this, I = comp.getRuntime()
  7462. , asBinary = arguments.length > 1 ? arguments[1] : true
  7463. ;
  7464. if (!I.can('access_binary')) {
  7465. throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
  7466. }
  7467. _blob = blob;
  7468. if (blob.isDetached()) {
  7469. _binStr = blob.getSource();
  7470. _preload.call(this, _binStr);
  7471. return;
  7472. } else {
  7473. _readAsDataUrl.call(this, blob.getSource(), function(dataUrl) {
  7474. if (asBinary) {
  7475. _binStr = _toBinary(dataUrl);
  7476. }
  7477. _preload.call(comp, dataUrl);
  7478. });
  7479. }
  7480. },
  7481. loadFromImage: function(img, exact) {
  7482. this.meta = img.meta;
  7483. _blob = new File(null, {
  7484. name: img.name,
  7485. size: img.size,
  7486. type: img.type
  7487. });
  7488. _preload.call(this, exact ? (_binStr = img.getAsBinaryString()) : img.getAsDataURL());
  7489. },
  7490. getInfo: function() {
  7491. var I = this.getRuntime(), info;
  7492. if (!_imgInfo && _binStr && I.can('access_image_binary')) {
  7493. _imgInfo = new ImageInfo(_binStr);
  7494. }
  7495. info = {
  7496. width: _getImg().width || 0,
  7497. height: _getImg().height || 0,
  7498. type: _blob.type || Mime.getFileMime(_blob.name),
  7499. size: _binStr && _binStr.length || _blob.size || 0,
  7500. name: _blob.name || '',
  7501. meta: null
  7502. };
  7503. if (_preserveHeaders) {
  7504. info.meta = _imgInfo && _imgInfo.meta || this.meta || {};
  7505. // store thumbnail data as blob
  7506. if (info.meta && info.meta.thumb && !(info.meta.thumb.data instanceof Blob)) {
  7507. info.meta.thumb.data = new Blob(null, {
  7508. type: 'image/jpeg',
  7509. data: info.meta.thumb.data
  7510. });
  7511. }
  7512. }
  7513. return info;
  7514. },
  7515. resize: function(rect, ratio, options) {
  7516. var canvas = document.createElement('canvas');
  7517. canvas.width = rect.width;
  7518. canvas.height = rect.height;
  7519. canvas.getContext("2d").drawImage(_getImg(), rect.x, rect.y, rect.width, rect.height, 0, 0, canvas.width, canvas.height);
  7520. _canvas = ResizerCanvas.scale(canvas, ratio);
  7521. _preserveHeaders = options.preserveHeaders;
  7522. // rotate if required, according to orientation tag
  7523. if (!_preserveHeaders) {
  7524. var orientation = (this.meta && this.meta.tiff && this.meta.tiff.Orientation) || 1;
  7525. _canvas = _rotateToOrientaion(_canvas, orientation);
  7526. }
  7527. this.width = _canvas.width;
  7528. this.height = _canvas.height;
  7529. _modified = true;
  7530. this.trigger('Resize');
  7531. },
  7532. getAsCanvas: function() {
  7533. if (!_canvas) {
  7534. _canvas = _getCanvas();
  7535. }
  7536. _canvas.id = this.uid + '_canvas';
  7537. return _canvas;
  7538. },
  7539. getAsBlob: function(type, quality) {
  7540. if (type !== this.type) {
  7541. _modified = true; // reconsider the state
  7542. return new File(null, {
  7543. name: _blob.name || '',
  7544. type: type,
  7545. data: me.getAsDataURL(type, quality)
  7546. });
  7547. }
  7548. return new File(null, {
  7549. name: _blob.name || '',
  7550. type: type,
  7551. data: me.getAsBinaryString(type, quality)
  7552. });
  7553. },
  7554. getAsDataURL: function(type) {
  7555. var quality = arguments[1] || 90;
  7556. // if image has not been modified, return the source right away
  7557. if (!_modified) {
  7558. return _img.src;
  7559. }
  7560. // make sure we have a canvas to work with
  7561. _getCanvas();
  7562. if ('image/jpeg' !== type) {
  7563. return _canvas.toDataURL('image/png');
  7564. } else {
  7565. try {
  7566. // older Geckos used to result in an exception on quality argument
  7567. return _canvas.toDataURL('image/jpeg', quality/100);
  7568. } catch (ex) {
  7569. return _canvas.toDataURL('image/jpeg');
  7570. }
  7571. }
  7572. },
  7573. getAsBinaryString: function(type, quality) {
  7574. // if image has not been modified, return the source right away
  7575. if (!_modified) {
  7576. // if image was not loaded from binary string
  7577. if (!_binStr) {
  7578. _binStr = _toBinary(me.getAsDataURL(type, quality));
  7579. }
  7580. return _binStr;
  7581. }
  7582. if ('image/jpeg' !== type) {
  7583. _binStr = _toBinary(me.getAsDataURL(type, quality));
  7584. } else {
  7585. var dataUrl;
  7586. // if jpeg
  7587. if (!quality) {
  7588. quality = 90;
  7589. }
  7590. // make sure we have a canvas to work with
  7591. _getCanvas();
  7592. try {
  7593. // older Geckos used to result in an exception on quality argument
  7594. dataUrl = _canvas.toDataURL('image/jpeg', quality/100);
  7595. } catch (ex) {
  7596. dataUrl = _canvas.toDataURL('image/jpeg');
  7597. }
  7598. _binStr = _toBinary(dataUrl);
  7599. if (_imgInfo) {
  7600. _binStr = _imgInfo.stripHeaders(_binStr);
  7601. if (_preserveHeaders) {
  7602. // update dimensions info in exif
  7603. if (_imgInfo.meta && _imgInfo.meta.exif) {
  7604. _imgInfo.setExif({
  7605. PixelXDimension: this.width,
  7606. PixelYDimension: this.height
  7607. });
  7608. }
  7609. // re-inject the headers
  7610. _binStr = _imgInfo.writeHeaders(_binStr);
  7611. }
  7612. // will be re-created from fresh on next getInfo call
  7613. _imgInfo.purge();
  7614. _imgInfo = null;
  7615. }
  7616. }
  7617. _modified = false;
  7618. return _binStr;
  7619. },
  7620. destroy: function() {
  7621. me = null;
  7622. _purge.call(this);
  7623. this.getRuntime().getShim().removeInstance(this.uid);
  7624. }
  7625. });
  7626. function _getImg() {
  7627. if (!_canvas && !_img) {
  7628. throw new x.ImageError(x.DOMException.INVALID_STATE_ERR);
  7629. }
  7630. return _canvas || _img;
  7631. }
  7632. function _getCanvas() {
  7633. var canvas = _getImg();
  7634. if (canvas.nodeName.toLowerCase() == 'canvas') {
  7635. return canvas;
  7636. }
  7637. _canvas = document.createElement('canvas');
  7638. _canvas.width = canvas.width;
  7639. _canvas.height = canvas.height;
  7640. _canvas.getContext("2d").drawImage(canvas, 0, 0);
  7641. return _canvas;
  7642. }
  7643. function _toBinary(str) {
  7644. return Encode.atob(str.substring(str.indexOf('base64,') + 7));
  7645. }
  7646. function _toDataUrl(str, type) {
  7647. return 'data:' + (type || '') + ';base64,' + Encode.btoa(str);
  7648. }
  7649. function _preload(str) {
  7650. var comp = this;
  7651. _img = new Image();
  7652. _img.onerror = function() {
  7653. _purge.call(this);
  7654. comp.trigger('error', x.ImageError.WRONG_FORMAT);
  7655. };
  7656. _img.onload = function() {
  7657. comp.trigger('load');
  7658. };
  7659. _img.src = str.substr(0, 5) == 'data:' ? str : _toDataUrl(str, _blob.type);
  7660. }
  7661. function _readAsDataUrl(file, callback) {
  7662. var comp = this, fr;
  7663. // use FileReader if it's available
  7664. if (window.FileReader) {
  7665. fr = new FileReader();
  7666. fr.onload = function() {
  7667. callback(this.result);
  7668. };
  7669. fr.onerror = function() {
  7670. comp.trigger('error', x.ImageError.WRONG_FORMAT);
  7671. };
  7672. fr.readAsDataURL(file);
  7673. } else {
  7674. return callback(file.getAsDataURL());
  7675. }
  7676. }
  7677. /**
  7678. * Transform canvas coordination according to specified frame size and orientation
  7679. * Orientation value is from EXIF tag
  7680. * @author Shinichi Tomita <shinichi.tomita@gmail.com>
  7681. */
  7682. function _rotateToOrientaion(img, orientation) {
  7683. var RADIANS = Math.PI/180;
  7684. var canvas = document.createElement('canvas');
  7685. var ctx = canvas.getContext('2d');
  7686. var width = img.width;
  7687. var height = img.height;
  7688. if (Basic.inArray(orientation, [5,6,7,8]) > -1) {
  7689. canvas.width = height;
  7690. canvas.height = width;
  7691. } else {
  7692. canvas.width = width;
  7693. canvas.height = height;
  7694. }
  7695. /**
  7696. 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
  7697. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
  7698. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
  7699. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
  7700. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
  7701. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
  7702. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
  7703. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
  7704. */
  7705. switch (orientation) {
  7706. case 2:
  7707. // horizontal flip
  7708. ctx.translate(width, 0);
  7709. ctx.scale(-1, 1);
  7710. break;
  7711. case 3:
  7712. // 180 rotate left
  7713. ctx.translate(width, height);
  7714. ctx.rotate(180 * RADIANS);
  7715. break;
  7716. case 4:
  7717. // vertical flip
  7718. ctx.translate(0, height);
  7719. ctx.scale(1, -1);
  7720. break;
  7721. case 5:
  7722. // vertical flip + 90 rotate right
  7723. ctx.rotate(90 * RADIANS);
  7724. ctx.scale(1, -1);
  7725. break;
  7726. case 6:
  7727. // 90 rotate right
  7728. ctx.rotate(90 * RADIANS);
  7729. ctx.translate(0, -height);
  7730. break;
  7731. case 7:
  7732. // horizontal flip + 90 rotate right
  7733. ctx.rotate(90 * RADIANS);
  7734. ctx.translate(width, -height);
  7735. ctx.scale(-1, 1);
  7736. break;
  7737. case 8:
  7738. // 90 rotate left
  7739. ctx.rotate(-90 * RADIANS);
  7740. ctx.translate(-width, 0);
  7741. break;
  7742. }
  7743. ctx.drawImage(img, 0, 0, width, height);
  7744. return canvas;
  7745. }
  7746. function _purge() {
  7747. if (_imgInfo) {
  7748. _imgInfo.purge();
  7749. _imgInfo = null;
  7750. }
  7751. _binStr = _img = _canvas = _blob = null;
  7752. _modified = false;
  7753. }
  7754. }
  7755. return (extensions.Image = HTML5Image);
  7756. });
  7757. // Included from: src/javascript/runtime/flash/Runtime.js
  7758. /**
  7759. * Runtime.js
  7760. *
  7761. * Copyright 2013, Moxiecode Systems AB
  7762. * Released under GPL License.
  7763. *
  7764. * License: http://www.plupload.com/license
  7765. * Contributing: http://www.plupload.com/contributing
  7766. */
  7767. /*global ActiveXObject:true */
  7768. /**
  7769. Defines constructor for Flash runtime.
  7770. @class moxie/runtime/flash/Runtime
  7771. @private
  7772. */
  7773. define("moxie/runtime/flash/Runtime", [
  7774. "moxie/core/utils/Basic",
  7775. "moxie/core/utils/Env",
  7776. "moxie/core/utils/Dom",
  7777. "moxie/core/Exceptions",
  7778. "moxie/runtime/Runtime"
  7779. ], function(Basic, Env, Dom, x, Runtime) {
  7780. var type = 'flash', extensions = {};
  7781. /**
  7782. Get the version of the Flash Player
  7783. @method getShimVersion
  7784. @private
  7785. @return {Number} Flash Player version
  7786. */
  7787. function getShimVersion() {
  7788. var version;
  7789. try {
  7790. version = navigator.plugins['Shockwave Flash'];
  7791. version = version.description;
  7792. } catch (e1) {
  7793. try {
  7794. version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
  7795. } catch (e2) {
  7796. version = '0.0';
  7797. }
  7798. }
  7799. version = version.match(/\d+/g);
  7800. return parseFloat(version[0] + '.' + version[1]);
  7801. }
  7802. /**
  7803. Cross-browser SWF removal
  7804. - Especially needed to safely and completely remove a SWF in Internet Explorer
  7805. Originated from SWFObject v2.2 <http://code.google.com/p/swfobject/>
  7806. */
  7807. function removeSWF(id) {
  7808. var obj = Dom.get(id);
  7809. if (obj && obj.nodeName == "OBJECT") {
  7810. if (Env.browser === 'IE') {
  7811. obj.style.display = "none";
  7812. (function onInit(){
  7813. // http://msdn.microsoft.com/en-us/library/ie/ms534360(v=vs.85).aspx
  7814. if (obj.readyState == 4) {
  7815. removeObjectInIE(id);
  7816. }
  7817. else {
  7818. setTimeout(onInit, 10);
  7819. }
  7820. })();
  7821. }
  7822. else {
  7823. obj.parentNode.removeChild(obj);
  7824. }
  7825. }
  7826. }
  7827. function removeObjectInIE(id) {
  7828. var obj = Dom.get(id);
  7829. if (obj) {
  7830. for (var i in obj) {
  7831. if (typeof obj[i] == "function") {
  7832. obj[i] = null;
  7833. }
  7834. }
  7835. obj.parentNode.removeChild(obj);
  7836. }
  7837. }
  7838. /**
  7839. Constructor for the Flash Runtime
  7840. @class FlashRuntime
  7841. @extends Runtime
  7842. */
  7843. function FlashRuntime(options) {
  7844. var I = this, initTimer;
  7845. options = Basic.extend({ swf_url: Env.swf_url }, options);
  7846. Runtime.call(this, options, type, {
  7847. access_binary: function(value) {
  7848. return value && I.mode === 'browser';
  7849. },
  7850. access_image_binary: function(value) {
  7851. return value && I.mode === 'browser';
  7852. },
  7853. display_media: Runtime.capTest(defined('moxie/image/Image')),
  7854. do_cors: Runtime.capTrue,
  7855. drag_and_drop: false,
  7856. report_upload_progress: function() {
  7857. return I.mode === 'client';
  7858. },
  7859. resize_image: Runtime.capTrue,
  7860. return_response_headers: false,
  7861. return_response_type: function(responseType) {
  7862. if (responseType === 'json' && !!window.JSON) {
  7863. return true;
  7864. }
  7865. return !Basic.arrayDiff(responseType, ['', 'text', 'document']) || I.mode === 'browser';
  7866. },
  7867. return_status_code: function(code) {
  7868. return I.mode === 'browser' || !Basic.arrayDiff(code, [200, 404]);
  7869. },
  7870. select_file: Runtime.capTrue,
  7871. select_multiple: Runtime.capTrue,
  7872. send_binary_string: function(value) {
  7873. return value && I.mode === 'browser';
  7874. },
  7875. send_browser_cookies: function(value) {
  7876. return value && I.mode === 'browser';
  7877. },
  7878. send_custom_headers: function(value) {
  7879. return value && I.mode === 'browser';
  7880. },
  7881. send_multipart: Runtime.capTrue,
  7882. slice_blob: function(value) {
  7883. return value && I.mode === 'browser';
  7884. },
  7885. stream_upload: function(value) {
  7886. return value && I.mode === 'browser';
  7887. },
  7888. summon_file_dialog: false,
  7889. upload_filesize: function(size) {
  7890. return Basic.parseSizeStr(size) <= 2097152 || I.mode === 'client';
  7891. },
  7892. use_http_method: function(methods) {
  7893. return !Basic.arrayDiff(methods, ['GET', 'POST']);
  7894. }
  7895. }, {
  7896. // capabilities that require specific mode
  7897. access_binary: function(value) {
  7898. return value ? 'browser' : 'client';
  7899. },
  7900. access_image_binary: function(value) {
  7901. return value ? 'browser' : 'client';
  7902. },
  7903. report_upload_progress: function(value) {
  7904. return value ? 'browser' : 'client';
  7905. },
  7906. return_response_type: function(responseType) {
  7907. return Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) ? 'browser' : ['client', 'browser'];
  7908. },
  7909. return_status_code: function(code) {
  7910. return Basic.arrayDiff(code, [200, 404]) ? 'browser' : ['client', 'browser'];
  7911. },
  7912. send_binary_string: function(value) {
  7913. return value ? 'browser' : 'client';
  7914. },
  7915. send_browser_cookies: function(value) {
  7916. return value ? 'browser' : 'client';
  7917. },
  7918. send_custom_headers: function(value) {
  7919. return value ? 'browser' : 'client';
  7920. },
  7921. slice_blob: function(value) {
  7922. return value ? 'browser' : 'client';
  7923. },
  7924. stream_upload: function(value) {
  7925. return value ? 'client' : 'browser';
  7926. },
  7927. upload_filesize: function(size) {
  7928. return Basic.parseSizeStr(size) >= 2097152 ? 'client' : 'browser';
  7929. }
  7930. }, 'client');
  7931. // minimal requirement for Flash Player version
  7932. if (getShimVersion() < 11.3) {
  7933. if (MXI_DEBUG && Env.debug.runtime) {
  7934. Env.log("\tFlash didn't meet minimal version requirement (11.3).");
  7935. }
  7936. this.mode = false; // with falsy mode, runtime won't operable, no matter what the mode was before
  7937. }
  7938. Basic.extend(this, {
  7939. getShim: function() {
  7940. return Dom.get(this.uid);
  7941. },
  7942. shimExec: function(component, action) {
  7943. var args = [].slice.call(arguments, 2);
  7944. return I.getShim().exec(this.uid, component, action, args);
  7945. },
  7946. init: function() {
  7947. var html, el, container;
  7948. container = this.getShimContainer();
  7949. // if not the minimal height, shims are not initialized in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc)
  7950. Basic.extend(container.style, {
  7951. position: 'absolute',
  7952. top: '-8px',
  7953. left: '-8px',
  7954. width: '9px',
  7955. height: '9px',
  7956. overflow: 'hidden'
  7957. });
  7958. // insert flash object
  7959. html = '<object id="' + this.uid + '" type="application/x-shockwave-flash" data="' + options.swf_url + '" ';
  7960. if (Env.browser === 'IE') {
  7961. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
  7962. }
  7963. html += 'width="100%" height="100%" style="outline:0">' +
  7964. '<param name="movie" value="' + options.swf_url + '" />' +
  7965. '<param name="flashvars" value="uid=' + escape(this.uid) + '&target=' + Env.global_event_dispatcher + '" />' +
  7966. '<param name="wmode" value="transparent" />' +
  7967. '<param name="allowscriptaccess" value="always" />' +
  7968. '</object>';
  7969. if (Env.browser === 'IE') {
  7970. el = document.createElement('div');
  7971. container.appendChild(el);
  7972. el.outerHTML = html;
  7973. el = container = null; // just in case
  7974. } else {
  7975. container.innerHTML = html;
  7976. }
  7977. // Init is dispatched by the shim
  7978. initTimer = setTimeout(function() {
  7979. if (I && !I.initialized) { // runtime might be already destroyed by this moment
  7980. I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
  7981. if (MXI_DEBUG && Env.debug.runtime) {
  7982. Env.log("\tFlash failed to initialize within a specified period of time (typically 5s).");
  7983. }
  7984. }
  7985. }, 5000);
  7986. },
  7987. destroy: (function(destroy) { // extend default destroy method
  7988. return function() {
  7989. removeSWF(I.uid); // SWF removal requires special care in IE
  7990. destroy.call(I);
  7991. clearTimeout(initTimer); // initialization check might be still onwait
  7992. options = initTimer = destroy = I = null;
  7993. };
  7994. }(this.destroy))
  7995. }, extensions);
  7996. }
  7997. Runtime.addConstructor(type, FlashRuntime);
  7998. return extensions;
  7999. });
  8000. // Included from: src/javascript/runtime/flash/file/Blob.js
  8001. /**
  8002. * Blob.js
  8003. *
  8004. * Copyright 2013, Moxiecode Systems AB
  8005. * Released under GPL License.
  8006. *
  8007. * License: http://www.plupload.com/license
  8008. * Contributing: http://www.plupload.com/contributing
  8009. */
  8010. /**
  8011. @class moxie/runtime/flash/file/Blob
  8012. @private
  8013. */
  8014. define("moxie/runtime/flash/file/Blob", [
  8015. "moxie/runtime/flash/Runtime",
  8016. "moxie/file/Blob"
  8017. ], function(extensions, Blob) {
  8018. var FlashBlob = {
  8019. slice: function(blob, start, end, type) {
  8020. var self = this.getRuntime();
  8021. if (start < 0) {
  8022. start = Math.max(blob.size + start, 0);
  8023. } else if (start > 0) {
  8024. start = Math.min(start, blob.size);
  8025. }
  8026. if (end < 0) {
  8027. end = Math.max(blob.size + end, 0);
  8028. } else if (end > 0) {
  8029. end = Math.min(end, blob.size);
  8030. }
  8031. blob = self.shimExec.call(this, 'Blob', 'slice', start, end, type || '');
  8032. if (blob) {
  8033. blob = new Blob(self.uid, blob);
  8034. }
  8035. return blob;
  8036. }
  8037. };
  8038. return (extensions.Blob = FlashBlob);
  8039. });
  8040. // Included from: src/javascript/runtime/flash/file/FileInput.js
  8041. /**
  8042. * FileInput.js
  8043. *
  8044. * Copyright 2013, Moxiecode Systems AB
  8045. * Released under GPL License.
  8046. *
  8047. * License: http://www.plupload.com/license
  8048. * Contributing: http://www.plupload.com/contributing
  8049. */
  8050. /**
  8051. @class moxie/runtime/flash/file/FileInput
  8052. @private
  8053. */
  8054. define("moxie/runtime/flash/file/FileInput", [
  8055. "moxie/runtime/flash/Runtime",
  8056. "moxie/file/File",
  8057. "moxie/core/utils/Basic"
  8058. ], function(extensions, File, Basic) {
  8059. var FileInput = {
  8060. init: function(options) {
  8061. var comp = this, I = this.getRuntime();
  8062. this.bind("Change", function() {
  8063. var files = I.shimExec.call(comp, 'FileInput', 'getFiles');
  8064. comp.files = [];
  8065. Basic.each(files, function(file) {
  8066. comp.files.push(new File(I.uid, file));
  8067. });
  8068. }, 999);
  8069. this.getRuntime().shimExec.call(this, 'FileInput', 'init', {
  8070. accept: options.accept,
  8071. multiple: options.multiple
  8072. });
  8073. this.trigger('ready');
  8074. }
  8075. };
  8076. return (extensions.FileInput = FileInput);
  8077. });
  8078. // Included from: src/javascript/runtime/flash/file/FileReader.js
  8079. /**
  8080. * FileReader.js
  8081. *
  8082. * Copyright 2013, Moxiecode Systems AB
  8083. * Released under GPL License.
  8084. *
  8085. * License: http://www.plupload.com/license
  8086. * Contributing: http://www.plupload.com/contributing
  8087. */
  8088. /**
  8089. @class moxie/runtime/flash/file/FileReader
  8090. @private
  8091. */
  8092. define("moxie/runtime/flash/file/FileReader", [
  8093. "moxie/runtime/flash/Runtime",
  8094. "moxie/core/utils/Encode"
  8095. ], function(extensions, Encode) {
  8096. function _formatData(data, op) {
  8097. switch (op) {
  8098. case 'readAsText':
  8099. return Encode.atob(data, 'utf8');
  8100. case 'readAsBinaryString':
  8101. return Encode.atob(data);
  8102. case 'readAsDataURL':
  8103. return data;
  8104. }
  8105. return null;
  8106. }
  8107. var FileReader = {
  8108. read: function(op, blob) {
  8109. var comp = this;
  8110. comp.result = '';
  8111. // special prefix for DataURL read mode
  8112. if (op === 'readAsDataURL') {
  8113. comp.result = 'data:' + (blob.type || '') + ';base64,';
  8114. }
  8115. comp.bind('Progress', function(e, data) {
  8116. if (data) {
  8117. comp.result += _formatData(data, op);
  8118. }
  8119. }, 999);
  8120. return comp.getRuntime().shimExec.call(this, 'FileReader', 'readAsBase64', blob.uid);
  8121. }
  8122. };
  8123. return (extensions.FileReader = FileReader);
  8124. });
  8125. // Included from: src/javascript/runtime/flash/file/FileReaderSync.js
  8126. /**
  8127. * FileReaderSync.js
  8128. *
  8129. * Copyright 2013, Moxiecode Systems AB
  8130. * Released under GPL License.
  8131. *
  8132. * License: http://www.plupload.com/license
  8133. * Contributing: http://www.plupload.com/contributing
  8134. */
  8135. /**
  8136. @class moxie/runtime/flash/file/FileReaderSync
  8137. @private
  8138. */
  8139. define("moxie/runtime/flash/file/FileReaderSync", [
  8140. "moxie/runtime/flash/Runtime",
  8141. "moxie/core/utils/Encode"
  8142. ], function(extensions, Encode) {
  8143. function _formatData(data, op) {
  8144. switch (op) {
  8145. case 'readAsText':
  8146. return Encode.atob(data, 'utf8');
  8147. case 'readAsBinaryString':
  8148. return Encode.atob(data);
  8149. case 'readAsDataURL':
  8150. return data;
  8151. }
  8152. return null;
  8153. }
  8154. var FileReaderSync = {
  8155. read: function(op, blob) {
  8156. var result, self = this.getRuntime();
  8157. result = self.shimExec.call(this, 'FileReaderSync', 'readAsBase64', blob.uid);
  8158. if (!result) {
  8159. return null; // or throw ex
  8160. }
  8161. // special prefix for DataURL read mode
  8162. if (op === 'readAsDataURL') {
  8163. result = 'data:' + (blob.type || '') + ';base64,' + result;
  8164. }
  8165. return _formatData(result, op, blob.type);
  8166. }
  8167. };
  8168. return (extensions.FileReaderSync = FileReaderSync);
  8169. });
  8170. // Included from: src/javascript/runtime/flash/runtime/Transporter.js
  8171. /**
  8172. * Transporter.js
  8173. *
  8174. * Copyright 2013, Moxiecode Systems AB
  8175. * Released under GPL License.
  8176. *
  8177. * License: http://www.plupload.com/license
  8178. * Contributing: http://www.plupload.com/contributing
  8179. */
  8180. /**
  8181. @class moxie/runtime/flash/runtime/Transporter
  8182. @private
  8183. */
  8184. define("moxie/runtime/flash/runtime/Transporter", [
  8185. "moxie/runtime/flash/Runtime",
  8186. "moxie/file/Blob"
  8187. ], function(extensions, Blob) {
  8188. var Transporter = {
  8189. getAsBlob: function(type) {
  8190. var self = this.getRuntime()
  8191. , blob = self.shimExec.call(this, 'Transporter', 'getAsBlob', type)
  8192. ;
  8193. if (blob) {
  8194. return new Blob(self.uid, blob);
  8195. }
  8196. return null;
  8197. }
  8198. };
  8199. return (extensions.Transporter = Transporter);
  8200. });
  8201. // Included from: src/javascript/runtime/flash/xhr/XMLHttpRequest.js
  8202. /**
  8203. * XMLHttpRequest.js
  8204. *
  8205. * Copyright 2013, Moxiecode Systems AB
  8206. * Released under GPL License.
  8207. *
  8208. * License: http://www.plupload.com/license
  8209. * Contributing: http://www.plupload.com/contributing
  8210. */
  8211. /**
  8212. @class moxie/runtime/flash/xhr/XMLHttpRequest
  8213. @private
  8214. */
  8215. define("moxie/runtime/flash/xhr/XMLHttpRequest", [
  8216. "moxie/runtime/flash/Runtime",
  8217. "moxie/core/utils/Basic",
  8218. "moxie/file/Blob",
  8219. "moxie/file/File",
  8220. "moxie/file/FileReaderSync",
  8221. "moxie/runtime/flash/file/FileReaderSync",
  8222. "moxie/xhr/FormData",
  8223. "moxie/runtime/Transporter",
  8224. "moxie/runtime/flash/runtime/Transporter"
  8225. ], function(extensions, Basic, Blob, File, FileReaderSync, FileReaderSyncFlash, FormData, Transporter, TransporterFlash) {
  8226. var XMLHttpRequest = {
  8227. send: function(meta, data) {
  8228. var target = this, self = target.getRuntime();
  8229. function send() {
  8230. meta.transport = self.mode;
  8231. self.shimExec.call(target, 'XMLHttpRequest', 'send', meta, data);
  8232. }
  8233. function appendBlob(name, blob) {
  8234. self.shimExec.call(target, 'XMLHttpRequest', 'appendBlob', name, blob.uid);
  8235. data = null;
  8236. send();
  8237. }
  8238. function attachBlob(blob, cb) {
  8239. var tr = new Transporter();
  8240. tr.bind("TransportingComplete", function() {
  8241. cb(this.result);
  8242. });
  8243. tr.transport(blob.getSource(), blob.type, {
  8244. ruid: self.uid
  8245. });
  8246. }
  8247. // copy over the headers if any
  8248. if (!Basic.isEmptyObj(meta.headers)) {
  8249. Basic.each(meta.headers, function(value, header) {
  8250. self.shimExec.call(target, 'XMLHttpRequest', 'setRequestHeader', header, value.toString()); // Silverlight doesn't accept integers into the arguments of type object
  8251. });
  8252. }
  8253. // transfer over multipart params and blob itself
  8254. if (data instanceof FormData) {
  8255. var blobField;
  8256. data.each(function(value, name) {
  8257. if (value instanceof Blob) {
  8258. blobField = name;
  8259. } else {
  8260. self.shimExec.call(target, 'XMLHttpRequest', 'append', name, value);
  8261. }
  8262. });
  8263. if (!data.hasBlob()) {
  8264. data = null;
  8265. send();
  8266. } else {
  8267. var blob = data.getBlob();
  8268. if (blob.isDetached()) {
  8269. attachBlob(blob, function(attachedBlob) {
  8270. blob.destroy();
  8271. appendBlob(blobField, attachedBlob);
  8272. });
  8273. } else {
  8274. appendBlob(blobField, blob);
  8275. }
  8276. }
  8277. } else if (data instanceof Blob) {
  8278. if (data.isDetached()) {
  8279. attachBlob(data, function(attachedBlob) {
  8280. data.destroy();
  8281. data = attachedBlob.uid;
  8282. send();
  8283. });
  8284. } else {
  8285. data = data.uid;
  8286. send();
  8287. }
  8288. } else {
  8289. send();
  8290. }
  8291. },
  8292. getResponse: function(responseType) {
  8293. var frs, blob, self = this.getRuntime();
  8294. blob = self.shimExec.call(this, 'XMLHttpRequest', 'getResponseAsBlob');
  8295. if (blob) {
  8296. blob = new File(self.uid, blob);
  8297. if ('blob' === responseType) {
  8298. return blob;
  8299. }
  8300. try {
  8301. frs = new FileReaderSync();
  8302. if (!!~Basic.inArray(responseType, ["", "text"])) {
  8303. return frs.readAsText(blob);
  8304. } else if ('json' === responseType && !!window.JSON) {
  8305. return JSON.parse(frs.readAsText(blob));
  8306. }
  8307. } finally {
  8308. blob.destroy();
  8309. }
  8310. }
  8311. return null;
  8312. },
  8313. abort: function(upload_complete_flag) {
  8314. var self = this.getRuntime();
  8315. self.shimExec.call(this, 'XMLHttpRequest', 'abort');
  8316. this.dispatchEvent('readystatechange');
  8317. // this.dispatchEvent('progress');
  8318. this.dispatchEvent('abort');
  8319. //if (!upload_complete_flag) {
  8320. // this.dispatchEvent('uploadprogress');
  8321. //}
  8322. }
  8323. };
  8324. return (extensions.XMLHttpRequest = XMLHttpRequest);
  8325. });
  8326. // Included from: src/javascript/runtime/flash/image/Image.js
  8327. /**
  8328. * Image.js
  8329. *
  8330. * Copyright 2013, Moxiecode Systems AB
  8331. * Released under GPL License.
  8332. *
  8333. * License: http://www.plupload.com/license
  8334. * Contributing: http://www.plupload.com/contributing
  8335. */
  8336. /**
  8337. @class moxie/runtime/flash/image/Image
  8338. @private
  8339. */
  8340. define("moxie/runtime/flash/image/Image", [
  8341. "moxie/runtime/flash/Runtime",
  8342. "moxie/core/utils/Basic",
  8343. "moxie/runtime/Transporter",
  8344. "moxie/file/Blob",
  8345. "moxie/file/FileReaderSync"
  8346. ], function(extensions, Basic, Transporter, Blob, FileReaderSync) {
  8347. var Image = {
  8348. loadFromBlob: function(blob) {
  8349. var comp = this, self = comp.getRuntime();
  8350. function exec(srcBlob) {
  8351. self.shimExec.call(comp, 'Image', 'loadFromBlob', srcBlob.uid);
  8352. comp = self = null;
  8353. }
  8354. if (blob.isDetached()) { // binary string
  8355. var tr = new Transporter();
  8356. tr.bind("TransportingComplete", function() {
  8357. exec(tr.result.getSource());
  8358. });
  8359. tr.transport(blob.getSource(), blob.type, { ruid: self.uid });
  8360. } else {
  8361. exec(blob.getSource());
  8362. }
  8363. },
  8364. loadFromImage: function(img) {
  8365. var self = this.getRuntime();
  8366. return self.shimExec.call(this, 'Image', 'loadFromImage', img.uid);
  8367. },
  8368. getInfo: function() {
  8369. var self = this.getRuntime()
  8370. , info = self.shimExec.call(this, 'Image', 'getInfo')
  8371. ;
  8372. if (info.meta && info.meta.thumb && !(info.meta.thumb.data instanceof Blob)) {
  8373. info.meta.thumb.data = new Blob(self.uid, info.meta.thumb.data);
  8374. }
  8375. return info;
  8376. },
  8377. getAsBlob: function(type, quality) {
  8378. var self = this.getRuntime()
  8379. , blob = self.shimExec.call(this, 'Image', 'getAsBlob', type, quality)
  8380. ;
  8381. if (blob) {
  8382. return new Blob(self.uid, blob);
  8383. }
  8384. return null;
  8385. },
  8386. getAsDataURL: function() {
  8387. var self = this.getRuntime()
  8388. , blob = self.Image.getAsBlob.apply(this, arguments)
  8389. , frs
  8390. ;
  8391. if (!blob) {
  8392. return null;
  8393. }
  8394. frs = new FileReaderSync();
  8395. return frs.readAsDataURL(blob);
  8396. }
  8397. };
  8398. return (extensions.Image = Image);
  8399. });
  8400. // Included from: src/javascript/runtime/silverlight/Runtime.js
  8401. /**
  8402. * RunTime.js
  8403. *
  8404. * Copyright 2013, Moxiecode Systems AB
  8405. * Released under GPL License.
  8406. *
  8407. * License: http://www.plupload.com/license
  8408. * Contributing: http://www.plupload.com/contributing
  8409. */
  8410. /*global ActiveXObject:true */
  8411. /**
  8412. Defines constructor for Silverlight runtime.
  8413. @class moxie/runtime/silverlight/Runtime
  8414. @private
  8415. */
  8416. define("moxie/runtime/silverlight/Runtime", [
  8417. "moxie/core/utils/Basic",
  8418. "moxie/core/utils/Env",
  8419. "moxie/core/utils/Dom",
  8420. "moxie/core/Exceptions",
  8421. "moxie/runtime/Runtime"
  8422. ], function(Basic, Env, Dom, x, Runtime) {
  8423. var type = "silverlight", extensions = {};
  8424. function isInstalled(version) {
  8425. var isVersionSupported = false, control = null, actualVer,
  8426. actualVerArray, reqVerArray, requiredVersionPart, actualVersionPart, index = 0;
  8427. try {
  8428. try {
  8429. control = new ActiveXObject('AgControl.AgControl');
  8430. if (control.IsVersionSupported(version)) {
  8431. isVersionSupported = true;
  8432. }
  8433. control = null;
  8434. } catch (e) {
  8435. var plugin = navigator.plugins["Silverlight Plug-In"];
  8436. if (plugin) {
  8437. actualVer = plugin.description;
  8438. if (actualVer === "1.0.30226.2") {
  8439. actualVer = "2.0.30226.2";
  8440. }
  8441. actualVerArray = actualVer.split(".");
  8442. while (actualVerArray.length > 3) {
  8443. actualVerArray.pop();
  8444. }
  8445. while ( actualVerArray.length < 4) {
  8446. actualVerArray.push(0);
  8447. }
  8448. reqVerArray = version.split(".");
  8449. while (reqVerArray.length > 4) {
  8450. reqVerArray.pop();
  8451. }
  8452. do {
  8453. requiredVersionPart = parseInt(reqVerArray[index], 10);
  8454. actualVersionPart = parseInt(actualVerArray[index], 10);
  8455. index++;
  8456. } while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);
  8457. if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) {
  8458. isVersionSupported = true;
  8459. }
  8460. }
  8461. }
  8462. } catch (e2) {
  8463. isVersionSupported = false;
  8464. }
  8465. return isVersionSupported;
  8466. }
  8467. /**
  8468. Constructor for the Silverlight Runtime
  8469. @class SilverlightRuntime
  8470. @extends Runtime
  8471. */
  8472. function SilverlightRuntime(options) {
  8473. var I = this, initTimer;
  8474. options = Basic.extend({ xap_url: Env.xap_url }, options);
  8475. Runtime.call(this, options, type, {
  8476. access_binary: Runtime.capTrue,
  8477. access_image_binary: Runtime.capTrue,
  8478. display_media: Runtime.capTest(defined('moxie/image/Image')),
  8479. do_cors: Runtime.capTrue,
  8480. drag_and_drop: false,
  8481. report_upload_progress: Runtime.capTrue,
  8482. resize_image: Runtime.capTrue,
  8483. return_response_headers: function(value) {
  8484. return value && I.mode === 'client';
  8485. },
  8486. return_response_type: function(responseType) {
  8487. if (responseType !== 'json') {
  8488. return true;
  8489. } else {
  8490. return !!window.JSON;
  8491. }
  8492. },
  8493. return_status_code: function(code) {
  8494. return I.mode === 'client' || !Basic.arrayDiff(code, [200, 404]);
  8495. },
  8496. select_file: Runtime.capTrue,
  8497. select_multiple: Runtime.capTrue,
  8498. send_binary_string: Runtime.capTrue,
  8499. send_browser_cookies: function(value) {
  8500. return value && I.mode === 'browser';
  8501. },
  8502. send_custom_headers: function(value) {
  8503. return value && I.mode === 'client';
  8504. },
  8505. send_multipart: Runtime.capTrue,
  8506. slice_blob: Runtime.capTrue,
  8507. stream_upload: true,
  8508. summon_file_dialog: false,
  8509. upload_filesize: Runtime.capTrue,
  8510. use_http_method: function(methods) {
  8511. return I.mode === 'client' || !Basic.arrayDiff(methods, ['GET', 'POST']);
  8512. }
  8513. }, {
  8514. // capabilities that require specific mode
  8515. return_response_headers: function(value) {
  8516. return value ? 'client' : 'browser';
  8517. },
  8518. return_status_code: function(code) {
  8519. return Basic.arrayDiff(code, [200, 404]) ? 'client' : ['client', 'browser'];
  8520. },
  8521. send_browser_cookies: function(value) {
  8522. return value ? 'browser' : 'client';
  8523. },
  8524. send_custom_headers: function(value) {
  8525. return value ? 'client' : 'browser';
  8526. },
  8527. use_http_method: function(methods) {
  8528. return Basic.arrayDiff(methods, ['GET', 'POST']) ? 'client' : ['client', 'browser'];
  8529. }
  8530. });
  8531. // minimal requirement
  8532. if (!isInstalled('2.0.31005.0') || Env.browser === 'Opera') {
  8533. if (MXI_DEBUG && Env.debug.runtime) {
  8534. Env.log("\tSilverlight is not installed or minimal version (2.0.31005.0) requirement not met (not likely).");
  8535. }
  8536. this.mode = false;
  8537. }
  8538. Basic.extend(this, {
  8539. getShim: function() {
  8540. return Dom.get(this.uid).content.Moxie;
  8541. },
  8542. shimExec: function(component, action) {
  8543. var args = [].slice.call(arguments, 2);
  8544. return I.getShim().exec(this.uid, component, action, args);
  8545. },
  8546. init : function() {
  8547. var container;
  8548. container = this.getShimContainer();
  8549. container.innerHTML = '<object id="' + this.uid + '" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%" style="outline:none;">' +
  8550. '<param name="source" value="' + options.xap_url + '"/>' +
  8551. '<param name="background" value="Transparent"/>' +
  8552. '<param name="windowless" value="true"/>' +
  8553. '<param name="enablehtmlaccess" value="true"/>' +
  8554. '<param name="initParams" value="uid=' + this.uid + ',target=' + Env.global_event_dispatcher + '"/>' +
  8555. '</object>';
  8556. // Init is dispatched by the shim
  8557. initTimer = setTimeout(function() {
  8558. if (I && !I.initialized) { // runtime might be already destroyed by this moment
  8559. I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
  8560. if (MXI_DEBUG && Env.debug.runtime) {
  8561. Env.log("\Silverlight failed to initialize within a specified period of time (5-10s).");
  8562. }
  8563. }
  8564. }, Env.OS !== 'Windows'? 10000 : 5000); // give it more time to initialize in non Windows OS (like Mac)
  8565. },
  8566. destroy: (function(destroy) { // extend default destroy method
  8567. return function() {
  8568. destroy.call(I);
  8569. clearTimeout(initTimer); // initialization check might be still onwait
  8570. options = initTimer = destroy = I = null;
  8571. };
  8572. }(this.destroy))
  8573. }, extensions);
  8574. }
  8575. Runtime.addConstructor(type, SilverlightRuntime);
  8576. return extensions;
  8577. });
  8578. // Included from: src/javascript/runtime/silverlight/file/Blob.js
  8579. /**
  8580. * Blob.js
  8581. *
  8582. * Copyright 2013, Moxiecode Systems AB
  8583. * Released under GPL License.
  8584. *
  8585. * License: http://www.plupload.com/license
  8586. * Contributing: http://www.plupload.com/contributing
  8587. */
  8588. /**
  8589. @class moxie/runtime/silverlight/file/Blob
  8590. @private
  8591. */
  8592. define("moxie/runtime/silverlight/file/Blob", [
  8593. "moxie/runtime/silverlight/Runtime",
  8594. "moxie/core/utils/Basic",
  8595. "moxie/runtime/flash/file/Blob"
  8596. ], function(extensions, Basic, Blob) {
  8597. return (extensions.Blob = Basic.extend({}, Blob));
  8598. });
  8599. // Included from: src/javascript/runtime/silverlight/file/FileInput.js
  8600. /**
  8601. * FileInput.js
  8602. *
  8603. * Copyright 2013, Moxiecode Systems AB
  8604. * Released under GPL License.
  8605. *
  8606. * License: http://www.plupload.com/license
  8607. * Contributing: http://www.plupload.com/contributing
  8608. */
  8609. /**
  8610. @class moxie/runtime/silverlight/file/FileInput
  8611. @private
  8612. */
  8613. define("moxie/runtime/silverlight/file/FileInput", [
  8614. "moxie/runtime/silverlight/Runtime",
  8615. "moxie/file/File",
  8616. "moxie/core/utils/Basic"
  8617. ], function(extensions, File, Basic) {
  8618. function toFilters(accept) {
  8619. var filter = '';
  8620. for (var i = 0; i < accept.length; i++) {
  8621. filter += (filter !== '' ? '|' : '') + accept[i].title + " | *." + accept[i].extensions.replace(/,/g, ';*.');
  8622. }
  8623. return filter;
  8624. }
  8625. var FileInput = {
  8626. init: function(options) {
  8627. var comp = this, I = this.getRuntime();
  8628. this.bind("Change", function() {
  8629. var files = I.shimExec.call(comp, 'FileInput', 'getFiles');
  8630. comp.files = [];
  8631. Basic.each(files, function(file) {
  8632. comp.files.push(new File(I.uid, file));
  8633. });
  8634. }, 999);
  8635. I.shimExec.call(this, 'FileInput', 'init', toFilters(options.accept), options.multiple);
  8636. this.trigger('ready');
  8637. },
  8638. setOption: function(name, value) {
  8639. if (name == 'accept') {
  8640. value = toFilters(value);
  8641. }
  8642. this.getRuntime().shimExec.call(this, 'FileInput', 'setOption', name, value);
  8643. }
  8644. };
  8645. return (extensions.FileInput = FileInput);
  8646. });
  8647. // Included from: src/javascript/runtime/silverlight/file/FileDrop.js
  8648. /**
  8649. * FileDrop.js
  8650. *
  8651. * Copyright 2013, Moxiecode Systems AB
  8652. * Released under GPL License.
  8653. *
  8654. * License: http://www.plupload.com/license
  8655. * Contributing: http://www.plupload.com/contributing
  8656. */
  8657. /**
  8658. @class moxie/runtime/silverlight/file/FileDrop
  8659. @private
  8660. */
  8661. define("moxie/runtime/silverlight/file/FileDrop", [
  8662. "moxie/runtime/silverlight/Runtime",
  8663. "moxie/core/utils/Dom",
  8664. "moxie/core/utils/Events"
  8665. ], function(extensions, Dom, Events) {
  8666. // not exactly useful, since works only in safari (...crickets...)
  8667. var FileDrop = {
  8668. init: function() {
  8669. var comp = this, self = comp.getRuntime(), dropZone;
  8670. dropZone = self.getShimContainer();
  8671. Events.addEvent(dropZone, 'dragover', function(e) {
  8672. e.preventDefault();
  8673. e.stopPropagation();
  8674. e.dataTransfer.dropEffect = 'copy';
  8675. }, comp.uid);
  8676. Events.addEvent(dropZone, 'dragenter', function(e) {
  8677. e.preventDefault();
  8678. var flag = Dom.get(self.uid).dragEnter(e);
  8679. // If handled, then stop propagation of event in DOM
  8680. if (flag) {
  8681. e.stopPropagation();
  8682. }
  8683. }, comp.uid);
  8684. Events.addEvent(dropZone, 'drop', function(e) {
  8685. e.preventDefault();
  8686. var flag = Dom.get(self.uid).dragDrop(e);
  8687. // If handled, then stop propagation of event in DOM
  8688. if (flag) {
  8689. e.stopPropagation();
  8690. }
  8691. }, comp.uid);
  8692. return self.shimExec.call(this, 'FileDrop', 'init');
  8693. }
  8694. };
  8695. return (extensions.FileDrop = FileDrop);
  8696. });
  8697. // Included from: src/javascript/runtime/silverlight/file/FileReader.js
  8698. /**
  8699. * FileReader.js
  8700. *
  8701. * Copyright 2013, Moxiecode Systems AB
  8702. * Released under GPL License.
  8703. *
  8704. * License: http://www.plupload.com/license
  8705. * Contributing: http://www.plupload.com/contributing
  8706. */
  8707. /**
  8708. @class moxie/runtime/silverlight/file/FileReader
  8709. @private
  8710. */
  8711. define("moxie/runtime/silverlight/file/FileReader", [
  8712. "moxie/runtime/silverlight/Runtime",
  8713. "moxie/core/utils/Basic",
  8714. "moxie/runtime/flash/file/FileReader"
  8715. ], function(extensions, Basic, FileReader) {
  8716. return (extensions.FileReader = Basic.extend({}, FileReader));
  8717. });
  8718. // Included from: src/javascript/runtime/silverlight/file/FileReaderSync.js
  8719. /**
  8720. * FileReaderSync.js
  8721. *
  8722. * Copyright 2013, Moxiecode Systems AB
  8723. * Released under GPL License.
  8724. *
  8725. * License: http://www.plupload.com/license
  8726. * Contributing: http://www.plupload.com/contributing
  8727. */
  8728. /**
  8729. @class moxie/runtime/silverlight/file/FileReaderSync
  8730. @private
  8731. */
  8732. define("moxie/runtime/silverlight/file/FileReaderSync", [
  8733. "moxie/runtime/silverlight/Runtime",
  8734. "moxie/core/utils/Basic",
  8735. "moxie/runtime/flash/file/FileReaderSync"
  8736. ], function(extensions, Basic, FileReaderSync) {
  8737. return (extensions.FileReaderSync = Basic.extend({}, FileReaderSync));
  8738. });
  8739. // Included from: src/javascript/runtime/silverlight/runtime/Transporter.js
  8740. /**
  8741. * Transporter.js
  8742. *
  8743. * Copyright 2013, Moxiecode Systems AB
  8744. * Released under GPL License.
  8745. *
  8746. * License: http://www.plupload.com/license
  8747. * Contributing: http://www.plupload.com/contributing
  8748. */
  8749. /**
  8750. @class moxie/runtime/silverlight/runtime/Transporter
  8751. @private
  8752. */
  8753. define("moxie/runtime/silverlight/runtime/Transporter", [
  8754. "moxie/runtime/silverlight/Runtime",
  8755. "moxie/core/utils/Basic",
  8756. "moxie/runtime/flash/runtime/Transporter"
  8757. ], function(extensions, Basic, Transporter) {
  8758. return (extensions.Transporter = Basic.extend({}, Transporter));
  8759. });
  8760. // Included from: src/javascript/runtime/silverlight/xhr/XMLHttpRequest.js
  8761. /**
  8762. * XMLHttpRequest.js
  8763. *
  8764. * Copyright 2013, Moxiecode Systems AB
  8765. * Released under GPL License.
  8766. *
  8767. * License: http://www.plupload.com/license
  8768. * Contributing: http://www.plupload.com/contributing
  8769. */
  8770. /**
  8771. @class moxie/runtime/silverlight/xhr/XMLHttpRequest
  8772. @private
  8773. */
  8774. define("moxie/runtime/silverlight/xhr/XMLHttpRequest", [
  8775. "moxie/runtime/silverlight/Runtime",
  8776. "moxie/core/utils/Basic",
  8777. "moxie/runtime/flash/xhr/XMLHttpRequest",
  8778. "moxie/runtime/silverlight/file/FileReaderSync",
  8779. "moxie/runtime/silverlight/runtime/Transporter"
  8780. ], function(extensions, Basic, XMLHttpRequest, FileReaderSyncSilverlight, TransporterSilverlight) {
  8781. return (extensions.XMLHttpRequest = Basic.extend({}, XMLHttpRequest));
  8782. });
  8783. // Included from: src/javascript/runtime/silverlight/image/Image.js
  8784. /**
  8785. * Image.js
  8786. *
  8787. * Copyright 2013, Moxiecode Systems AB
  8788. * Released under GPL License.
  8789. *
  8790. * License: http://www.plupload.com/license
  8791. * Contributing: http://www.plupload.com/contributing
  8792. */
  8793. /**
  8794. @class moxie/runtime/silverlight/image/Image
  8795. @private
  8796. */
  8797. define("moxie/runtime/silverlight/image/Image", [
  8798. "moxie/runtime/silverlight/Runtime",
  8799. "moxie/core/utils/Basic",
  8800. "moxie/file/Blob",
  8801. "moxie/runtime/flash/image/Image"
  8802. ], function(extensions, Basic, Blob, Image) {
  8803. return (extensions.Image = Basic.extend({}, Image, {
  8804. getInfo: function() {
  8805. var self = this.getRuntime()
  8806. , grps = ['tiff', 'exif', 'gps', 'thumb']
  8807. , info = { meta: {} }
  8808. , rawInfo = self.shimExec.call(this, 'Image', 'getInfo')
  8809. ;
  8810. if (rawInfo.meta) {
  8811. Basic.each(grps, function(grp) {
  8812. var meta = rawInfo.meta[grp]
  8813. , tag
  8814. , i
  8815. , length
  8816. , value
  8817. ;
  8818. if (meta && meta.keys) {
  8819. info.meta[grp] = {};
  8820. for (i = 0, length = meta.keys.length; i < length; i++) {
  8821. tag = meta.keys[i];
  8822. value = meta[tag];
  8823. if (value) {
  8824. // convert numbers
  8825. if (/^(\d|[1-9]\d+)$/.test(value)) { // integer (make sure doesn't start with zero)
  8826. value = parseInt(value, 10);
  8827. } else if (/^\d*\.\d+$/.test(value)) { // double
  8828. value = parseFloat(value);
  8829. }
  8830. info.meta[grp][tag] = value;
  8831. }
  8832. }
  8833. }
  8834. });
  8835. // save thumb data as blob
  8836. if (info.meta && info.meta.thumb && !(info.meta.thumb.data instanceof Blob)) {
  8837. info.meta.thumb.data = new Blob(self.uid, info.meta.thumb.data);
  8838. }
  8839. }
  8840. info.width = parseInt(rawInfo.width, 10);
  8841. info.height = parseInt(rawInfo.height, 10);
  8842. info.size = parseInt(rawInfo.size, 10);
  8843. info.type = rawInfo.type;
  8844. info.name = rawInfo.name;
  8845. return info;
  8846. },
  8847. resize: function(rect, ratio, opts) {
  8848. this.getRuntime().shimExec.call(this, 'Image', 'resize', rect.x, rect.y, rect.width, rect.height, ratio, opts.preserveHeaders, opts.resample);
  8849. }
  8850. }));
  8851. });
  8852. // Included from: src/javascript/runtime/html4/Runtime.js
  8853. /**
  8854. * Runtime.js
  8855. *
  8856. * Copyright 2013, Moxiecode Systems AB
  8857. * Released under GPL License.
  8858. *
  8859. * License: http://www.plupload.com/license
  8860. * Contributing: http://www.plupload.com/contributing
  8861. */
  8862. /*global File:true */
  8863. /**
  8864. Defines constructor for HTML4 runtime.
  8865. @class moxie/runtime/html4/Runtime
  8866. @private
  8867. */
  8868. define("moxie/runtime/html4/Runtime", [
  8869. "moxie/core/utils/Basic",
  8870. "moxie/core/Exceptions",
  8871. "moxie/runtime/Runtime",
  8872. "moxie/core/utils/Env"
  8873. ], function(Basic, x, Runtime, Env) {
  8874. var type = 'html4', extensions = {};
  8875. function Html4Runtime(options) {
  8876. var I = this
  8877. , Test = Runtime.capTest
  8878. , True = Runtime.capTrue
  8879. ;
  8880. Runtime.call(this, options, type, {
  8881. access_binary: Test(window.FileReader || window.File && File.getAsDataURL),
  8882. access_image_binary: false,
  8883. display_media: Test(
  8884. (Env.can('create_canvas') || Env.can('use_data_uri_over32kb')) &&
  8885. defined('moxie/image/Image')
  8886. ),
  8887. do_cors: false,
  8888. drag_and_drop: false,
  8889. filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
  8890. return !(
  8891. (Env.browser === 'Chrome' && Env.verComp(Env.version, 28, '<')) ||
  8892. (Env.browser === 'IE' && Env.verComp(Env.version, 10, '<')) ||
  8893. (Env.browser === 'Safari' && Env.verComp(Env.version, 7, '<')) ||
  8894. (Env.browser === 'Firefox' && Env.verComp(Env.version, 37, '<'))
  8895. );
  8896. }()),
  8897. resize_image: function() {
  8898. return extensions.Image && I.can('access_binary') && Env.can('create_canvas');
  8899. },
  8900. report_upload_progress: false,
  8901. return_response_headers: false,
  8902. return_response_type: function(responseType) {
  8903. if (responseType === 'json' && !!window.JSON) {
  8904. return true;
  8905. }
  8906. return !!~Basic.inArray(responseType, ['text', 'document', '']);
  8907. },
  8908. return_status_code: function(code) {
  8909. return !Basic.arrayDiff(code, [200, 404]);
  8910. },
  8911. select_file: function() {
  8912. return Env.can('use_fileinput');
  8913. },
  8914. select_multiple: false,
  8915. send_binary_string: false,
  8916. send_custom_headers: false,
  8917. send_multipart: true,
  8918. slice_blob: false,
  8919. stream_upload: function() {
  8920. return I.can('select_file');
  8921. },
  8922. summon_file_dialog: function() { // yeah... some dirty sniffing here...
  8923. return I.can('select_file') && (
  8924. (Env.browser === 'Firefox' && Env.verComp(Env.version, 4, '>=')) ||
  8925. (Env.browser === 'Opera' && Env.verComp(Env.version, 12, '>=')) ||
  8926. (Env.browser === 'IE' && Env.verComp(Env.version, 10, '>=')) ||
  8927. !!~Basic.inArray(Env.browser, ['Chrome', 'Safari'])
  8928. );
  8929. },
  8930. upload_filesize: True,
  8931. use_http_method: function(methods) {
  8932. return !Basic.arrayDiff(methods, ['GET', 'POST']);
  8933. }
  8934. });
  8935. Basic.extend(this, {
  8936. init : function() {
  8937. this.trigger("Init");
  8938. },
  8939. destroy: (function(destroy) { // extend default destroy method
  8940. return function() {
  8941. destroy.call(I);
  8942. destroy = I = null;
  8943. };
  8944. }(this.destroy))
  8945. });
  8946. Basic.extend(this.getShim(), extensions);
  8947. }
  8948. Runtime.addConstructor(type, Html4Runtime);
  8949. return extensions;
  8950. });
  8951. // Included from: src/javascript/runtime/html4/file/FileInput.js
  8952. /**
  8953. * FileInput.js
  8954. *
  8955. * Copyright 2013, Moxiecode Systems AB
  8956. * Released under GPL License.
  8957. *
  8958. * License: http://www.plupload.com/license
  8959. * Contributing: http://www.plupload.com/contributing
  8960. */
  8961. /**
  8962. @class moxie/runtime/html4/file/FileInput
  8963. @private
  8964. */
  8965. define("moxie/runtime/html4/file/FileInput", [
  8966. "moxie/runtime/html4/Runtime",
  8967. "moxie/file/File",
  8968. "moxie/core/utils/Basic",
  8969. "moxie/core/utils/Dom",
  8970. "moxie/core/utils/Events",
  8971. "moxie/core/utils/Mime",
  8972. "moxie/core/utils/Env"
  8973. ], function(extensions, File, Basic, Dom, Events, Mime, Env) {
  8974. function FileInput() {
  8975. var _uid, _mimes = [], _options, _browseBtnZIndex; // save original z-index;
  8976. function addInput() {
  8977. var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid;
  8978. uid = Basic.guid('uid_');
  8979. shimContainer = I.getShimContainer(); // we get new ref every time to avoid memory leaks in IE
  8980. if (_uid) { // move previous form out of the view
  8981. currForm = Dom.get(_uid + '_form');
  8982. if (currForm) {
  8983. Basic.extend(currForm.style, { top: '100%' });
  8984. }
  8985. }
  8986. // build form in DOM, since innerHTML version not able to submit file for some reason
  8987. form = document.createElement('form');
  8988. form.setAttribute('id', uid + '_form');
  8989. form.setAttribute('method', 'post');
  8990. form.setAttribute('enctype', 'multipart/form-data');
  8991. form.setAttribute('encoding', 'multipart/form-data');
  8992. Basic.extend(form.style, {
  8993. overflow: 'hidden',
  8994. position: 'absolute',
  8995. top: 0,
  8996. left: 0,
  8997. width: '100%',
  8998. height: '100%'
  8999. });
  9000. input = document.createElement('input');
  9001. input.setAttribute('id', uid);
  9002. input.setAttribute('type', 'file');
  9003. input.setAttribute('accept', _mimes.join(','));
  9004. Basic.extend(input.style, {
  9005. fontSize: '999px',
  9006. opacity: 0
  9007. });
  9008. form.appendChild(input);
  9009. shimContainer.appendChild(form);
  9010. // prepare file input to be placed underneath the browse_button element
  9011. Basic.extend(input.style, {
  9012. position: 'absolute',
  9013. top: 0,
  9014. left: 0,
  9015. width: '100%',
  9016. height: '100%'
  9017. });
  9018. if (Env.browser === 'IE' && Env.verComp(Env.version, 10, '<')) {
  9019. Basic.extend(input.style, {
  9020. filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)"
  9021. });
  9022. }
  9023. input.onchange = function() { // there should be only one handler for this
  9024. var file;
  9025. if (!this.value) {
  9026. return;
  9027. }
  9028. if (this.files) { // check if browser is fresh enough
  9029. file = this.files[0];
  9030. // ignore empty files (IE10 for example hangs if you try to send them via XHR)
  9031. if (file.size === 0) {
  9032. form.parentNode.removeChild(form);
  9033. return;
  9034. }
  9035. } else {
  9036. file = {
  9037. name: this.value
  9038. };
  9039. }
  9040. file = new File(I.uid, file);
  9041. // clear event handler
  9042. this.onchange = function() {};
  9043. addInput.call(comp);
  9044. comp.files = [file];
  9045. // substitute all ids with file uids (consider file.uid read-only - we cannot do it the other way around)
  9046. input.setAttribute('id', file.uid);
  9047. form.setAttribute('id', file.uid + '_form');
  9048. comp.trigger('change');
  9049. input = form = null;
  9050. };
  9051. // route click event to the input
  9052. if (I.can('summon_file_dialog')) {
  9053. browseButton = Dom.get(_options.browse_button);
  9054. Events.removeEvent(browseButton, 'click', comp.uid);
  9055. Events.addEvent(browseButton, 'click', function(e) {
  9056. if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file]
  9057. input.click();
  9058. }
  9059. e.preventDefault();
  9060. }, comp.uid);
  9061. }
  9062. _uid = uid;
  9063. shimContainer = currForm = browseButton = null;
  9064. }
  9065. Basic.extend(this, {
  9066. init: function(options) {
  9067. var comp = this, I = comp.getRuntime(), shimContainer;
  9068. // figure out accept string
  9069. _options = options;
  9070. _mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension'));
  9071. shimContainer = I.getShimContainer();
  9072. (function() {
  9073. var browseButton, zIndex, top;
  9074. browseButton = Dom.get(options.browse_button);
  9075. _browseBtnZIndex = Dom.getStyle(browseButton, 'z-index') || 'auto';
  9076. // Route click event to the input[type=file] element for browsers that support such behavior
  9077. if (I.can('summon_file_dialog')) {
  9078. if (Dom.getStyle(browseButton, 'position') === 'static') {
  9079. browseButton.style.position = 'relative';
  9080. }
  9081. comp.bind('Refresh', function() {
  9082. zIndex = parseInt(_browseBtnZIndex, 10) || 1;
  9083. Dom.get(_options.browse_button).style.zIndex = zIndex;
  9084. this.getRuntime().getShimContainer().style.zIndex = zIndex - 1;
  9085. });
  9086. }
  9087. /* Since we have to place input[type=file] on top of the browse_button for some browsers,
  9088. browse_button loses interactivity, so we restore it here */
  9089. top = I.can('summon_file_dialog') ? browseButton : shimContainer;
  9090. Events.addEvent(top, 'mouseover', function() {
  9091. comp.trigger('mouseenter');
  9092. }, comp.uid);
  9093. Events.addEvent(top, 'mouseout', function() {
  9094. comp.trigger('mouseleave');
  9095. }, comp.uid);
  9096. Events.addEvent(top, 'mousedown', function() {
  9097. comp.trigger('mousedown');
  9098. }, comp.uid);
  9099. Events.addEvent(Dom.get(options.container), 'mouseup', function() {
  9100. comp.trigger('mouseup');
  9101. }, comp.uid);
  9102. browseButton = null;
  9103. }());
  9104. addInput.call(this);
  9105. shimContainer = null;
  9106. // trigger ready event asynchronously
  9107. comp.trigger({
  9108. type: 'ready',
  9109. async: true
  9110. });
  9111. },
  9112. setOption: function(name, value) {
  9113. var I = this.getRuntime();
  9114. var input;
  9115. if (name == 'accept') {
  9116. _mimes = value.mimes || Mime.extList2mimes(value, I.can('filter_by_extension'));
  9117. }
  9118. // update current input
  9119. input = Dom.get(_uid)
  9120. if (input) {
  9121. input.setAttribute('accept', _mimes.join(','));
  9122. }
  9123. },
  9124. disable: function(state) {
  9125. var input;
  9126. if ((input = Dom.get(_uid))) {
  9127. input.disabled = !!state;
  9128. }
  9129. },
  9130. destroy: function() {
  9131. var I = this.getRuntime()
  9132. , shim = I.getShim()
  9133. , shimContainer = I.getShimContainer()
  9134. , container = _options && Dom.get(_options.container)
  9135. , browseButton = _options && Dom.get(_options.browse_button)
  9136. ;
  9137. if (container) {
  9138. Events.removeAllEvents(container, this.uid);
  9139. }
  9140. if (browseButton) {
  9141. Events.removeAllEvents(browseButton, this.uid);
  9142. browseButton.style.zIndex = _browseBtnZIndex; // reset to original value
  9143. }
  9144. if (shimContainer) {
  9145. Events.removeAllEvents(shimContainer, this.uid);
  9146. shimContainer.innerHTML = '';
  9147. }
  9148. shim.removeInstance(this.uid);
  9149. _uid = _mimes = _options = shimContainer = container = browseButton = shim = null;
  9150. }
  9151. });
  9152. }
  9153. return (extensions.FileInput = FileInput);
  9154. });
  9155. // Included from: src/javascript/runtime/html4/file/FileReader.js
  9156. /**
  9157. * FileReader.js
  9158. *
  9159. * Copyright 2013, Moxiecode Systems AB
  9160. * Released under GPL License.
  9161. *
  9162. * License: http://www.plupload.com/license
  9163. * Contributing: http://www.plupload.com/contributing
  9164. */
  9165. /**
  9166. @class moxie/runtime/html4/file/FileReader
  9167. @private
  9168. */
  9169. define("moxie/runtime/html4/file/FileReader", [
  9170. "moxie/runtime/html4/Runtime",
  9171. "moxie/runtime/html5/file/FileReader"
  9172. ], function(extensions, FileReader) {
  9173. return (extensions.FileReader = FileReader);
  9174. });
  9175. // Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js
  9176. /**
  9177. * XMLHttpRequest.js
  9178. *
  9179. * Copyright 2013, Moxiecode Systems AB
  9180. * Released under GPL License.
  9181. *
  9182. * License: http://www.plupload.com/license
  9183. * Contributing: http://www.plupload.com/contributing
  9184. */
  9185. /**
  9186. @class moxie/runtime/html4/xhr/XMLHttpRequest
  9187. @private
  9188. */
  9189. define("moxie/runtime/html4/xhr/XMLHttpRequest", [
  9190. "moxie/runtime/html4/Runtime",
  9191. "moxie/core/utils/Basic",
  9192. "moxie/core/utils/Dom",
  9193. "moxie/core/utils/Url",
  9194. "moxie/core/Exceptions",
  9195. "moxie/core/utils/Events",
  9196. "moxie/file/Blob",
  9197. "moxie/xhr/FormData"
  9198. ], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData) {
  9199. function XMLHttpRequest() {
  9200. var _status, _response, _iframe;
  9201. function cleanup(cb) {
  9202. var target = this, uid, form, inputs, i, hasFile = false;
  9203. if (!_iframe) {
  9204. return;
  9205. }
  9206. uid = _iframe.id.replace(/_iframe$/, '');
  9207. form = Dom.get(uid + '_form');
  9208. if (form) {
  9209. inputs = form.getElementsByTagName('input');
  9210. i = inputs.length;
  9211. while (i--) {
  9212. switch (inputs[i].getAttribute('type')) {
  9213. case 'hidden':
  9214. inputs[i].parentNode.removeChild(inputs[i]);
  9215. break;
  9216. case 'file':
  9217. hasFile = true; // flag the case for later
  9218. break;
  9219. }
  9220. }
  9221. inputs = [];
  9222. if (!hasFile) { // we need to keep the form for sake of possible retries
  9223. form.parentNode.removeChild(form);
  9224. }
  9225. form = null;
  9226. }
  9227. // without timeout, request is marked as canceled (in console)
  9228. setTimeout(function() {
  9229. Events.removeEvent(_iframe, 'load', target.uid);
  9230. if (_iframe.parentNode) { // #382
  9231. _iframe.parentNode.removeChild(_iframe);
  9232. }
  9233. // check if shim container has any other children, if - not, remove it as well
  9234. var shimContainer = target.getRuntime().getShimContainer();
  9235. if (!shimContainer.children.length) {
  9236. shimContainer.parentNode.removeChild(shimContainer);
  9237. }
  9238. shimContainer = _iframe = null;
  9239. cb();
  9240. }, 1);
  9241. }
  9242. Basic.extend(this, {
  9243. send: function(meta, data) {
  9244. var target = this, I = target.getRuntime(), uid, form, input, blob;
  9245. _status = _response = null;
  9246. function createIframe() {
  9247. var container = I.getShimContainer() || document.body
  9248. , temp = document.createElement('div')
  9249. ;
  9250. // IE 6 won't be able to set the name using setAttribute or iframe.name
  9251. temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:&quot;&quot;" style="display:none"></iframe>';
  9252. _iframe = temp.firstChild;
  9253. container.appendChild(_iframe);
  9254. /* _iframe.onreadystatechange = function() {
  9255. console.info(_iframe.readyState);
  9256. };*/
  9257. Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8
  9258. var el;
  9259. try {
  9260. el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document;
  9261. // try to detect some standard error pages
  9262. if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error
  9263. _status = el.title.replace(/^(\d+).*$/, '$1');
  9264. } else {
  9265. _status = 200;
  9266. // get result
  9267. _response = Basic.trim(el.body.innerHTML);
  9268. // we need to fire these at least once
  9269. target.trigger({
  9270. type: 'progress',
  9271. loaded: _response.length,
  9272. total: _response.length
  9273. });
  9274. if (blob) { // if we were uploading a file
  9275. target.trigger({
  9276. type: 'uploadprogress',
  9277. loaded: blob.size || 1025,
  9278. total: blob.size || 1025
  9279. });
  9280. }
  9281. }
  9282. } catch (ex) {
  9283. if (Url.hasSameOrigin(meta.url)) {
  9284. // if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm
  9285. // which obviously results to cross domain error (wtf?)
  9286. _status = 404;
  9287. } else {
  9288. cleanup.call(target, function() {
  9289. target.trigger('error');
  9290. });
  9291. return;
  9292. }
  9293. }
  9294. cleanup.call(target, function() {
  9295. target.trigger('load');
  9296. });
  9297. }, target.uid);
  9298. } // end createIframe
  9299. // prepare data to be sent and convert if required
  9300. if (data instanceof FormData && data.hasBlob()) {
  9301. blob = data.getBlob();
  9302. uid = blob.uid;
  9303. input = Dom.get(uid);
  9304. form = Dom.get(uid + '_form');
  9305. if (!form) {
  9306. throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
  9307. }
  9308. } else {
  9309. uid = Basic.guid('uid_');
  9310. form = document.createElement('form');
  9311. form.setAttribute('id', uid + '_form');
  9312. form.setAttribute('method', meta.method);
  9313. form.setAttribute('enctype', 'multipart/form-data');
  9314. form.setAttribute('encoding', 'multipart/form-data');
  9315. I.getShimContainer().appendChild(form);
  9316. }
  9317. // set upload target
  9318. form.setAttribute('target', uid + '_iframe');
  9319. if (data instanceof FormData) {
  9320. data.each(function(value, name) {
  9321. if (value instanceof Blob) {
  9322. if (input) {
  9323. input.setAttribute('name', name);
  9324. }
  9325. } else {
  9326. var hidden = document.createElement('input');
  9327. Basic.extend(hidden, {
  9328. type : 'hidden',
  9329. name : name,
  9330. value : value
  9331. });
  9332. // make sure that input[type="file"], if it's there, comes last
  9333. if (input) {
  9334. form.insertBefore(hidden, input);
  9335. } else {
  9336. form.appendChild(hidden);
  9337. }
  9338. }
  9339. });
  9340. }
  9341. // set destination url
  9342. form.setAttribute("action", meta.url);
  9343. createIframe();
  9344. form.submit();
  9345. target.trigger('loadstart');
  9346. },
  9347. getStatus: function() {
  9348. return _status;
  9349. },
  9350. getResponse: function(responseType) {
  9351. if ('json' === responseType) {
  9352. // strip off <pre>..</pre> tags that might be enclosing the response
  9353. if (Basic.typeOf(_response) === 'string' && !!window.JSON) {
  9354. try {
  9355. return JSON.parse(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, ''));
  9356. } catch (ex) {
  9357. return null;
  9358. }
  9359. }
  9360. } else if ('document' === responseType) {
  9361. }
  9362. return _response;
  9363. },
  9364. abort: function() {
  9365. var target = this;
  9366. if (_iframe && _iframe.contentWindow) {
  9367. if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome
  9368. _iframe.contentWindow.stop();
  9369. } else if (_iframe.contentWindow.document.execCommand) { // IE
  9370. _iframe.contentWindow.document.execCommand('Stop');
  9371. } else {
  9372. _iframe.src = "about:blank";
  9373. }
  9374. }
  9375. cleanup.call(this, function() {
  9376. // target.dispatchEvent('readystatechange');
  9377. target.dispatchEvent('abort');
  9378. });
  9379. }
  9380. });
  9381. }
  9382. return (extensions.XMLHttpRequest = XMLHttpRequest);
  9383. });
  9384. // Included from: src/javascript/runtime/html4/image/Image.js
  9385. /**
  9386. * Image.js
  9387. *
  9388. * Copyright 2013, Moxiecode Systems AB
  9389. * Released under GPL License.
  9390. *
  9391. * License: http://www.plupload.com/license
  9392. * Contributing: http://www.plupload.com/contributing
  9393. */
  9394. /**
  9395. @class moxie/runtime/html4/image/Image
  9396. @private
  9397. */
  9398. define("moxie/runtime/html4/image/Image", [
  9399. "moxie/runtime/html4/Runtime",
  9400. "moxie/runtime/html5/image/Image"
  9401. ], function(extensions, Image) {
  9402. return (extensions.Image = Image);
  9403. });
  9404. expose(["moxie/core/utils/Basic","moxie/core/utils/Encode","moxie/core/utils/Env","moxie/core/Exceptions","moxie/core/utils/Dom","moxie/core/EventTarget","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/core/I18n","moxie/core/utils/Mime","moxie/file/FileInput","moxie/file/File","moxie/file/FileDrop","moxie/file/FileReader","moxie/core/utils/Url","moxie/runtime/RuntimeTarget","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/image/Image","moxie/core/utils/Events","moxie/runtime/html5/image/ResizerCanvas"]);
  9405. })(this);
  9406. }));