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.

9901 lines
248 KiB

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