Section 1
//MD5 (com.adobe.crypto.MD5)
package com.adobe.crypto {
import com.adobe.utils.*;
public class MD5 {
public function MD5(){
super();
}
private static function ff(a:int, b:int, c:int, d:int, x:int, s:int, t:int):int{
return (transform(f, a, b, c, d, x, s, t));
}
private static function createBlocks(s:String):Array{
var blocks:Array = new Array();
var len:int = (s.length * 8);
var mask = 0xFF;
var i:int;
while (i < len) {
blocks[(i >> 5)] = (blocks[(i >> 5)] | ((s.charCodeAt((i / 8)) & mask) << (i % 32)));
i = (i + 8);
};
blocks[(len >> 5)] = (blocks[(len >> 5)] | (128 << (len % 32)));
blocks[((((len + 64) >>> 9) << 4) + 14)] = len;
return (blocks);
}
private static function ii(a:int, b:int, c:int, d:int, x:int, s:int, t:int):int{
return (transform(i, a, b, c, d, x, s, t));
}
private static function f(x:int, y:int, z:int):int{
return (((x & y) | (~(x) & z)));
}
private static function g(x:int, y:int, z:int):int{
return (((x & z) | (y & ~(z))));
}
private static function h(x:int, y:int, z:int):int{
return (((x ^ y) ^ z));
}
private static function i(x:int, y:int, z:int):int{
return ((y ^ (x | ~(z))));
}
private static function transform(func:Function, a:int, b:int, c:int, d:int, x:int, s:int, t:int):int{
var tmp:int = (((a + int(func(b, c, d))) + x) + t);
return ((IntUtil.rol(tmp, s) + b));
}
private static function hh(a:int, b:int, c:int, d:int, x:int, s:int, t:int):int{
return (transform(h, a, b, c, d, x, s, t));
}
public static function hash(s:String):String{
var aa:int;
var bb:int;
var cc:int;
var dd:int;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var x:Array = createBlocks(s);
var len:int = x.length;
var i:int;
while (i < len) {
aa = a;
bb = b;
cc = c;
dd = d;
a = ff(a, b, c, d, x[(i + 0)], 7, -680876936);
d = ff(d, a, b, c, x[(i + 1)], 12, -389564586);
c = ff(c, d, a, b, x[(i + 2)], 17, 606105819);
b = ff(b, c, d, a, x[(i + 3)], 22, -1044525330);
a = ff(a, b, c, d, x[(i + 4)], 7, -176418897);
d = ff(d, a, b, c, x[(i + 5)], 12, 1200080426);
c = ff(c, d, a, b, x[(i + 6)], 17, -1473231341);
b = ff(b, c, d, a, x[(i + 7)], 22, -45705983);
a = ff(a, b, c, d, x[(i + 8)], 7, 1770035416);
d = ff(d, a, b, c, x[(i + 9)], 12, -1958414417);
c = ff(c, d, a, b, x[(i + 10)], 17, -42063);
b = ff(b, c, d, a, x[(i + 11)], 22, -1990404162);
a = ff(a, b, c, d, x[(i + 12)], 7, 1804603682);
d = ff(d, a, b, c, x[(i + 13)], 12, -40341101);
c = ff(c, d, a, b, x[(i + 14)], 17, -1502002290);
b = ff(b, c, d, a, x[(i + 15)], 22, 1236535329);
a = gg(a, b, c, d, x[(i + 1)], 5, -165796510);
d = gg(d, a, b, c, x[(i + 6)], 9, -1069501632);
c = gg(c, d, a, b, x[(i + 11)], 14, 643717713);
b = gg(b, c, d, a, x[(i + 0)], 20, -373897302);
a = gg(a, b, c, d, x[(i + 5)], 5, -701558691);
d = gg(d, a, b, c, x[(i + 10)], 9, 38016083);
c = gg(c, d, a, b, x[(i + 15)], 14, -660478335);
b = gg(b, c, d, a, x[(i + 4)], 20, -405537848);
a = gg(a, b, c, d, x[(i + 9)], 5, 568446438);
d = gg(d, a, b, c, x[(i + 14)], 9, -1019803690);
c = gg(c, d, a, b, x[(i + 3)], 14, -187363961);
b = gg(b, c, d, a, x[(i + 8)], 20, 1163531501);
a = gg(a, b, c, d, x[(i + 13)], 5, -1444681467);
d = gg(d, a, b, c, x[(i + 2)], 9, -51403784);
c = gg(c, d, a, b, x[(i + 7)], 14, 1735328473);
b = gg(b, c, d, a, x[(i + 12)], 20, -1926607734);
a = hh(a, b, c, d, x[(i + 5)], 4, -378558);
d = hh(d, a, b, c, x[(i + 8)], 11, -2022574463);
c = hh(c, d, a, b, x[(i + 11)], 16, 1839030562);
b = hh(b, c, d, a, x[(i + 14)], 23, -35309556);
a = hh(a, b, c, d, x[(i + 1)], 4, -1530992060);
d = hh(d, a, b, c, x[(i + 4)], 11, 1272893353);
c = hh(c, d, a, b, x[(i + 7)], 16, -155497632);
b = hh(b, c, d, a, x[(i + 10)], 23, -1094730640);
a = hh(a, b, c, d, x[(i + 13)], 4, 681279174);
d = hh(d, a, b, c, x[(i + 0)], 11, -358537222);
c = hh(c, d, a, b, x[(i + 3)], 16, -722521979);
b = hh(b, c, d, a, x[(i + 6)], 23, 76029189);
a = hh(a, b, c, d, x[(i + 9)], 4, -640364487);
d = hh(d, a, b, c, x[(i + 12)], 11, -421815835);
c = hh(c, d, a, b, x[(i + 15)], 16, 530742520);
b = hh(b, c, d, a, x[(i + 2)], 23, -995338651);
a = ii(a, b, c, d, x[(i + 0)], 6, -198630844);
d = ii(d, a, b, c, x[(i + 7)], 10, 1126891415);
c = ii(c, d, a, b, x[(i + 14)], 15, -1416354905);
b = ii(b, c, d, a, x[(i + 5)], 21, -57434055);
a = ii(a, b, c, d, x[(i + 12)], 6, 1700485571);
d = ii(d, a, b, c, x[(i + 3)], 10, -1894986606);
c = ii(c, d, a, b, x[(i + 10)], 15, -1051523);
b = ii(b, c, d, a, x[(i + 1)], 21, -2054922799);
a = ii(a, b, c, d, x[(i + 8)], 6, 1873313359);
d = ii(d, a, b, c, x[(i + 15)], 10, -30611744);
c = ii(c, d, a, b, x[(i + 6)], 15, -1560198380);
b = ii(b, c, d, a, x[(i + 13)], 21, 1309151649);
a = ii(a, b, c, d, x[(i + 4)], 6, -145523070);
d = ii(d, a, b, c, x[(i + 11)], 10, -1120210379);
c = ii(c, d, a, b, x[(i + 2)], 15, 718787259);
b = ii(b, c, d, a, x[(i + 9)], 21, -343485551);
a = (a + aa);
b = (b + bb);
c = (c + cc);
d = (d + dd);
i = (i + 16);
};
return ((((IntUtil.toHex(a) + IntUtil.toHex(b)) + IntUtil.toHex(c)) + IntUtil.toHex(d)));
}
private static function gg(a:int, b:int, c:int, d:int, x:int, s:int, t:int):int{
return (transform(g, a, b, c, d, x, s, t));
}
}
}//package com.adobe.crypto
Section 2
//JSON (com.adobe.serialization.json.JSON)
package com.adobe.serialization.json {
public class JSON {
public function JSON(){
super();
}
public static function decode(s:String){
var decoder:JSONDecoder = new JSONDecoder(s);
return (decoder.getValue());
}
public static function encode(o:Object):String{
var encoder:JSONEncoder = new JSONEncoder(o);
return (encoder.getString());
}
}
}//package com.adobe.serialization.json
Section 3
//JSONDecoder (com.adobe.serialization.json.JSONDecoder)
package com.adobe.serialization.json {
public class JSONDecoder {
private var value;
private var tokenizer:JSONTokenizer;
private var token:JSONToken;
public function JSONDecoder(s:String){
super();
tokenizer = new JSONTokenizer(s);
nextToken();
value = parseValue();
}
private function parseObject():Object{
var key:String;
var o:Object = new Object();
nextToken();
if (token.type == JSONTokenType.RIGHT_BRACE){
return (o);
};
while (true) {
if (token.type == JSONTokenType.STRING){
key = String(token.value);
nextToken();
if (token.type == JSONTokenType.COLON){
nextToken();
o[key] = parseValue();
nextToken();
if (token.type == JSONTokenType.RIGHT_BRACE){
return (o);
};
if (token.type == JSONTokenType.COMMA){
nextToken();
} else {
tokenizer.parseError(("Expecting } or , but found " + token.value));
};
} else {
tokenizer.parseError(("Expecting : but found " + token.value));
};
} else {
tokenizer.parseError(("Expecting string but found " + token.value));
};
};
return (null);
}
private function parseValue():Object{
switch (token.type){
case JSONTokenType.LEFT_BRACE:
return (parseObject());
case JSONTokenType.LEFT_BRACKET:
return (parseArray());
case JSONTokenType.STRING:
case JSONTokenType.NUMBER:
case JSONTokenType.TRUE:
case JSONTokenType.FALSE:
case JSONTokenType.NULL:
return (token.value);
default:
tokenizer.parseError(("Unexpected " + token.value));
};
return (null);
}
private function nextToken():JSONToken{
return ((token = tokenizer.getNextToken()));
}
public function getValue(){
return (value);
}
private function parseArray():Array{
var a:Array = new Array();
nextToken();
if (token.type == JSONTokenType.RIGHT_BRACKET){
return (a);
};
while (true) {
a.push(parseValue());
nextToken();
if (token.type == JSONTokenType.RIGHT_BRACKET){
return (a);
};
if (token.type == JSONTokenType.COMMA){
nextToken();
} else {
tokenizer.parseError(("Expecting ] or , but found " + token.value));
};
};
return (null);
}
}
}//package com.adobe.serialization.json
Section 4
//JSONEncoder (com.adobe.serialization.json.JSONEncoder)
package com.adobe.serialization.json {
import flash.utils.*;
public class JSONEncoder {
private var jsonString:String;
public function JSONEncoder(value){
super();
jsonString = convertToString(value);
}
private function escapeString(str:String):String{
var ch:String;
var hexCode:String;
var zeroPad:String;
var s:String = "";
var len:Number = str.length;
var i:int;
while (i < len) {
ch = str.charAt(i);
switch (ch){
case "\"":
s = (s + "\\\"");
break;
case "\\":
s = (s + "\\\\");
break;
case "\b":
s = (s + "\\b");
break;
case "\f":
s = (s + "\\f");
break;
case "\n":
s = (s + "\\n");
break;
case "\r":
s = (s + "\\r");
break;
case "\t":
s = (s + "\\t");
break;
default:
if (ch < " "){
hexCode = ch.charCodeAt(0).toString(16);
zeroPad = ((hexCode.length == 2)) ? "00" : "000";
s = (s + (("\\u" + zeroPad) + hexCode));
} else {
s = (s + ch);
};
};
i++;
};
return ((("\"" + s) + "\""));
}
private function arrayToString(a:Array):String{
var s:String = "";
var i:int;
while (i < a.length) {
if (s.length > 0){
s = (s + ",");
};
s = (s + convertToString(a[i]));
i++;
};
return ((("[" + s) + "]"));
}
public function getString():String{
return (jsonString);
}
private function objectToString(o:Object):String{
var value:Object;
var key:String;
var v:XML;
var o = o;
var s = "";
var classInfo:XML = describeType(o);
if (classInfo.@name.toString() == "Object"){
for (key in o) {
value = o[key];
if ((value is Function)){
} else {
if (s.length > 0){
s = (s + ",");
};
s = (s + ((escapeString(key) + ":") + convertToString(value)));
};
};
} else {
for each (v in classInfo..*.(((name() == "variable")) || ((name() == "accessor")))) {
if (s.length > 0){
s = (s + ",");
};
s = (s + ((escapeString(v.@name.toString()) + ":") + convertToString(o[v.@name])));
};
};
return ((("{" + s) + "}"));
}
private function convertToString(value):String{
if ((value is String)){
return (escapeString((value as String)));
};
if ((value is Number)){
return ((isFinite((value as Number))) ? value.toString() : "null");
} else {
if ((value is Boolean)){
return ((value) ? "true" : "false");
} else {
if ((value is Array)){
return (arrayToString((value as Array)));
};
if ((((value is Object)) && (!((value == null))))){
return (objectToString(value));
};
};
};
return ("null");
}
}
}//package com.adobe.serialization.json
Section 5
//JSONParseError (com.adobe.serialization.json.JSONParseError)
package com.adobe.serialization.json {
public class JSONParseError extends Error {
private var _location:int;
private var _text:String;
public function JSONParseError(message:String="", location:int=0, text:String=""){
super(message);
_location = location;
_text = text;
}
public function get location():int{
return (_location);
}
public function get text():String{
return (_text);
}
}
}//package com.adobe.serialization.json
Section 6
//JSONToken (com.adobe.serialization.json.JSONToken)
package com.adobe.serialization.json {
public class JSONToken {
private var _value:Object;
private var _type:int;
public function JSONToken(type:int=-1, value:Object=null){
super();
_type = type;
_value = value;
}
public function get value():Object{
return (_value);
}
public function get type():int{
return (_type);
}
public function set type(value:int):void{
_type = value;
}
public function set value(v:Object):void{
_value = v;
}
}
}//package com.adobe.serialization.json
Section 7
//JSONTokenizer (com.adobe.serialization.json.JSONTokenizer)
package com.adobe.serialization.json {
public class JSONTokenizer {
private var loc:int;
private var ch:String;
private var obj:Object;
private var jsonString:String;
public function JSONTokenizer(s:String){
super();
jsonString = s;
loc = 0;
nextChar();
}
private function skipComments():void{
if (ch == "/"){
nextChar();
switch (ch){
case "/":
do {
nextChar();
} while (((!((ch == "\n"))) && (!((ch == "")))));
nextChar();
break;
case "*":
nextChar();
while (true) {
if (ch == "*"){
nextChar();
if (ch == "/"){
nextChar();
break;
};
} else {
nextChar();
};
if (ch == ""){
parseError("Multi-line comment not closed");
};
};
break;
default:
parseError((("Unexpected " + ch) + " encountered (expecting '/' or '*' )"));
};
};
}
private function isDigit(ch:String):Boolean{
return ((((ch >= "0")) && ((ch <= "9"))));
}
private function readString():JSONToken{
var _local5:String;
var i:int;
var token:JSONToken = new JSONToken();
token.type = JSONTokenType.STRING;
var string:String = "";
nextChar();
while (((!((ch == "\""))) && (!((ch == ""))))) {
if (ch == "\\"){
nextChar();
switch (ch){
case "\"":
string = (string + "\"");
break;
case "/":
string = (string + "/");
break;
case "\\":
string = (string + "\\");
break;
case "b":
string = (string + "\b");
break;
case "f":
string = (string + "\f");
break;
case "n":
string = (string + "\n");
break;
case "r":
string = (string + "\r");
break;
case "t":
string = (string + "\t");
break;
case "u":
_local5 = "";
i = 0;
while (i < 4) {
if (!isHexDigit(nextChar())){
parseError((" Excepted a hex digit, but found: " + ch));
};
_local5 = (_local5 + ch);
i++;
};
string = (string + String.fromCharCode(parseInt(_local5, 16)));
break;
default:
string = (string + ("\\" + ch));
};
} else {
string = (string + ch);
};
nextChar();
};
if (ch == ""){
parseError("Unterminated string literal");
};
nextChar();
token.value = string;
return (token);
}
private function nextChar():String{
return ((ch = jsonString.charAt(loc++)));
}
public function getNextToken():JSONToken{
var _local2:String;
var _local3:String;
var _local4:String;
var token:JSONToken = new JSONToken();
skipIgnored();
switch (ch){
case "{":
token.type = JSONTokenType.LEFT_BRACE;
token.value = "{";
nextChar();
break;
case "}":
token.type = JSONTokenType.RIGHT_BRACE;
token.value = "}";
nextChar();
break;
case "[":
token.type = JSONTokenType.LEFT_BRACKET;
token.value = "[";
nextChar();
break;
case "]":
token.type = JSONTokenType.RIGHT_BRACKET;
token.value = "]";
nextChar();
break;
case ",":
token.type = JSONTokenType.COMMA;
token.value = ",";
nextChar();
break;
case ":":
token.type = JSONTokenType.COLON;
token.value = ":";
nextChar();
break;
case "t":
_local2 = ((("t" + nextChar()) + nextChar()) + nextChar());
if (_local2 == "true"){
token.type = JSONTokenType.TRUE;
token.value = true;
nextChar();
} else {
parseError(("Expecting 'true' but found " + _local2));
};
break;
case "f":
_local3 = (((("f" + nextChar()) + nextChar()) + nextChar()) + nextChar());
if (_local3 == "false"){
token.type = JSONTokenType.FALSE;
token.value = false;
nextChar();
} else {
parseError(("Expecting 'false' but found " + _local3));
};
break;
case "n":
_local4 = ((("n" + nextChar()) + nextChar()) + nextChar());
if (_local4 == "null"){
token.type = JSONTokenType.NULL;
token.value = null;
nextChar();
} else {
parseError(("Expecting 'null' but found " + _local4));
};
break;
case "\"":
token = readString();
break;
default:
if (((isDigit(ch)) || ((ch == "-")))){
token = readNumber();
} else {
if (ch == ""){
return (null);
};
parseError((("Unexpected " + ch) + " encountered"));
};
};
return (token);
}
private function skipWhite():void{
while (isWhiteSpace(ch)) {
nextChar();
};
}
public function parseError(message:String):void{
throw (new JSONParseError(message, loc, jsonString));
}
private function isWhiteSpace(ch:String):Boolean{
return ((((((ch == " ")) || ((ch == "\t")))) || ((ch == "\n"))));
}
private function skipIgnored():void{
skipWhite();
skipComments();
skipWhite();
}
private function isHexDigit(ch:String):Boolean{
var uc:String = ch.toUpperCase();
return (((isDigit(ch)) || ((((uc >= "A")) && ((uc <= "F"))))));
}
private function readNumber():JSONToken{
var token:JSONToken = new JSONToken();
token.type = JSONTokenType.NUMBER;
var input:String = "";
if (ch == "-"){
input = (input + "-");
nextChar();
};
if (!isDigit(ch)){
parseError("Expecting a digit");
};
if (ch == "0"){
input = (input + ch);
nextChar();
if (isDigit(ch)){
parseError("A digit cannot immediately follow 0");
};
} else {
while (isDigit(ch)) {
input = (input + ch);
nextChar();
};
};
if (ch == "."){
input = (input + ".");
nextChar();
if (!isDigit(ch)){
parseError("Expecting a digit");
};
while (isDigit(ch)) {
input = (input + ch);
nextChar();
};
};
if ((((ch == "e")) || ((ch == "E")))){
input = (input + "e");
nextChar();
if ((((ch == "+")) || ((ch == "-")))){
input = (input + ch);
nextChar();
};
if (!isDigit(ch)){
parseError("Scientific notation number needs exponent value");
};
while (isDigit(ch)) {
input = (input + ch);
nextChar();
};
};
var num:Number = Number(input);
if (((isFinite(num)) && (!(isNaN(num))))){
token.value = num;
return (token);
};
parseError((("Number " + num) + " is not valid!"));
return (null);
}
}
}//package com.adobe.serialization.json
Section 8
//JSONTokenType (com.adobe.serialization.json.JSONTokenType)
package com.adobe.serialization.json {
public class JSONTokenType {
public static const NUMBER:int = 11;
public static const FALSE:int = 8;
public static const RIGHT_BRACKET:int = 4;
public static const NULL:int = 9;
public static const TRUE:int = 7;
public static const RIGHT_BRACE:int = 2;
public static const UNKNOWN:int = -1;
public static const COMMA:int = 0;
public static const LEFT_BRACKET:int = 3;
public static const STRING:int = 10;
public static const LEFT_BRACE:int = 1;
public static const COLON:int = 6;
public function JSONTokenType(){
super();
}
}
}//package com.adobe.serialization.json
Section 9
//IntUtil (com.adobe.utils.IntUtil)
package com.adobe.utils {
public class IntUtil {
private static var hexChars:String = "0123456789abcdef";
public function IntUtil(){
super();
}
public static function toHex(n:int, bigEndian:Boolean=false):String{
var i:int;
var x:int;
var s:String = "";
if (bigEndian){
i = 0;
while (i < 4) {
s = (s + (hexChars.charAt(((n >> (((3 - i) * 8) + 4)) & 15)) + hexChars.charAt(((n >> ((3 - i) * 8)) & 15))));
i++;
};
} else {
x = 0;
while (x < 4) {
s = (s + (hexChars.charAt(((n >> ((x * 8) + 4)) & 15)) + hexChars.charAt(((n >> (x * 8)) & 15))));
x++;
};
};
return (s);
}
public static function ror(x:int, n:int):uint{
var nn:int = (32 - n);
return (((x << nn) | (x >>> (32 - nn))));
}
public static function rol(x:int, n:int):int{
return (((x << n) | (x >>> (32 - n))));
}
}
}//package com.adobe.utils
Section 10
//IHash (com.hurlant.crypto.hash.IHash)
package com.hurlant.crypto.hash {
import flash.utils.*;
public interface IHash {
function toString():String;
function getHashSize():uint;
function getInputSize():uint;
function hash(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;com/hurlant/crypto/hash;IHash.as:ByteArray):ByteArray;
}
}//package com.hurlant.crypto.hash
Section 11
//SHA1 (com.hurlant.crypto.hash.SHA1)
package com.hurlant.crypto.hash {
public class SHA1 extends SHABase implements IHash {
public static const HASH_SIZE:int = 20;
public function SHA1(){
super();
}
override public function toString():String{
return ("sha1");
}
override protected function core(x:Array, len:uint):Array{
var olda:uint;
var oldb:uint;
var oldc:uint;
var oldd:uint;
var olde:uint;
var j:uint;
var t:uint;
x[(len >> 5)] = (x[(len >> 5)] | (128 << (24 - (len % 32))));
x[((((len + 64) >> 9) << 4) + 15)] = len;
var w:Array = [];
var a:uint = 1732584193;
var b:uint = 4023233417;
var c:uint = 2562383102;
var d:uint = 271733878;
var e:uint = 3285377520;
var i:uint;
while (i < x.length) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
olde = e;
j = 0;
while (j < 80) {
if (j < 16){
w[j] = ((x[(i + j)]) || (0));
} else {
w[j] = rol((((w[(j - 3)] ^ w[(j - 8)]) ^ w[(j - 14)]) ^ w[(j - 16)]), 1);
};
t = ((((rol(a, 5) + ft(j, b, c, d)) + e) + w[j]) + kt(j));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
j++;
};
a = (a + olda);
b = (b + oldb);
c = (c + oldc);
d = (d + oldd);
e = (e + olde);
i = (i + 16);
};
return ([a, b, c, d, e]);
}
private function kt(t:uint):uint{
return (((t)<20) ? 1518500249 : ((t)<40) ? 1859775393 : ((t)<60) ? 2400959708 : 3395469782);
}
override public function getHashSize():uint{
return (HASH_SIZE);
}
private function ft(t:uint, b:uint, c:uint, d:uint):uint{
if (t < 20){
return (((b & c) | (~(b) & d)));
};
if (t < 40){
return (((b ^ c) ^ d));
};
if (t < 60){
return ((((b & c) | (b & d)) | (c & d)));
};
return (((b ^ c) ^ d));
}
private function rol(num:uint, cnt:uint):uint{
return (((num << cnt) | (num >>> (32 - cnt))));
}
}
}//package com.hurlant.crypto.hash
Section 12
//SHABase (com.hurlant.crypto.hash.SHABase)
package com.hurlant.crypto.hash {
import flash.utils.*;
public class SHABase implements IHash {
public function SHABase(){
super();
}
public function toString():String{
return ("sha");
}
public function getInputSize():uint{
return (64);
}
public function getHashSize():uint{
return (0);
}
public function hash(src:ByteArray):ByteArray{
var savedLength:uint = src.length;
var savedEndian:String = src.endian;
src.endian = Endian.BIG_ENDIAN;
var len:uint = (savedLength * 8);
while ((src.length % 4) != 0) {
src[src.length] = 0;
};
src.position = 0;
var a:Array = [];
var i:uint;
while (i < src.length) {
a.push(src.readUnsignedInt());
i = (i + 4);
};
var h:Array = core(a, len);
var out:ByteArray = new ByteArray();
var words:uint = (getHashSize() / 4);
i = 0;
while (i < words) {
out.writeUnsignedInt(h[i]);
i++;
};
src.length = savedLength;
src.endian = savedEndian;
return (out);
}
protected function core(x:Array, len:uint):Array{
return (null);
}
}
}//package com.hurlant.crypto.hash
Section 13
//ARC4 (com.hurlant.crypto.prng.ARC4)
package com.hurlant.crypto.prng {
import flash.utils.*;
import com.hurlant.util.*;
import com.hurlant.crypto.symmetric.*;
public class ARC4 implements IPRNG, IStreamCipher {
private const psize:uint = 0x0100;
private var S:ByteArray;
private var i:int;// = 0
private var j:int;// = 0
public function ARC4(key:ByteArray=null){
super();
S = new ByteArray();
if (key){
init(key);
};
}
public function decrypt(block:ByteArray):void{
encrypt(block);
}
public function init(key:ByteArray):void{
var i:int;
var j:int;
var t:int;
i = 0;
while (i < 0x0100) {
S[i] = i;
i++;
};
j = 0;
i = 0;
while (i < 0x0100) {
j = (((j + S[i]) + key[(i % key.length)]) & 0xFF);
t = S[i];
S[i] = S[j];
S[j] = t;
i++;
};
this.i = 0;
this.j = 0;
}
public function next():uint{
var t:int;
i = ((i + 1) & 0xFF);
j = ((j + S[i]) & 0xFF);
t = S[i];
S[i] = S[j];
S[j] = t;
return (S[((t + S[i]) & 0xFF)]);
}
public function encrypt(block:ByteArray):void{
var i:uint;
while (i < block.length) {
var _temp1 = i;
i = (i + 1);
var _local3 = _temp1;
block[_local3] = (block[_local3] ^ next());
};
}
public function dispose():void{
var i:uint;
if (S != null){
i = 0;
while (i < S.length) {
S[i] = (Math.random() * 0x0100);
i++;
};
S.length = 0;
S = null;
};
this.i = 0;
this.j = 0;
Memory.gc();
}
public function getBlockSize():uint{
return (1);
}
public function getPoolSize():uint{
return (psize);
}
public function toString():String{
return ("rc4");
}
}
}//package com.hurlant.crypto.prng
Section 14
//IPRNG (com.hurlant.crypto.prng.IPRNG)
package com.hurlant.crypto.prng {
import flash.utils.*;
public interface IPRNG {
function init(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;com/hurlant/crypto/prng;IPRNG.as:ByteArray):void;
function next():uint;
function getPoolSize():uint;
function toString():String;
function dispose():void;
}
}//package com.hurlant.crypto.prng
Section 15
//Random (com.hurlant.crypto.prng.Random)
package com.hurlant.crypto.prng {
import flash.utils.*;
import flash.system.*;
import flash.text.*;
import com.hurlant.util.*;
public class Random {
private var ready:Boolean;// = false
private var pool:ByteArray;
private var seeded:Boolean;// = false
private var psize:int;
private var state:IPRNG;
private var pptr:int;
public function Random(prng:Class=null){
var t:uint;
super();
if (prng == null){
prng = ARC4;
};
state = (new (prng) as IPRNG);
psize = state.getPoolSize();
pool = new ByteArray();
pptr = 0;
while (pptr < psize) {
t = (65536 * Math.random());
var _local3 = pptr++;
pool[_local3] = (t >>> 8);
var _local4 = pptr++;
pool[_local4] = (t & 0xFF);
};
pptr = 0;
seed();
}
public function autoSeed():void{
var f:Font;
var b:ByteArray = new ByteArray();
b.writeUnsignedInt(System.totalMemory);
b.writeUTF(Capabilities.serverString);
b.writeUnsignedInt(getTimer());
b.writeUnsignedInt(new Date().getTime());
var a:Array = Font.enumerateFonts(true);
for each (f in a) {
b.writeUTF(f.fontName);
b.writeUTF(f.fontStyle);
b.writeUTF(f.fontType);
};
b.position = 0;
while (b.bytesAvailable >= 4) {
seed(b.readUnsignedInt());
};
}
public function seed(x:int=0):void{
if (x == 0){
x = new Date().getTime();
};
var _local2 = pptr++;
pool[_local2] = (pool[_local2] ^ (x & 0xFF));
var _local3 = pptr++;
pool[_local3] = (pool[_local3] ^ ((x >> 8) & 0xFF));
var _local4 = pptr++;
pool[_local4] = (pool[_local4] ^ ((x >> 16) & 0xFF));
var _local5 = pptr++;
pool[_local5] = (pool[_local5] ^ ((x >> 24) & 0xFF));
pptr = (pptr % psize);
seeded = true;
}
public function toString():String{
return (("random-" + state.toString()));
}
public function dispose():void{
var i:uint;
while (i < pool.length) {
pool[i] = (Math.random() * 0x0100);
i++;
};
pool.length = 0;
pool = null;
state.dispose();
state = null;
psize = 0;
pptr = 0;
Memory.gc();
}
public function nextBytes(buffer:ByteArray, length:int):void{
while (length--) {
buffer.writeByte(nextByte());
};
}
public function nextByte():int{
if (!ready){
if (!seeded){
autoSeed();
};
state.init(pool);
pool.length = 0;
pptr = 0;
ready = true;
};
return (state.next());
}
}
}//package com.hurlant.crypto.prng
Section 16
//RSAKey (com.hurlant.crypto.rsa.RSAKey)
package com.hurlant.crypto.rsa {
import flash.utils.*;
import com.hurlant.math.*;
import com.hurlant.crypto.prng.*;
import com.hurlant.util.*;
public class RSAKey {
public var dmp1:BigInteger;
protected var canDecrypt:Boolean;
public var d:BigInteger;
public var e:int;
public var dmq1:BigInteger;
public var n:BigInteger;
public var p:BigInteger;
public var q:BigInteger;
protected var canEncrypt:Boolean;
public var coeff:BigInteger;
public function RSAKey(N:BigInteger, E:int, D:BigInteger=null, P:BigInteger=null, Q:BigInteger=null, DP:BigInteger=null, DQ:BigInteger=null, C:BigInteger=null){
super();
this.n = N;
this.e = E;
this.d = D;
this.p = P;
this.q = Q;
this.dmp1 = DP;
this.dmq1 = DQ;
this.coeff = C;
canEncrypt = ((!((n == null))) && (!((e == 0))));
canDecrypt = ((canEncrypt) && (!((d == null))));
}
public function verify(src:ByteArray, dst:ByteArray, length:uint, pad:Function=null):void{
_decrypt(doPublic, src, dst, length, pad, 1);
}
protected function doPrivate2(x:BigInteger):BigInteger{
if ((((p == null)) && ((q == null)))){
return (x.modPow(d, n));
};
var xp:BigInteger = x.mod(p).modPow(dmp1, p);
var xq:BigInteger = x.mod(q).modPow(dmq1, q);
while (xp.compareTo(xq) < 0) {
xp = xp.add(p);
};
var r:BigInteger = xp.subtract(xq).multiply(coeff).mod(p).multiply(q).add(xq);
return (r);
}
public function dump():String{
var s = ((((("N=" + n.toString(16)) + "\n") + "E=") + e.toString(16)) + "\n");
if (canDecrypt){
s = (s + (("D=" + d.toString(16)) + "\n"));
if (((!((p == null))) && (!((q == null))))){
s = (s + (("P=" + p.toString(16)) + "\n"));
s = (s + (("Q=" + q.toString(16)) + "\n"));
s = (s + (("DMP1=" + dmp1.toString(16)) + "\n"));
s = (s + (("DMQ1=" + dmq1.toString(16)) + "\n"));
s = (s + (("IQMP=" + coeff.toString(16)) + "\n"));
};
};
return (s);
}
public function decrypt(src:ByteArray, dst:ByteArray, length:uint, pad:Function=null):void{
_decrypt(doPrivate2, src, dst, length, pad, 2);
}
private function _decrypt(op:Function, src:ByteArray, dst:ByteArray, length:uint, pad:Function, padType:int):void{
var block:BigInteger;
var chunk:BigInteger;
var b:ByteArray;
if (pad == null){
pad = pkcs1unpad;
};
if (src.position >= src.length){
src.position = 0;
};
var bl:uint = getBlockSize();
var end:int = (src.position + length);
while (src.position < end) {
block = new BigInteger(src, length);
chunk = op(block);
b = pad(chunk, bl);
dst.writeBytes(b);
};
}
protected function doPublic(x:BigInteger):BigInteger{
return (x.modPowInt(e, n));
}
public function dispose():void{
e = 0;
n.dispose();
n = null;
Memory.gc();
}
private function _encrypt(op:Function, src:ByteArray, dst:ByteArray, length:uint, pad:Function, padType:int):void{
var block:BigInteger;
var chunk:BigInteger;
if (pad == null){
pad = pkcs1pad;
};
if (src.position >= src.length){
src.position = 0;
};
var bl:uint = getBlockSize();
var end:int = (src.position + length);
while (src.position < end) {
block = new BigInteger(pad(src, end, bl, padType), bl);
chunk = op(block);
chunk.toArray(dst);
};
}
private function rawpad(src:ByteArray, end:int, n:uint):ByteArray{
return (src);
}
public function encrypt(src:ByteArray, dst:ByteArray, length:uint, pad:Function=null):void{
_encrypt(doPublic, src, dst, length, pad, 2);
}
private function pkcs1pad(src:ByteArray, end:int, n:uint, type:uint=2):ByteArray{
var x:int;
var out:ByteArray = new ByteArray();
var p:uint = src.position;
end = Math.min(end, src.length, ((p + n) - 11));
src.position = end;
var i:int = (end - 1);
while ((((i >= p)) && ((n > 11)))) {
--n;
var _local10 = n;
var _temp1 = i;
i = (i - 1);
out[_local10] = src[_temp1];
};
--n;
_local10 = n;
out[_local10] = 0;
var rng:Random = new Random();
while (n > 2) {
x = 0;
while (x == 0) {
x = ((type)==2) ? rng.nextByte() : 0xFF;
};
--n;
var _local11 = n;
out[_local11] = x;
};
--n;
_local11 = n;
out[_local11] = type;
--n;
var _local12 = n;
out[_local12] = 0;
return (out);
}
private function pkcs1unpad(src:BigInteger, n:uint, type:uint=2):ByteArray{
var b:ByteArray = src.toByteArray();
var out:ByteArray = new ByteArray();
var i:int;
while ((((i < b.length)) && ((b[i] == 0)))) {
i++;
};
if (((!(((b.length - i) == (n - 1)))) || ((b[i] > 2)))){
trace(((("PKCS#1 unpad: i=" + i) + ", expected b[i]==[0,1,2], got b[i]=") + b[i].toString(16)));
return (null);
};
i++;
while (b[i] != 0) {
++i;
if (i >= b.length){
trace((((("PKCS#1 unpad: i=" + i) + ", b[i-1]!=0 (=") + b[(i - 1)].toString(16)) + ")"));
return (null);
};
};
while (++i < b.length) {
out.writeByte(b[i]);
};
out.position = 0;
return (out);
}
public function getBlockSize():uint{
return (((n.bitLength() + 7) / 8));
}
public function toString():String{
return ("rsa");
}
public function sign(src:ByteArray, dst:ByteArray, length:uint, pad:Function=null):void{
_encrypt(doPrivate2, src, dst, length, pad, 1);
}
protected function doPrivate(x:BigInteger):BigInteger{
if ((((p == null)) || ((q == null)))){
return (x.modPow(d, n));
};
var xp:BigInteger = x.mod(p).modPow(dmp1, p);
var xq:BigInteger = x.mod(q).modPow(dmq1, q);
while (xp.compareTo(xq) < 0) {
xp = xp.add(p);
};
return (xp.subtract(xq).multiply(coeff).mod(p).multiply(q).add(xq));
}
protected static function bigRandom(bits:int, rnd:Random):BigInteger{
if (bits < 2){
return (BigInteger.nbv(1));
};
var x:ByteArray = new ByteArray();
rnd.nextBytes(x, (bits >> 3));
x.position = 0;
var b:BigInteger = new BigInteger(x);
b.primify(bits, 1);
return (b);
}
public static function parsePublicKey(N:String, E:String):RSAKey{
return (new RSAKey(new BigInteger(N, 16), parseInt(E, 16)));
}
public static function generate(B:uint, E:String):RSAKey{
var p1:BigInteger;
var q1:BigInteger;
var phi:BigInteger;
var t:BigInteger;
var rng:Random = new Random();
var qs:uint = (B >> 1);
var key:RSAKey = new RSAKey(null, 0, null);
key.e = parseInt(E, 16);
var ee:BigInteger = new BigInteger(E, 16);
while (true) {
while (true) {
key.p = bigRandom((B - qs), rng);
if ((((key.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0)) && (key.p.isProbablePrime(10)))){
break;
};
};
while (true) {
key.q = bigRandom(qs, rng);
if ((((key.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0)) && (key.q.isProbablePrime(10)))){
break;
};
};
if (key.p.compareTo(key.q) <= 0){
t = key.p;
key.p = key.q;
key.q = t;
};
p1 = key.p.subtract(BigInteger.ONE);
q1 = key.q.subtract(BigInteger.ONE);
phi = p1.multiply(q1);
if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0){
key.n = key.p.multiply(key.q);
key.d = ee.modInverse(phi);
key.dmp1 = key.d.mod(p1);
key.dmq1 = key.d.mod(q1);
key.coeff = key.q.modInverse(key.p);
break;
};
};
return (key);
}
public static function parsePrivateKey(N:String, E:String, D:String, P:String=null, Q:String=null, DMP1:String=null, DMQ1:String=null, IQMP:String=null):RSAKey{
if (P == null){
return (new RSAKey(new BigInteger(N, 16), parseInt(E, 16), new BigInteger(D, 16)));
};
return (new RSAKey(new BigInteger(N, 16), parseInt(E, 16), new BigInteger(D, 16), new BigInteger(P, 16), new BigInteger(Q, 16), new BigInteger(DMP1, 16), new BigInteger(DMQ1), new BigInteger(IQMP)));
}
}
}//package com.hurlant.crypto.rsa
Section 17
//ICipher (com.hurlant.crypto.symmetric.ICipher)
package com.hurlant.crypto.symmetric {
import flash.utils.*;
public interface ICipher {
function encrypt(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;com/hurlant/crypto/symmetric;ICipher.as:ByteArray):void;
function getBlockSize():uint;
function toString():String;
function decrypt(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;com/hurlant/crypto/symmetric;ICipher.as:ByteArray):void;
function dispose():void;
}
}//package com.hurlant.crypto.symmetric
Section 18
//IStreamCipher (com.hurlant.crypto.symmetric.IStreamCipher)
package com.hurlant.crypto.symmetric {
public interface IStreamCipher extends ICipher {
}
}//package com.hurlant.crypto.symmetric
Section 19
//BarrettReduction (com.hurlant.math.BarrettReduction)
package com.hurlant.math {
import com.hurlant.math.*;
class BarrettReduction implements IReduction {
private var r2:BigInteger;
private var q3:BigInteger;
private var mu:BigInteger;
private var m:BigInteger;
function BarrettReduction(m:BigInteger){
super();
r2 = new BigInteger();
q3 = new BigInteger();
BigInteger.ONE.dlShiftTo((2 * m.t), r2);
mu = r2.divide(m);
this.m = m;
}
public function revert(x:BigInteger):BigInteger{
return (x);
}
public function sqrTo(x:BigInteger, r:BigInteger):void{
x.squareTo(r);
reduce(r);
}
public function convert(x:BigInteger):BigInteger{
var r:BigInteger;
if ((((x.s < 0)) || ((x.t > (2 * m.t))))){
return (x.mod(m));
};
if (x.compareTo(m) < 0){
return (x);
};
r = new BigInteger();
x.copyTo(r);
reduce(r);
return (r);
}
public function reduce(lx:BigInteger):void{
var x:BigInteger = (lx as BigInteger);
x.drShiftTo((m.t - 1), r2);
if (x.t > (m.t + 1)){
x.t = (m.t + 1);
x.clamp();
};
mu.multiplyUpperTo(r2, (m.t + 1), q3);
m.multiplyLowerTo(q3, (m.t + 1), r2);
while (x.compareTo(r2) < 0) {
x.dAddOffset(1, (m.t + 1));
};
x.subTo(r2, x);
while (x.compareTo(m) >= 0) {
x.subTo(m, x);
};
}
public function mulTo(x:BigInteger, y:BigInteger, r:BigInteger):void{
x.multiplyTo(y, r);
reduce(r);
}
}
}//package com.hurlant.math
Section 20
//bi_internal (com.hurlant.math.bi_internal)
package com.hurlant.math {
public namespace bi_internal = "http://crypto.hurlant.com/BigInteger";
}//package com.hurlant.math
Section 21
//BigInteger (com.hurlant.math.BigInteger)
package com.hurlant.math {
import flash.utils.*;
import com.hurlant.crypto.prng.*;
import com.hurlant.util.*;
public class BigInteger {
bi_internal var a:Array;
bi_internal var s:int;
public var t:int;
public static const ONE:BigInteger = nbv(1);
public static const ZERO:BigInteger = nbv(0);
public static const DM:int = (DV - 1);
public static const F1:int = 22;
public static const F2:int = 8;
public static const lplim:int = ((1 << 26) / lowprimes[(lowprimes.length - 1)]);
public static const lowprimes:Array = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 0x0101, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509];
public static const FV:Number = Math.pow(2, BI_FP);
public static const BI_FP:int = 52;
public static const DV:int = (1 << DB);
public static const DB:int = 30;
public function BigInteger(value=null, radix:int=0){
var array:ByteArray;
var length:int;
super();
a = new Array();
if ((value is String)){
value = Hex.toArray(value);
radix = 0;
};
if ((value is ByteArray)){
array = (value as ByteArray);
length = ((radix) || ((array.length - array.position)));
fromArray(array, length);
};
}
public function clearBit(n:int):BigInteger{
return (changeBit(n, op_andnot));
}
private function op_or(x:int, y:int):int{
return ((x | y));
}
public function negate():BigInteger{
var r:BigInteger = nbi();
ZERO.subTo(this, r);
return (r);
}
public function andNot(a:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
bitwiseTo(a, op_andnot, r);
return (r);
}
public function modPow(e:BigInteger, m:BigInteger):BigInteger{
var k:int;
var z:IReduction;
var w:int;
var t:BigInteger;
var g2:BigInteger;
var i:int = e.bitLength();
var r:BigInteger = nbv(1);
if (i <= 0){
return (r);
};
if (i < 18){
k = 1;
} else {
if (i < 48){
k = 3;
} else {
if (i < 144){
k = 4;
} else {
if (i < 0x0300){
k = 5;
} else {
k = 6;
};
};
};
};
if (i < 8){
z = new ClassicReduction(m);
} else {
if (m.isEven()){
z = new BarrettReduction(m);
} else {
z = new MontgomeryReduction(m);
};
};
var g:Array = [];
var n = 3;
var k1:int = (k - 1);
var km:int = ((1 << k) - 1);
g[1] = z.convert(this);
if (k > 1){
g2 = new BigInteger();
z.sqrTo(g[1], g2);
while (n <= km) {
g[n] = new BigInteger();
z.mulTo(g2, g[(n - 2)], g[n]);
n = (n + 2);
};
};
var j:int = (e.t - 1);
var is1:Boolean;
var r2:BigInteger = new BigInteger();
i = (nbits(e.a[j]) - 1);
while (j >= 0) {
if (i >= k1){
w = ((e.a[j] >> (i - k1)) & km);
} else {
w = ((e.a[j] & ((1 << (i + 1)) - 1)) << (k1 - i));
if (j > 0){
w = (w | (e.a[(j - 1)] >> ((DB + i) - k1)));
};
};
n = k;
while ((w & 1) == 0) {
w = (w >> 1);
n--;
};
i = (i - n);
if (i < 0){
i = (i + DB);
j--;
};
if (is1){
g[w].copyTo(r);
is1 = false;
} else {
while (n > 1) {
z.sqrTo(r, r2);
z.sqrTo(r2, r);
n = (n - 2);
};
if (n > 0){
z.sqrTo(r, r2);
} else {
t = r;
r = r2;
r2 = t;
};
z.mulTo(r2, g[w], r);
};
while ((((j >= 0)) && (((e.a[j] & (1 << i)) == 0)))) {
z.sqrTo(r, r2);
t = r;
r = r2;
r2 = t;
--i;
if (i < 0){
i = (DB - 1);
j--;
};
};
};
return (z.revert(r));
}
public function isProbablePrime(t:int):Boolean{
var i:int;
var m:int;
var j:int;
var x:BigInteger = abs();
if ((((x.t == 1)) && ((x.a[0] <= lowprimes[(lowprimes.length - 1)])))){
i = 0;
while (i < lowprimes.length) {
if (x[0] == lowprimes[i]){
return (true);
};
i++;
};
return (false);
};
if (x.isEven()){
return (false);
};
i = 1;
while (i < lowprimes.length) {
m = lowprimes[i];
j = (i + 1);
while ((((j < lowprimes.length)) && ((m < lplim)))) {
var _temp1 = j;
j = (j + 1);
m = (m * lowprimes[_temp1]);
};
m = x.modInt(m);
while (i < j) {
var _temp2 = m;
var _temp3 = i;
i = (i + 1);
if ((_temp2 % lowprimes[_temp3]) == 0){
return (false);
};
};
};
return (x.millerRabin(t));
}
public function divide(a:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
divRemTo(a, r, null);
return (r);
}
public function mod(v:BigInteger):BigInteger{
var r:BigInteger = nbi();
abs().divRemTo(v, null, r);
if ((((s < 0)) && ((r.compareTo(ZERO) > 0)))){
v.subTo(r, r);
};
return (r);
}
protected function addTo(a:BigInteger, r:BigInteger):void{
var i:int;
var c:int;
var m:int = Math.min(a.t, t);
while (i < m) {
c = (c + (this.a[i] + a.a[i]));
var _temp1 = i;
i = (i + 1);
var _local6 = _temp1;
r.a[_local6] = (c & DM);
c = (c >> DB);
};
if (a.t < t){
c = (c + a.s);
while (i < t) {
c = (c + this.a[i]);
var _temp2 = i;
i = (i + 1);
_local6 = _temp2;
r.a[_local6] = (c & DM);
c = (c >> DB);
};
c = (c + s);
} else {
c = (c + s);
while (i < a.t) {
c = (c + a.a[i]);
var _temp3 = i;
i = (i + 1);
_local6 = _temp3;
r.a[_local6] = (c & DM);
c = (c >> DB);
};
c = (c + a.s);
};
r.s = ((c)<0) ? -1 : 0;
if (c > 0){
var _temp4 = i;
i = (i + 1);
_local6 = _temp4;
r.a[_local6] = c;
} else {
if (c < -1){
var _temp5 = i;
i = (i + 1);
_local6 = _temp5;
r.a[_local6] = (DV + c);
};
};
r.t = i;
r.clamp();
}
protected function bitwiseTo(a:BigInteger, op:Function, r:BigInteger):void{
var i:int;
var f:int;
var m:int = Math.min(a.t, t);
i = 0;
while (i < m) {
r.a[i] = op(this.a[i], a.a[i]);
i++;
};
if (a.t < t){
f = (a.s & DM);
i = m;
while (i < t) {
r.a[i] = op(this.a[i], f);
i++;
};
r.t = t;
} else {
f = (s & DM);
i = m;
while (i < a.t) {
r.a[i] = op(f, a.a[i]);
i++;
};
r.t = a.t;
};
r.s = op(s, a.s);
r.clamp();
}
protected function modInt(n:int):int{
var i:int;
if (n <= 0){
return (0);
};
var d:int = (DV % n);
var r:int = ((s)<0) ? (n - 1) : 0;
if (t > 0){
if (d == 0){
r = (a[0] % n);
} else {
i = (t - 1);
while (i >= 0) {
r = (((d * r) + a[i]) % n);
i--;
};
};
};
return (r);
}
protected function chunkSize(r:Number):int{
return (Math.floor(((Math.LN2 * DB) / Math.log(r))));
}
public function gcd(a:BigInteger):BigInteger{
var t:BigInteger;
var x:BigInteger = ((s)<0) ? negate() : clone();
var y:BigInteger = ((a.s)<0) ? a.negate() : a.clone();
if (x.compareTo(y) < 0){
t = x;
x = y;
y = t;
};
var i:int = x.getLowestSetBit();
var g:int = y.getLowestSetBit();
if (g < 0){
return (x);
};
if (i < g){
g = i;
};
if (g > 0){
x.rShiftTo(g, x);
y.rShiftTo(g, y);
};
while (x.sigNum() > 0) {
i = x.getLowestSetBit();
if (i > 0){
x.rShiftTo(i, x);
};
i = y.getLowestSetBit();
if (i > 0){
y.rShiftTo(i, y);
};
if (x.compareTo(y) >= 0){
x.subTo(y, x);
x.rShiftTo(1, x);
} else {
y.subTo(x, y);
y.rShiftTo(1, y);
};
};
if (g > 0){
y.lShiftTo(g, y);
};
return (y);
}
bi_internal function dAddOffset(n:int, w:int):void{
while (t <= w) {
var _local3 = t++;
a[_local3] = 0;
};
a[w] = (a[w] + n);
while (a[w] >= DV) {
a[w] = (a[w] - DV);
++w;
if (w >= t){
_local3 = t++;
a[_local3] = 0;
};
_local3 = a;
var _local4 = w;
var _local5 = (_local3[_local4] + 1);
_local3[_local4] = _local5;
};
}
bi_internal function lShiftTo(n:int, r:BigInteger):void{
var i:int;
var bs:int = (n % DB);
var cbs:int = (DB - bs);
var bm:int = ((1 << cbs) - 1);
var ds:int = (n / DB);
var c = ((s << bs) & DM);
i = (t - 1);
while (i >= 0) {
r.a[((i + ds) + 1)] = ((a[i] >> cbs) | c);
c = ((a[i] & bm) << bs);
i--;
};
i = (ds - 1);
while (i >= 0) {
r.a[i] = 0;
i--;
};
r.a[ds] = c;
r.t = ((t + ds) + 1);
r.s = s;
r.clamp();
}
public function getLowestSetBit():int{
var i:int;
while (i < t) {
if (a[i] != 0){
return (((i * DB) + lbit(a[i])));
};
i++;
};
if (s < 0){
return ((t * DB));
};
return (-1);
}
public function subtract(a:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
subTo(a, r);
return (r);
}
public function primify(bits:int, t:int):void{
if (!testBit((bits - 1))){
bitwiseTo(BigInteger.ONE.shiftLeft((bits - 1)), op_or, this);
};
if (isEven()){
dAddOffset(1, 0);
};
while (!(isProbablePrime(t))) {
dAddOffset(2, 0);
while (bitLength() > bits) {
subTo(BigInteger.ONE.shiftLeft((bits - 1)), this);
};
};
}
bi_internal function multiplyLowerTo(a:BigInteger, n:int, r:BigInteger):void{
var j:int;
var i:int = Math.min((t + a.t), n);
r.s = 0;
r.t = i;
while (i > 0) {
--i;
var _local6 = i;
r.a[_local6] = 0;
};
j = (r.t - t);
while (i < j) {
r.a[(i + t)] = am(0, a.a[i], r, i, 0, t);
i++;
};
j = Math.min(a.t, n);
while (i < j) {
am(0, a.a[i], r, i, 0, (n - i));
i++;
};
r.clamp();
}
public function modPowInt(e:int, m:BigInteger):BigInteger{
var z:IReduction;
if ((((e < 0x0100)) || (m.isEven()))){
z = new ClassicReduction(m);
} else {
z = new MontgomeryReduction(m);
};
return (exp(e, z));
}
bi_internal function intAt(str:String, index:int):int{
return (parseInt(str.charAt(index), 36));
}
public function testBit(n:int):Boolean{
var j:int = Math.floor((n / DB));
if (j >= t){
return (!((s == 0)));
};
return (!(((a[j] & (1 << (n % DB))) == 0)));
}
bi_internal function exp(e:int, z:IReduction):BigInteger{
var t:BigInteger;
if ((((e > 4294967295)) || ((e < 1)))){
return (ONE);
};
var r:BigInteger = nbi();
var r2:BigInteger = nbi();
var g:BigInteger = z.convert(this);
var i:int = (nbits(e) - 1);
g.copyTo(r);
while (--i >= 0) {
z.sqrTo(r, r2);
if ((e & (1 << i)) > 0){
z.mulTo(r2, g, r);
} else {
t = r;
r = r2;
r2 = t;
};
};
return (z.revert(r));
}
public function toArray(array:ByteArray):uint{
var k = 8;
var km:int = ((1 << 8) - 1);
var d:int;
var i:int = t;
var p:int = (DB - ((i * DB) % k));
var m:Boolean;
var c:int;
var _temp1 = i;
i = (i - 1);
if (_temp1 > 0){
if ((((p < DB)) && (((a[i] >> p) > 0)))){
m = true;
array.writeByte(d);
c++;
};
while (i >= 0) {
if (p < k){
d = ((a[i] & ((1 << p) - 1)) << (k - p));
var _temp2 = d;
i = (i - 1);
p = (p + (DB - k));
d = (_temp2 | (a[i] >> p));
} else {
p = (p - k);
d = ((a[i] >> p) & km);
if (p <= 0){
p = (p + DB);
i--;
};
};
if (d > 0){
m = true;
};
if (m){
array.writeByte(d);
c++;
};
};
};
return (c);
}
public function dispose():void{
var r:Random = new Random();
var i:uint;
while (i < a.length) {
a[i] = r.nextByte();
delete a[i];
i++;
};
a = null;
t = 0;
s = 0;
Memory.gc();
}
private function lbit(x:int):int{
if (x == 0){
return (-1);
};
var r:int;
if ((x & 0xFFFF) == 0){
x = (x >> 16);
r = (r + 16);
};
if ((x & 0xFF) == 0){
x = (x >> 8);
r = (r + 8);
};
if ((x & 15) == 0){
x = (x >> 4);
r = (r + 4);
};
if ((x & 3) == 0){
x = (x >> 2);
r = (r + 2);
};
if ((x & 1) == 0){
r++;
};
return (r);
}
bi_internal function divRemTo(m:BigInteger, q:BigInteger=null, r:BigInteger=null):void{
var qd:int;
var m = m;
var q = q;
var r = r;
var pm:BigInteger = m.abs();
if (pm.t <= 0){
return;
};
var pt:BigInteger = abs();
if (pt.t < pm.t){
if (q != null){
q.fromInt(0);
};
if (r != null){
copyTo(r);
};
return;
};
if (r == null){
r = nbi();
};
var y:BigInteger = nbi();
var ts:int = s;
var ms:int = m.s;
var nsh:int = (DB - nbits(pm.a[(pm.t - 1)]));
if (nsh > 0){
pm.lShiftTo(nsh, y);
pt.lShiftTo(nsh, r);
} else {
pm.copyTo(y);
pt.copyTo(r);
};
var ys:int = y.t;
var y0:int = y.a[(ys - 1)];
if (y0 == 0){
return;
};
var yt:Number = ((y0 * (1 << F1)) + ((ys)>1) ? (y.a[(ys - 2)] >> F2) : 0);
var d1:Number = (FV / yt);
var d2:Number = ((1 << F1) / yt);
var e:Number = (1 << F2);
var i:int = r.t;
var j:int = (i - ys);
var t:BigInteger = ((q)==null) ? nbi() : q;
y.dlShiftTo(j, t);
if (r.compareTo(t) >= 0){
var _local5 = r.t++;
r.a[_local5] = 1;
r.subTo(t, r);
};
ONE.dlShiftTo(ys, t);
t.subTo(y, y);
while (y.t < ys) {
y.(y.t++); //not popped
};
while ((j = (j - 1)), (j - 1) >= 0) {
i = (i - 1);
qd = ((r.a[(i - 1)])==y0) ? DM : ((Number(r.a[i]) * d1) + ((Number(r.a[(i - 1)]) + e) * d2));
if ((r.a[i] = (r.a[i] + y.am(0, qd, r, j, 0, ys))) < qd){
y.dlShiftTo(j, t);
r.subTo(t, r);
while ((qd = (qd - 1)), r.a[i] < (qd - 1)) {
r.subTo(t, r);
};
};
};
if (q != null){
r.drShiftTo(ys, q);
if (ts != ms){
ZERO.subTo(q, q);
};
};
r.t = ys;
r.clamp();
if (nsh > 0){
r.rShiftTo(nsh, r);
};
if (ts < 0){
ZERO.subTo(r, r);
};
}
public function remainder(a:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
divRemTo(a, null, r);
return (r);
}
bi_internal function multiplyUpperTo(a:BigInteger, n:int, r:BigInteger):void{
n--;
var i:int = (r.t = ((t + a.t) - n));
r.s = 0;
while (--i >= 0) {
r.a[i] = 0;
};
i = Math.max((n - t), 0);
while (i < a.t) {
r.a[((t + i) - n)] = am((n - i), a.a[i], r, 0, 0, ((t + i) - n));
i++;
};
r.clamp();
r.drShiftTo(1, r);
}
public function divideAndRemainder(a:BigInteger):Array{
var q:BigInteger = new BigInteger();
var r:BigInteger = new BigInteger();
divRemTo(a, q, r);
return ([q, r]);
}
public function valueOf():Number{
var coef:Number = 1;
var value:Number = 0;
var i:uint;
while (i < t) {
value = (value + (a[i] * coef));
coef = (coef * DV);
i++;
};
return (value);
}
public function shiftLeft(n:int):BigInteger{
var r:BigInteger = new BigInteger();
if (n < 0){
rShiftTo(-(n), r);
} else {
lShiftTo(n, r);
};
return (r);
}
public function multiply(a:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
multiplyTo(a, r);
return (r);
}
bi_internal function am(i:int, x:int, w:BigInteger, j:int, c:int, n:int):int{
var l:int;
var h:int;
var m:int;
var xl = (x & 32767);
var xh = (x >> 15);
while (--n >= 0) {
l = (a[i] & 32767);
var _temp1 = i;
i = (i + 1);
h = (a[_temp1] >> 15);
m = ((xh * l) + (h * xl));
l = ((((xl * l) + ((m & 32767) << 15)) + w.a[j]) + (c & 1073741823));
c = ((((l >>> 30) + (m >>> 15)) + (xh * h)) + (c >>> 30));
var _temp2 = j;
j = (j + 1);
var _local12 = _temp2;
w.a[_local12] = (l & 1073741823);
};
return (c);
}
bi_internal function drShiftTo(n:int, r:BigInteger):void{
var i:int;
i = n;
while (i < t) {
r.a[(i - n)] = a[i];
i++;
};
r.t = Math.max((t - n), 0);
r.s = s;
}
public function add(a:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
addTo(a, r);
return (r);
}
protected function nbi(){
return (new BigInteger());
}
protected function millerRabin(t:int):Boolean{
var y:BigInteger;
var j:int;
var n1:BigInteger = subtract(BigInteger.ONE);
var k:int = n1.getLowestSetBit();
if (k <= 0){
return (false);
};
var r:BigInteger = n1.shiftRight(k);
t = ((t + 1) >> 1);
if (t > lowprimes.length){
t = lowprimes.length;
};
var a:BigInteger = new BigInteger();
var i:int;
while (i < t) {
a.fromInt(lowprimes[i]);
y = a.modPow(r, this);
if (((!((y.compareTo(BigInteger.ONE) == 0))) && (!((y.compareTo(n1) == 0))))){
j = 1;
while ((((j++ < k)) && (!((y.compareTo(n1) == 0))))) {
y = y.modPowInt(2, this);
if (y.compareTo(BigInteger.ONE) == 0){
return (false);
};
};
if (y.compareTo(n1) != 0){
return (false);
};
};
i++;
};
return (true);
}
bi_internal function dMultiply(n:int):void{
a[t] = am(0, (n - 1), this, 0, 0, t);
t++;
clamp();
}
private function op_andnot(x:int, y:int):int{
return ((x & ~(y)));
}
bi_internal function clamp():void{
var c = (s & DM);
while ((((t > 0)) && ((a[(t - 1)] == c)))) {
t--;
};
}
bi_internal function invDigit():int{
if (t < 1){
return (0);
};
var x:int = a[0];
if ((x & 1) == 0){
return (0);
};
var y = (x & 3);
y = ((y * (2 - ((x & 15) * y))) & 15);
y = ((y * (2 - ((x & 0xFF) * y))) & 0xFF);
y = ((y * (2 - (((x & 0xFFFF) * y) & 0xFFFF))) & 0xFFFF);
y = ((y * (2 - ((x * y) % DV))) % DV);
return (((y)>0) ? (DV - y) : -(y));
}
protected function changeBit(n:int, op:Function):BigInteger{
var r:BigInteger = BigInteger.ONE.shiftLeft(n);
bitwiseTo(r, op, r);
return (r);
}
public function equals(a:BigInteger):Boolean{
return ((compareTo(a) == 0));
}
public function compareTo(v:BigInteger):int{
var r:int = (s - v.s);
if (r != 0){
return (r);
};
var i:int = t;
r = (i - v.t);
if (r != 0){
return (r);
};
while (--i >= 0) {
r = (a[i] - v.a[i]);
if (r != 0){
return (r);
};
};
return (0);
}
public function shiftRight(n:int):BigInteger{
var r:BigInteger = new BigInteger();
if (n < 0){
lShiftTo(-(n), r);
} else {
rShiftTo(n, r);
};
return (r);
}
bi_internal function multiplyTo(v:BigInteger, r:BigInteger):void{
var x:BigInteger = abs();
var y:BigInteger = v.abs();
var i:int = x.t;
r.t = (i + y.t);
while (--i >= 0) {
r.a[i] = 0;
};
i = 0;
while (i < y.t) {
r.a[(i + x.t)] = x.am(0, y.a[i], r, i, 0, x.t);
i++;
};
r.s = 0;
r.clamp();
if (s != v.s){
ZERO.subTo(r, r);
};
}
public function bitCount():int{
var r:int;
var x = (s & DM);
var i:int;
while (i < t) {
r = (r + cbit((a[i] ^ x)));
i++;
};
return (r);
}
protected function toRadix(b:uint=10):String{
if ((((((sigNum() == 0)) || ((b < 2)))) || ((b > 32)))){
return ("0");
};
var cs:int = chunkSize(b);
var a:Number = Math.pow(b, cs);
var d:BigInteger = nbv(a);
var y:BigInteger = nbi();
var z:BigInteger = nbi();
var r:String = "";
divRemTo(d, y, z);
while (y.sigNum() > 0) {
r = ((a + z.intValue()).toString(b).substr(1) + r);
y.divRemTo(d, y, z);
};
return ((z.intValue().toString(b) + r));
}
private function cbit(x:int):int{
var r:uint;
while (x != 0) {
x = (x & (x - 1));
r++;
};
return (r);
}
bi_internal function rShiftTo(n:int, r:BigInteger):void{
var i:int;
r.s = s;
var ds:int = (n / DB);
if (ds >= t){
r.t = 0;
return;
};
var bs:int = (n % DB);
var cbs:int = (DB - bs);
var bm:int = ((1 << bs) - 1);
r.a[0] = (a[ds] >> bs);
i = (ds + 1);
while (i < t) {
r.a[((i - ds) - 1)] = (r.a[((i - ds) - 1)] | ((a[i] & bm) << cbs));
r.a[(i - ds)] = (a[i] >> bs);
i++;
};
if (bs > 0){
r.a[((t - ds) - 1)] = (r.a[((t - ds) - 1)] | ((s & bm) << cbs));
};
r.t = (t - ds);
r.clamp();
}
public function modInverse(m:BigInteger):BigInteger{
var ac:Boolean = m.isEven();
if (((((isEven()) && (ac))) || ((m.sigNum() == 0)))){
return (BigInteger.ZERO);
};
var u:BigInteger = m.clone();
var v:BigInteger = clone();
var a:BigInteger = nbv(1);
var b:BigInteger = nbv(0);
var c:BigInteger = nbv(0);
var d:BigInteger = nbv(1);
while (u.sigNum() != 0) {
while (u.isEven()) {
u.rShiftTo(1, u);
if (ac){
if (((!(a.isEven())) || (!(b.isEven())))){
a.addTo(this, a);
b.subTo(m, b);
};
a.rShiftTo(1, a);
} else {
if (!b.isEven()){
b.subTo(m, b);
};
};
b.rShiftTo(1, b);
};
while (v.isEven()) {
v.rShiftTo(1, v);
if (ac){
if (((!(c.isEven())) || (!(d.isEven())))){
c.addTo(this, c);
d.subTo(m, d);
};
c.rShiftTo(1, c);
} else {
if (!d.isEven()){
d.subTo(m, d);
};
};
d.rShiftTo(1, d);
};
if (u.compareTo(v) >= 0){
u.subTo(v, u);
if (ac){
a.subTo(c, a);
};
b.subTo(d, b);
} else {
v.subTo(u, v);
if (ac){
c.subTo(a, c);
};
d.subTo(b, d);
};
};
if (v.compareTo(BigInteger.ONE) != 0){
return (BigInteger.ZERO);
};
if (d.compareTo(m) >= 0){
return (d.subtract(m));
};
if (d.sigNum() < 0){
d.addTo(m, d);
} else {
return (d);
};
if (d.sigNum() < 0){
return (d.add(m));
};
return (d);
}
bi_internal function fromArray(value:ByteArray, length:int):void{
var x:int;
var p:int = value.position;
var i:int = (p + length);
var sh:int;
var k = 8;
t = 0;
s = 0;
while (--i >= p) {
x = ((i < value.length)) ? value[i] : 0;
if (sh == 0){
var _local8 = t++;
a[_local8] = x;
} else {
if ((sh + k) > DB){
a[(t - 1)] = (a[(t - 1)] | ((x & ((1 << (DB - sh)) - 1)) << sh));
_local8 = t++;
a[_local8] = (x >> (DB - sh));
} else {
a[(t - 1)] = (a[(t - 1)] | (x << sh));
};
};
sh = (sh + k);
if (sh >= DB){
sh = (sh - DB);
};
};
clamp();
value.position = Math.min((p + length), value.length);
}
bi_internal function copyTo(r:BigInteger):void{
var i:int = (t - 1);
while (i >= 0) {
r.a[i] = a[i];
i--;
};
r.t = t;
r.s = s;
}
public function intValue():int{
if (s < 0){
if (t == 1){
return ((a[0] - DV));
};
if (t == 0){
return (-1);
};
} else {
if (t == 1){
return (a[0]);
};
if (t == 0){
return (0);
};
};
return ((((a[1] & ((1 << (32 - DB)) - 1)) << DB) | a[0]));
}
public function min(a:BigInteger):BigInteger{
return (((compareTo(a))<0) ? this : a);
}
public function bitLength():int{
if (t <= 0){
return (0);
};
return (((DB * (t - 1)) + nbits((a[(t - 1)] ^ (s & DM)))));
}
public function shortValue():int{
return (((t)==0) ? s : ((a[0] << 16) >> 16));
}
public function and(a:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
bitwiseTo(a, op_and, r);
return (r);
}
public function byteValue():int{
return (((t)==0) ? s : ((a[0] << 24) >> 24));
}
public function not():BigInteger{
var r:BigInteger = new BigInteger();
var i:int;
while (i < t) {
r[i] = (DM & ~(a[i]));
i++;
};
r.t = t;
r.s = ~(s);
return (r);
}
bi_internal function subTo(v:BigInteger, r:BigInteger):void{
var i:int;
var c:int;
var m:int = Math.min(v.t, t);
while (i < m) {
c = (c + (a[i] - v.a[i]));
var _temp1 = i;
i = (i + 1);
var _local6 = _temp1;
r.a[_local6] = (c & DM);
c = (c >> DB);
};
if (v.t < t){
c = (c - v.s);
while (i < t) {
c = (c + a[i]);
var _temp2 = i;
i = (i + 1);
_local6 = _temp2;
r.a[_local6] = (c & DM);
c = (c >> DB);
};
c = (c + s);
} else {
c = (c + s);
while (i < v.t) {
c = (c - v.a[i]);
var _temp3 = i;
i = (i + 1);
_local6 = _temp3;
r.a[_local6] = (c & DM);
c = (c >> DB);
};
c = (c - v.s);
};
r.s = ((c)<0) ? -1 : 0;
if (c < -1){
var _temp4 = i;
i = (i + 1);
_local6 = _temp4;
r.a[_local6] = (DV + c);
} else {
if (c > 0){
var _temp5 = i;
i = (i + 1);
_local6 = _temp5;
r.a[_local6] = c;
};
};
r.t = i;
r.clamp();
}
public function clone():BigInteger{
var r:BigInteger = new BigInteger();
this.copyTo(r);
return (r);
}
public function pow(e:int):BigInteger{
return (exp(e, new NullReduction()));
}
public function flipBit(n:int):BigInteger{
return (changeBit(n, op_xor));
}
public function xor(a:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
bitwiseTo(a, op_xor, r);
return (r);
}
public function or(a:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
bitwiseTo(a, op_or, r);
return (r);
}
public function max(a:BigInteger):BigInteger{
return (((compareTo(a))>0) ? this : a);
}
bi_internal function fromInt(value:int):void{
t = 1;
s = ((value)<0) ? -1 : 0;
if (value > 0){
a[0] = value;
} else {
if (value < -1){
a[0] = (value + DV);
} else {
t = 0;
};
};
}
bi_internal function isEven():Boolean{
return ((((t)>0) ? (a[0] & 1) : s == 0));
}
public function toString(radix:Number=16):String{
var k:int;
if (s < 0){
return (("-" + negate().toString(radix)));
};
switch (radix){
case 2:
k = 1;
break;
case 4:
k = 2;
break;
case 8:
k = 3;
break;
case 16:
k = 4;
break;
case 32:
k = 5;
break;
};
var km:int = ((1 << k) - 1);
var d:int;
var m:Boolean;
var r:String = "";
var i:int = t;
var p:int = (DB - ((i * DB) % k));
var _temp1 = i;
i = (i - 1);
if (_temp1 > 0){
if ((((p < DB)) && (((a[i] >> p) > 0)))){
m = true;
r = d.toString(36);
};
while (i >= 0) {
if (p < k){
d = ((a[i] & ((1 << p) - 1)) << (k - p));
var _temp2 = d;
i = (i - 1);
p = (p + (DB - k));
d = (_temp2 | (a[i] >> p));
} else {
p = (p - k);
d = ((a[i] >> p) & km);
if (p <= 0){
p = (p + DB);
i--;
};
};
if (d > 0){
m = true;
};
if (m){
r = (r + d.toString(36));
};
};
};
return ((m) ? r : "0");
}
public function setBit(n:int):BigInteger{
return (changeBit(n, op_or));
}
public function abs():BigInteger{
return (((s)<0) ? negate() : this);
}
bi_internal function nbits(x:int):int{
var t:int;
var r = 1;
t = (x >>> 16);
if (t != 0){
x = t;
r = (r + 16);
};
t = (x >> 8);
if (t != 0){
x = t;
r = (r + 8);
};
t = (x >> 4);
if (t != 0){
x = t;
r = (r + 4);
};
t = (x >> 2);
if (t != 0){
x = t;
r = (r + 2);
};
t = (x >> 1);
if (t != 0){
x = t;
r = (r + 1);
};
return (r);
}
public function sigNum():int{
if (s < 0){
return (-1);
};
if ((((t <= 0)) || ((((t == 1)) && ((a[0] <= 0)))))){
return (0);
};
return (1);
}
public function toByteArray():ByteArray{
var d:int;
var i:int = t;
var r:ByteArray = new ByteArray();
r[0] = s;
var p:int = (DB - ((i * DB) % 8));
var k:int;
var _temp1 = i;
i = (i - 1);
if (_temp1 > 0){
if ((((p < DB)) && (!(((a[i] >> p) == ((s & DM) >> p)))))){
var _temp2 = k;
k = (k + 1);
var _local6 = _temp2;
r[_local6] = (d | (s << (DB - p)));
};
while (i >= 0) {
if (p < 8){
d = ((a[i] & ((1 << p) - 1)) << (8 - p));
var _temp3 = d;
i = (i - 1);
p = (p + (DB - 8));
d = (_temp3 | (a[i] >> p));
} else {
p = (p - 8);
d = ((a[i] >> p) & 0xFF);
if (p <= 0){
p = (p + DB);
i--;
};
};
if ((d & 128) != 0){
d = (d | -256);
};
if ((((k == 0)) && (!(((s & 128) == (d & 128)))))){
k++;
};
if ((((k > 0)) || (!((d == s))))){
var _temp4 = k;
k = (k + 1);
_local6 = _temp4;
r[_local6] = d;
};
};
};
return (r);
}
bi_internal function squareTo(r:BigInteger):void{
var c:int;
var x:BigInteger = abs();
var i:int = (r.t = (2 * x.t));
while (--i >= 0) {
r.a[i] = 0;
};
i = 0;
while (i < (x.t - 1)) {
c = x.am(i, x.a[i], r, (2 * i), 0, 1);
if ((r.a[(i + x.t)] = (r.a[(i + x.t)] + x.am((i + 1), (2 * x.a[i]), r, ((2 * i) + 1), c, ((x.t - i) - 1)))) >= DV){
r.a[(i + x.t)] = (r.a[(i + x.t)] - DV);
r.a[((i + x.t) + 1)] = 1;
};
i++;
};
if (r.t > 0){
r.a[(r.t - 1)] = (r.a[(r.t - 1)] + x.am(i, x.a[i], r, (2 * i), 0, 1));
};
r.s = 0;
r.clamp();
}
private function op_and(x:int, y:int):int{
return ((x & y));
}
protected function fromRadix(s:String, b:int=10):void{
var x:int;
fromInt(0);
var cs:int = chunkSize(b);
var d:Number = Math.pow(b, cs);
var mi:Boolean;
var j:int;
var w:int;
var i:int;
while (i < s.length) {
x = intAt(s, i);
if (x < 0){
if ((((s.charAt(i) == "-")) && ((sigNum() == 0)))){
mi = true;
};
} else {
w = ((b * w) + x);
++j;
if (j >= cs){
dMultiply(d);
dAddOffset(w, 0);
j = 0;
w = 0;
};
};
i++;
};
if (j > 0){
dMultiply(Math.pow(b, j));
dAddOffset(w, 0);
};
if (mi){
BigInteger.ZERO.subTo(this, this);
};
}
bi_internal function dlShiftTo(n:int, r:BigInteger):void{
var i:int;
i = (t - 1);
while (i >= 0) {
r.a[(i + n)] = a[i];
i--;
};
i = (n - 1);
while (i >= 0) {
r.a[i] = 0;
i--;
};
r.t = (t + n);
r.s = s;
}
private function op_xor(x:int, y:int):int{
return ((x ^ y));
}
public static function nbv(value:int):BigInteger{
var bn:BigInteger = new (BigInteger);
bn.fromInt(value);
return (bn);
}
}
}//package com.hurlant.math
Section 22
//ClassicReduction (com.hurlant.math.ClassicReduction)
package com.hurlant.math {
import com.hurlant.math.*;
class ClassicReduction implements IReduction {
private var m:BigInteger;
function ClassicReduction(m:BigInteger){
super();
this.m = m;
}
public function revert(x:BigInteger):BigInteger{
return (x);
}
public function reduce(x:BigInteger):void{
x.divRemTo(m, null, x);
}
public function mulTo(x:BigInteger, y:BigInteger, r:BigInteger):void{
x.multiplyTo(y, r);
reduce(r);
}
public function sqrTo(x:BigInteger, r:BigInteger):void{
x.squareTo(r);
reduce(r);
}
public function convert(x:BigInteger):BigInteger{
if ((((x.s < 0)) || ((x.compareTo(m) >= 0)))){
return (x.mod(m));
};
return (x);
}
}
}//package com.hurlant.math
Section 23
//IReduction (com.hurlant.math.IReduction)
package com.hurlant.math {
import com.hurlant.math.*;
interface IReduction {
function revert(:BigInteger):BigInteger;
function reduce(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;com/hurlant/math;IReduction.as:BigInteger):void;
function convert(:BigInteger):BigInteger;
function mulTo(_arg1:BigInteger, _arg2:BigInteger, _arg3:BigInteger):void;
function sqrTo(_arg1:BigInteger, _arg2:BigInteger):void;
}
}//package com.hurlant.math
Section 24
//MontgomeryReduction (com.hurlant.math.MontgomeryReduction)
package com.hurlant.math {
import com.hurlant.math.*;
class MontgomeryReduction implements IReduction {
private var mp:int;
private var mph:int;
private var mpl:int;
private var mt2:int;
private var m:BigInteger;
private var um:int;
function MontgomeryReduction(m:BigInteger){
super();
this.m = m;
mp = m.invDigit();
mpl = (mp & 32767);
mph = (mp >> 15);
um = ((1 << (BigInteger.DB - 15)) - 1);
mt2 = (2 * m.t);
}
public function convert(x:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
x.abs().dlShiftTo(m.t, r);
r.divRemTo(m, null, r);
if ((((x.s < 0)) && ((r.compareTo(BigInteger.ZERO) > 0)))){
m.subTo(r, r);
};
return (r);
}
public function revert(x:BigInteger):BigInteger{
var r:BigInteger = new BigInteger();
x.copyTo(r);
reduce(r);
return (r);
}
public function sqrTo(x:BigInteger, r:BigInteger):void{
x.squareTo(r);
reduce(r);
}
public function reduce(x:BigInteger):void{
var j:int;
var u0:int;
while (x.t <= mt2) {
var _local5 = x.t++;
x.a[_local5] = 0;
};
var i:int;
while (i < m.t) {
j = (x.a[i] & 32767);
u0 = (((j * mpl) + ((((j * mph) + ((x.a[i] >> 15) * mpl)) & um) << 15)) & BigInteger.DM);
j = (i + m.t);
x.a[j] = (x.a[j] + m.am(0, u0, x, i, 0, m.t));
while (x.a[j] >= BigInteger.DV) {
x.a[j] = (x.a[j] - BigInteger.DV);
_local5 = x.a;
++j;
var _local6 = j;
var _local7 = (_local5[_local6] + 1);
_local5[_local6] = _local7;
};
i++;
};
x.clamp();
x.drShiftTo(m.t, x);
if (x.compareTo(m) >= 0){
x.subTo(m, x);
};
}
public function mulTo(x:BigInteger, y:BigInteger, r:BigInteger):void{
x.multiplyTo(y, r);
reduce(r);
}
}
}//package com.hurlant.math
Section 25
//NullReduction (com.hurlant.math.NullReduction)
package com.hurlant.math {
public class NullReduction implements IReduction {
public function NullReduction(){
super();
}
public function convert(x:BigInteger):BigInteger{
return (x);
}
public function sqrTo(x:BigInteger, r:BigInteger):void{
x.squareTo(r);
}
public function mulTo(x:BigInteger, y:BigInteger, r:BigInteger):void{
x.multiplyTo(y, r);
}
public function revert(x:BigInteger):BigInteger{
return (x);
}
public function reduce(x:BigInteger):void{
}
}
}//package com.hurlant.math
Section 26
//Base64 (com.hurlant.util.Base64)
package com.hurlant.util {
import flash.utils.*;
public class Base64 {
public static const version:String = "1.0.0";
private static const BASE64_CHARS:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
public function Base64(){
super();
throw (new Error("Base64 class is static container only"));
}
public static function encode(data:String):String{
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(data);
return (encodeByteArray(bytes));
}
public static function encodeByteArray(data:ByteArray):String{
var dataBuffer:Array;
var i:uint;
var j:uint;
var k:uint;
var output:String = "";
var outputBuffer:Array = new Array(4);
data.position = 0;
while (data.bytesAvailable > 0) {
dataBuffer = new Array();
i = 0;
while ((((i < 3)) && ((data.bytesAvailable > 0)))) {
dataBuffer[i] = data.readUnsignedByte();
i++;
};
outputBuffer[0] = ((dataBuffer[0] & 252) >> 2);
outputBuffer[1] = (((dataBuffer[0] & 3) << 4) | (dataBuffer[1] >> 4));
outputBuffer[2] = (((dataBuffer[1] & 15) << 2) | (dataBuffer[2] >> 6));
outputBuffer[3] = (dataBuffer[2] & 63);
j = dataBuffer.length;
while (j < 3) {
outputBuffer[(j + 1)] = 64;
j++;
};
k = 0;
while (k < outputBuffer.length) {
output = (output + BASE64_CHARS.charAt(outputBuffer[k]));
k++;
};
};
return (output);
}
public static function decode(data:String):String{
var bytes:ByteArray = decodeToByteArray(data);
return (bytes.readUTFBytes(bytes.length));
}
public static function decodeToByteArray(data:String):ByteArray{
var j:uint;
var k:uint;
var output:ByteArray = new ByteArray();
var dataBuffer:Array = new Array(4);
var outputBuffer:Array = new Array(3);
var i:uint;
while (i < data.length) {
j = 0;
while ((((j < 4)) && (((i + j) < data.length)))) {
dataBuffer[j] = BASE64_CHARS.indexOf(data.charAt((i + j)));
j++;
};
outputBuffer[0] = ((dataBuffer[0] << 2) + ((dataBuffer[1] & 48) >> 4));
outputBuffer[1] = (((dataBuffer[1] & 15) << 4) + ((dataBuffer[2] & 60) >> 2));
outputBuffer[2] = (((dataBuffer[2] & 3) << 6) + dataBuffer[3]);
k = 0;
while (k < outputBuffer.length) {
if (dataBuffer[(k + 1)] == 64){
break;
};
output.writeByte(outputBuffer[k]);
k++;
};
i = (i + 4);
};
output.position = 0;
return (output);
}
}
}//package com.hurlant.util
Section 27
//Hex (com.hurlant.util.Hex)
package com.hurlant.util {
import flash.utils.*;
public class Hex {
public function Hex(){
super();
}
public static function fromString(str:String, colons:Boolean=false):String{
var a:ByteArray = new ByteArray();
a.writeUTFBytes(str);
return (fromArray(a, colons));
}
public static function toString(hex:String):String{
var a:ByteArray = toArray(hex);
return (a.readUTFBytes(a.length));
}
public static function toArray(hex:String):ByteArray{
hex = hex.replace(/\s|:/gm, "");
var a:ByteArray = new ByteArray();
if ((hex.length & (1 == 1))){
hex = ("0" + hex);
};
var i:uint;
while (i < hex.length) {
a[(i / 2)] = parseInt(hex.substr(i, 2), 16);
i = (i + 2);
};
return (a);
}
public static function fromArray(array:ByteArray, colons:Boolean=false):String{
var s:String = "";
var i:uint;
while (i < array.length) {
s = (s + ("0" + array[i].toString(16)).substr(-2, 2));
if (colons){
if (i < (array.length - 1)){
s = (s + ":");
};
};
i++;
};
return (s);
}
}
}//package com.hurlant.util
Section 28
//Memory (com.hurlant.util.Memory)
package com.hurlant.util {
import flash.net.*;
import flash.system.*;
public class Memory {
public function Memory(){
super();
}
public static function gc():void{
new LocalConnection().connect("foo");
new LocalConnection().connect("foo");
//unresolved jump
var _slot1 = e;
}
public static function get used():uint{
return (System.totalMemory);
}
}
}//package com.hurlant.util
Section 29
//JabberChatRoom (com.kongregate.as3.chat.JabberChatRoom)
package com.kongregate.as3.chat {
import com.kongregate.as3.common.events.*;
import org.jivesoftware.xiff.core.*;
import org.jivesoftware.xiff.events.*;
import com.kongregate.as3.common.util.*;
import org.jivesoftware.xiff.conference.*;
import com.adobe.serialization.json.*;
public class JabberChatRoom {
private var mType:String;
private var mName:String;
private var mHistoryNum:int;
private var mRoom:Room;
private var mOccupants:Object;
private var mHistoryMode:String;
private var mConnection:JabberConnection;// = null
private var mXmppName:String;
public static const TYPE_CHAT:String = "chat";
public static const TYPE_GAME:String = "game";
public function JabberChatRoom(connection:JabberConnection, roomType:String, xmppName:String, naturalLanguageName:String, historyNum:int=60, historyMode:String="seconds"){
mOccupants = {};
super();
mConnection = connection;
mType = roomType;
mHistoryNum = historyNum;
mHistoryMode = historyMode;
mXmppName = xmppName;
mName = naturalLanguageName;
createRoomObject();
}
private function dispatchEvent(type:String, data:Object=null):void{
var event:JabberEvent = new JabberEvent(type, data);
mConnection.dispatchEvent(event);
}
public function get type():String{
return (mType);
}
private function onUserChanged(e:RoomEvent):void{
var valid:Boolean;
var data:Object;
if (Log.isDebug()){
Log.spam((("User " + e.nickname) + " status changed"));
};
var user:User = new User(e.nickname, null, null);
var status:String = e.data.status;
var occupant:Object = getValidOccupant(e.nickname);
if (occupant){
valid = true;
if (((!((status == null))) && ((status.length > 0)))){
user.parseCompressedVariables(status);
valid = user.validateUserVariables(true);
} else {
user.variables = occupant.variables;
};
if (valid){
user.variables.role = e.data.role;
user.variables.presence = e.data.show;
occupant.variables = user.variables;
data = {room:toObject(), user:user};
dispatchEvent(JabberEvent.USER_CHANGED, data);
} else {
Log.error(("Unable to validate update user variables for " + e.nickname));
};
} else {
Log.error(("User changed event for invalid occupant: " + e.nickname));
};
}
public function get name():String{
return (mName);
}
private function onUserDeparture(e:RoomEvent):void{
var user:User;
var data:Object;
if (Log.isDebug()){
Log.spam(((("User " + e.nickname) + " left ") + toString()));
};
var occupant:Object = getValidOccupant(e.nickname);
if (occupant){
delete mOccupants[e.nickname];
user = new User(e.nickname, null, null);
data = {room:toObject(), user:user};
dispatchEvent(JabberEvent.USER_DEPARTURE, data);
} else {
Log.error("Invalid user leaving room, ignoring");
};
}
private function onLeaveRoom(e:RoomEvent):void{
Log.info(("Left room " + toString()));
dispatchEvent(JabberEvent.LEAVE_ROOM, {room:toObject()});
}
function get room():Room{
return (mRoom);
}
private function createRoomObject():void{
destroy();
mRoom = new Room(mConnection.connection);
mRoom.addEventListener(RoomEvent.ROOM_JOIN, onJoinRoom);
mRoom.addEventListener(RoomEvent.ROOM_LEAVE, onLeaveRoom);
mRoom.addEventListener(RoomEvent.USER_JOIN, onUserJoin);
mRoom.addEventListener(RoomEvent.USER_CHANGED, onUserChanged);
mRoom.addEventListener(RoomEvent.USER_DEPARTURE, onUserDeparture);
mRoom.addEventListener(RoomEvent.GROUP_MESSAGE, onGroupMessage);
mRoom.addEventListener(RoomEvent.SUBJECT_CHANGE, onSubjectChange);
mRoom.nickname = mConnection.user.username;
mRoom.roomJID = new JID(((mXmppName + "@") + mConnection.conferenceServer));
}
public function sendMessage(message:String):void{
if (Log.isDebug()){
Log.debug(("Sending message: " + message));
};
mRoom.sendMessage(message);
}
public function get xmppName():String{
return (mXmppName);
}
public function toObject():Object{
return ({xmpp_name:xmppName, id:xmppName, name:name, type:type});
}
private function onUserJoin(e:RoomEvent):void{
var data:Object;
if (Log.isDebug()){
Log.spam(((("User " + e.nickname) + " joined ") + toString()));
};
var user:User = new User(e.nickname, null, null);
user.parseCompressedVariables(e.data.status);
var valid:Boolean = user.validateUserVariables(true);
if (valid){
user.variables.role = e.data.role;
user.variables.presence = e.data.show;
data = {room:toObject(), user:user};
dispatchEvent(JabberEvent.USER_JOIN, data);
} else {
Log.error(("Unable to validate join user variables for " + e.nickname));
};
mOccupants[e.nickname] = {valid:valid, variables:user.variables};
}
private function onJoinRoom(e:RoomEvent):void{
Log.info(("Joined room " + toString()));
dispatchEvent(JabberEvent.JOIN_ROOM, {room:toObject()});
}
public function toString():String{
return ((((mRoom.roomJID.toString() + " (") + xmppName) + ")"));
}
public function join():void{
createRoomObject();
Log.info(("Joining room " + toString()));
mRoom.join(false, mConnection.user.compressedVariables, mHistoryMode, mHistoryNum);
}
private function getValidOccupant(nickname:String):Object{
var occupant:Object = mOccupants[nickname];
if (((occupant) && (occupant.valid))){
return (occupant);
};
return (null);
}
private function onGroupMessage(e:RoomEvent):void{
var data:Object;
var user:User = new User(e.data.from.resource);
var history:Boolean = e.data.time;
var valid:Boolean = ((!(user.isGuest())) && (((getValidOccupant(user.username)) || (history))));
if (valid){
data = {room:toObject(), user:user, message:e.data.body, history:history};
dispatchEvent(JabberEvent.ROOM_MESSAGE, data);
} else {
if (Log.isDebug()){
Log.spam(("Room message from invalid user ignored: " + user.username));
};
};
}
private function onSubjectChange(e:RoomEvent):void{
var subject:String;
var data:Object;
var numGuests:int;
var e = e;
subject = e.subject;
Log.debug(("Room subject changed: " + subject));
data = JSON.decode(subject);
numGuests = data.g;
if (!isNaN(numGuests)){
data = {room:toObject(), guests:numGuests};
dispatchEvent(JabberEvent.GUEST_COUNT, data);
};
//unresolved jump
var _slot1 = e;
Log.error(("Error during subject change: " + _slot1.toString()));
}
public function leave():void{
Log.info(("Leaving room " + toString()));
mRoom.removeEventListener(RoomEvent.ROOM_JOIN, onJoinRoom);
mRoom.removeEventListener(RoomEvent.USER_JOIN, onUserJoin);
mRoom.removeEventListener(RoomEvent.USER_CHANGED, onUserChanged);
mRoom.removeEventListener(RoomEvent.USER_DEPARTURE, onUserDeparture);
mRoom.removeEventListener(RoomEvent.GROUP_MESSAGE, onGroupMessage);
mRoom.removeEventListener(RoomEvent.SUBJECT_CHANGE, onSubjectChange);
mRoom.leave();
}
public function destroy():void{
if (mRoom != null){
mRoom.removeEventListener(RoomEvent.ROOM_JOIN, onJoinRoom);
mRoom.removeEventListener(RoomEvent.ROOM_LEAVE, onLeaveRoom);
mRoom.removeEventListener(RoomEvent.USER_JOIN, onUserJoin);
mRoom.removeEventListener(RoomEvent.USER_CHANGED, onUserChanged);
mRoom.removeEventListener(RoomEvent.USER_DEPARTURE, onUserDeparture);
mRoom.removeEventListener(RoomEvent.GROUP_MESSAGE, onGroupMessage);
mRoom.removeEventListener(RoomEvent.SUBJECT_CHANGE, onSubjectChange);
mRoom.leave();
};
mOccupants = {};
}
}
}//package com.kongregate.as3.chat
Section 30
//JabberConnection (com.kongregate.as3.chat.JabberConnection)
package com.kongregate.as3.chat {
import com.kongregate.as3.service.*;
import com.kongregate.as3.common.events.*;
import flash.events.*;
import com.kongregate.as3.common.comm.*;
import org.jivesoftware.xiff.core.*;
import org.jivesoftware.xiff.events.*;
import com.kongregate.as3.common.util.*;
import flash.utils.*;
import org.jivesoftware.xiff.data.*;
import flash.system.*;
public class JabberConnection extends BufferedEventDispatcher {
private var mConnecting:Boolean;// = false
private var mPresence:String;
private var mRooms:Object;
private var mLastPacketReceived:int;
private var mIdleMonitorTimer:Timer;
private var mEverConnectedWithSocket:Boolean;// = false
private var mGameApiService:GameAPIService;
private var mSocketConnectionAttemptCount:uint;// = 0
private var mLastError:String;// = ""
private var mConnection:XMPPConnection;
private var mLastPacketSent:int;
private var mCompressionEnabled:Boolean;
private var mUser:User;
private var mLoginFailed:Boolean;// = true
private var mSessionConflict:Boolean;// = false
private var gStaticInit:Boolean;
private var mBanned:Boolean;// = false
private var mConnectionMonitorTimer:Timer;
private var mOptions:Object;
private var mLastPresenceSent:int;
private var mRateLimiter:RateLimiter;
private static const CONNECTION_TIMEOUT:int = 180000;
private static const IDLE_TIMEOUT:int = 900000;
private static const CONNECTION_MONITOR_INTERVAL:int = 60000;
private static const SOCKET_ATTEMPTS_BEFORE_BOSH:int = 2;
private static const IDLE_MONITOR_INTERVAL:int = 31000;
private static var OUTGOING_RATE_LIMITER_RULES:Array = [{duration:1000, capacity:2}, {duration:60000, capacity:20}];
public static var MAX_OUTGOING_MESSAGE_LENGTH:int = 250;
public function JabberConnection(options:Object){
mRooms = {};
mOptions = {};
mLastPacketReceived = getTimer();
mLastPacketSent = getTimer();
gStaticInit = staticInit();
mConnectionMonitorTimer = new Timer(CONNECTION_MONITOR_INTERVAL);
mRateLimiter = new RateLimiter(OUTGOING_RATE_LIMITER_RULES);
mLastPresenceSent = getTimer();
mIdleMonitorTimer = new Timer(IDLE_MONITOR_INTERVAL);
super();
mOptions = options;
initializeSocketConnection();
mConnectionMonitorTimer.addEventListener(TimerEvent.TIMER, onConnectionMonitorTimer);
Log.info(((("JabberConnection initialized, BOSH enabled=" + boshEnabled) + ", compression enabled=") + compressionEnabled));
}
private function get compressionEnabled():Boolean{
return ((((mOptions.enable_compression == true)) || ((mOptions.enable_compression == "true"))));
}
public function sendRoomMessage(roomType:String, message:String):void{
setPresence(Presence.SHOW_CHAT);
message = validateMessage(message);
if (null == message){
return;
};
var room:JabberChatRoom = getRoom(roomType);
if (room != null){
room.sendMessage(message);
} else {
Log.warn(("Message sent to non-existant room type: " + roomType));
};
}
private function get xiffConnectionType():String{
return ((isBosh) ? "terminatedStandard" : "terminatedFlash");
}
public function get loginFailed():Boolean{
return (mLoginFailed);
}
private function initializeConnection():void{
if (((!(boshEnabled)) || ((mSocketConnectionAttemptCount < SOCKET_ATTEMPTS_BEFORE_BOSH)))){
initializeSocketConnection();
mSocketConnectionAttemptCount++;
} else {
mSocketConnectionAttemptCount = 0;
initializeBOSHConnection();
};
}
public function get sessionConflict():Boolean{
return (mSessionConflict);
}
private function validateMessage(message:String):String{
if (user.isGuest()){
return (null);
};
var muteRuleViolated:Object = mRateLimiter.ruleViolated();
if (muteRuleViolated){
dispatchEvent(new JabberEvent(JabberEvent.MESSAGE_ERROR, {errorType:JabberEvent.ERROR_MSG_RATE_LIMIT, ruleViolated:muteRuleViolated}));
return (null);
};
if (message.length > MAX_OUTGOING_MESSAGE_LENGTH){
dispatchEvent(new JabberEvent(JabberEvent.MESSAGE_ERROR, {errorType:JabberEvent.ERROR_MSG_TOO_LONG}));
message = StringTruncate.truncateOn(message, MAX_OUTGOING_MESSAGE_LENGTH, " ", "...");
};
return (BadLanguageFilter.filter(message));
}
public function get lastError():String{
return (mLastError);
}
public function setPresence(presence:String):void{
if (Presence.SHOW_CHAT == presence){
mLastPresenceSent = getTimer();
};
if (mPresence == presence){
return;
};
mPresence = presence;
Log.info(("Changing user presence to " + mPresence));
var msg:Message = Message.fromOpcode(Opcode.OP_SET_PRESENCE);
msg.addParam(Opcode.PARAM_FROM, mConnection.username);
msg.addParam(Opcode.PARAM_PRESENCE, presence);
sendKongregateMessage(msg);
}
public function sendKongregateMessage(msg:Message):void{
var kongIQ:IQ = new IQ(null, IQ.GET_TYPE, XMPPStanza.generateID("sgm_"), null, null);
var kongExt:KongregateIQExtension = new KongregateIQExtension(kongIQ.getNode());
kongExt.opcode = msg.getOpcode();
kongExt.params = msg.getParams();
kongIQ.addExtension(kongExt);
mConnection.send(kongIQ);
}
public function set user(user:User):void{
mUser = user;
mConnection.username = user.username;
mConnection.password = user.password;
}
public function get banned():Boolean{
return (mBanned);
}
public function get conferenceServer():String{
return (("conference." + mConnection.server));
}
private function onIncomingMessage(e:MessageEvent):void{
var fromJID:String;
var fromUsername:String;
var gameId:int;
if (e.data.type != Message.NORMAL_TYPE){
return;
};
var msg:Message = Message.fromBase64(e.data.body);
if (msg != null){
fromJID = e.data.from.node.toLowerCase();
fromUsername = msg.getParam(Opcode.PARAM_FROM).toLowerCase();
gameId = msg.getParam(Opcode.PARAM_GAME_ID);
if (((!((fromUsername == fromJID))) || (!((gameId == mGameApiService.gameId))))){
Log.warn((fromJID + " sent us a peer message that failed validation"));
return;
};
if (msg.getOpcode() != null){
dispatchEvent(new PeerMessageEvent(msg));
};
};
}
public function disconnect():void{
Log.info("Disconnecting from Jabber server");
mConnection.disconnect();
}
private function onConnection(e:ConnectionSuccessEvent):void{
mConnecting = false;
if (isSocket){
mEverConnectedWithSocket = true;
mSocketConnectionAttemptCount = 0;
};
Log.info((((((("Connected to server (" + connectionType) + ")[") + mConnection.serverAddress) + "/") + mConnection.server) + "]"));
var connectionEvent:JabberEvent = new JabberEvent(JabberEvent.CONNECT, {success:true});
dispatchEvent(connectionEvent);
}
public function switchUser(newUser:User):void{
Log.debug((((("Switching user from " + user.username) + " to ") + newUser.username) + "."));
disconnect();
user = newUser;
connect();
}
private function initializeConnectionEventHandlers():void{
mConnection.addEventListener(ConnectionSuccessEvent.CONNECT_SUCCESS, onConnection);
mConnection.addEventListener(XIFFErrorEvent.XIFF_ERROR, onXiffError);
mConnection.addEventListener(DisconnectionEvent.DISCONNECT, onDisconnection);
mConnection.addEventListener(LoginEvent.LOGIN, onLogin);
mConnection.addEventListener(KongregateIQExtension.NS, onKongregateIQ);
mConnection.addEventListener(IncomingDataEvent.INCOMING_DATA, onIncomingData);
mConnection.addEventListener(OutgoingDataEvent.OUTGOING_DATA, onOutgoingData);
mConnection.addEventListener(MessageEvent.MESSAGE, onIncomingMessage);
this.addEventListener(MessageEvent.RECEIVED_KONG_IQ, onServerMessage);
}
private function get boshEnabled():Boolean{
return ((((((mOptions.enable_bosh == true)) || ((mOptions.enable_bosh == "true")))) && (!(mEverConnectedWithSocket))));
}
public function leaveRoom(roomType:String):void{
var room:JabberChatRoom = getRoom(roomType);
if (room != null){
room.leave();
mRooms[roomType] = null;
};
}
public function sendPrivateMessage(username:String, message:String):void{
setPresence(Presence.SHOW_CHAT);
message = validateMessage(message);
if (null == message){
return;
};
var msg:Message = Message.fromOpcode(Opcode.OP_PRIVATE_MESSAGE);
msg.addParam(Opcode.PARAM_FROM, mConnection.username);
msg.addParam(Opcode.PARAM_TO, username);
msg.addParam(Opcode.PARAM_DATA, message);
sendKongregateMessage(msg);
}
private function onOutgoingData(e:OutgoingDataEvent):void{
mLastPacketSent = getTimer();
}
public function joinRoom(roomType:String, roomXmppName:String=null, roomName:String=null):void{
Log.info(((("Join room request[" + roomType) + "] xmppName=") + roomXmppName));
var blankXmppName:Boolean = (((roomXmppName == null)) || ((roomXmppName.length == 0)));
if ((((roomType == JabberChatRoom.TYPE_GAME)) && (blankXmppName))){
Log.info("Game room join request received with no roomID, requesting one from server");
requestJoinGameRoom();
return;
};
if (blankXmppName){
Log.error((("Tried to join room (type: " + roomType) + ") with blank xmpp name"));
return;
};
leaveRoom(roomType);
var historyMode:String = "seconds";
var historyNum = 60;
var room:JabberChatRoom = new JabberChatRoom(this, roomType, roomXmppName, roomName, historyNum, historyMode);
mRooms[roomType] = room;
room.join();
}
public function get connectionType():String{
return ((isBosh) ? "BOSH" : (compressionEnabled) ? "cmp.socket" : "socket");
}
private function removeConnectionEventHandlers():void{
if (mConnection){
mConnection.removeEventListener(ConnectionSuccessEvent.CONNECT_SUCCESS, onConnection);
mConnection.removeEventListener(XIFFErrorEvent.XIFF_ERROR, onXiffError);
mConnection.removeEventListener(DisconnectionEvent.DISCONNECT, onDisconnection);
mConnection.removeEventListener(LoginEvent.LOGIN, onLogin);
mConnection.removeEventListener(IncomingDataEvent.INCOMING_DATA, onIncomingData);
mConnection.removeEventListener(OutgoingDataEvent.OUTGOING_DATA, onOutgoingData);
mConnection.removeEventListener(MessageEvent.MESSAGE, onIncomingMessage);
};
this.removeEventListener(MessageEvent.RECEIVED_KONG_IQ, onServerMessage);
}
private function onKongregateIQ(e:IQEvent):void{
var ext:KongregateIQExtension;
var msg:Message;
var kongIQReceivedEvent:MessageEvent;
var from:String = e.iq.from.node.toLowerCase();
if ((((from == "admin")) || ((from.indexOf("kong_") == 0)))){
ext = (e.data as KongregateIQExtension);
msg = Message.fromOpcode(ext.opcode);
msg.setParams(ext.params);
Log.debug(((("Kongregate Packet[" + from) + "] ") + msg.toString()));
kongIQReceivedEvent = new MessageEvent(MessageEvent.RECEIVED_KONG_IQ, msg);
dispatchEvent(kongIQReceivedEvent);
};
}
public function get isBosh():Boolean{
return ((mConnection is XMPPBOSHConnection));
}
private function onServerMessage(e:MessageEvent):void{
var msg:Message;
var _local5:String;
var _local6:String;
var privateMessage:JabberEvent;
var failedPrivateMessage:JabberEvent;
msg = e.msg;
if (!msg){
return;
};
switch (msg.getOpcode()){
case Opcode.OP_SILENCED:
dispatchEvent(new JabberEvent(JabberEvent.SILENCED, msg.getParams()));
break;
case Opcode.OP_PARTICIPATE:
dispatchEvent(new JabberEvent(JabberEvent.PARTICIPATE, msg.getParams()));
break;
case Opcode.OP_PRIVATE_MESSAGE:
if (msg.getParam(Opcode.PARAM_SUCCESS)){
privateMessage = new JabberEvent(JabberEvent.PRIVATE_MESSAGE, {success:true, from:msg.getParam(Opcode.PARAM_FROM), message:msg.getParam(Opcode.PARAM_DATA)});
dispatchEvent(privateMessage);
} else {
failedPrivateMessage = new JabberEvent(JabberEvent.PRIVATE_MESSAGE, {success:false, to:msg.getParam(Opcode.PARAM_TO), from:msg.getParam(Opcode.PARAM_FROM), message:msg.getParam(Opcode.PARAM_DATA)});
dispatchEvent(failedPrivateMessage);
};
break;
case Opcode.OP_REQUEST_GAME_ROOM:
_local5 = msg.getParam(Opcode.PARAM_ROOM_NAME);
_local6 = msg.getParam(Opcode.PARAM_ROOM_NATURAL_NAME);
Log.info(((("Game room response received: " + _local5) + ", name=") + _local6));
joinRoom(JabberChatRoom.TYPE_GAME, _local5, _local6);
break;
};
}
public function set gameApi(gameApi:GameAPIService):void{
mGameApiService = gameApi;
}
public function get user():User{
return (mUser);
}
public function get isSocket():Boolean{
return (!(isBosh));
}
private function onDisconnection(e:DisconnectionEvent):void{
var roomType:String;
var disconnectionEvent:JabberEvent;
var room:JabberChatRoom;
mConnecting = false;
for (roomType in mRooms) {
room = mRooms[roomType];
room.leave();
};
Log.info("Disconnected from server");
disconnectionEvent = new JabberEvent(JabberEvent.DISCONNECT, {conflict:sessionConflict, login_failed:loginFailed, banned:banned});
dispatchEvent(disconnectionEvent);
}
private function postInitializeConnection():void{
if (user){
mConnection.username = user.username;
mConnection.password = user.password;
};
initializeConnectionEventHandlers();
}
private function onConnectionMonitorTimer(e:TimerEvent):void{
var now:int;
var msg:Message;
var e = e;
if (mConnection.isActive()){
now = getTimer();
if ((now - mLastPacketReceived) >= CONNECTION_TIMEOUT){
Log.info("Time of last packet received is outside threshold, closing connection");
mConnection.disconnect();
} else {
if (((!(isBosh)) && (((now - mLastPacketSent) >= CONNECTION_MONITOR_INTERVAL)))){
if ((now - mLastPacketReceived) >= CONNECTION_MONITOR_INTERVAL){
msg = Message.fromOpcode(Opcode.OP_PING);
msg.addParam(Opcode.PARAM_TIME, now);
sendKongregateMessage(msg);
} else {
mConnection.sendKeepAlive();
};
};
};
} else {
if (shouldReconnect){
Log.info("Auto-reconnecting");
connect();
};
};
//unresolved jump
var _slot1 = e;
Log.info(((("Error in connection monitor (" + _slot1.toString()) + ", shouldReconnect=") + shouldReconnect));
if (shouldReconnect){
Log.info("Auto-reconnecting");
disconnect();
connect();
};
}
function get connection():XMPPConnection{
return (mConnection);
}
public function sendKongregateMessageToPlayer(msg:Message, username:String):void{
var body:String = msg.toBase64();
var toJID:JID = new JID(((username.toLowerCase() + "@") + mConnection.server));
var kongMsg:Message = new Message(toJID, null, body, null, Message.NORMAL_TYPE, null);
mConnection.send(kongMsg);
}
private function initializeSocketConnection():void{
removeConnectionEventHandlers();
mConnection = (compressionEnabled) ? new XMPPSocketConnection(true) : new XMPPConnection();
mConnection.server = mOptions.host;
mConnection.serverAddress = mOptions.ip;
if (mOptions.port){
mConnection.port = mOptions.port;
} else {
mConnection.port = 5222;
};
mConnectionMonitorTimer.addEventListener(TimerEvent.TIMER, onConnectionMonitorTimer);
mIdleMonitorTimer.addEventListener(TimerEvent.TIMER, onIdleMonitorTimer);
var crossDomainAddress:String = ((("xmlsocket://" + mConnection.serverAddress) + ":") + mConnection.port);
Log.info(("Loading cross-domain policy from " + crossDomainAddress));
Security.loadPolicyFile(crossDomainAddress);
postInitializeConnection();
}
public function get shouldReconnect():Boolean{
return (((((((((!(connection.isActive())) && (!(mConnecting)))) && (!(sessionConflict)))) && (!(banned)))) && (!(loginFailed))));
}
private function requestJoinGameRoom():void{
var msg:Message = Message.fromOpcode(Opcode.OP_REQUEST_GAME_ROOM);
msg.addParam(Opcode.PARAM_GAME_ID, mGameApiService.gameId);
msg.addParam(Opcode.PARAM_GAME_NAME, mGameApiService.gameTitle);
msg.addParam(Opcode.PARAM_PERMALINK, mGameApiService.gamePermalink);
sendKongregateMessage(msg);
}
public function getRoom(roomType:String):JabberChatRoom{
return (mRooms[roomType]);
}
public function connect():void{
if (((!(mConnecting)) && (!(mConnection.isActive())))){
initializeConnection();
Log.info((("Initializing connection (" + connectionType) + ")"));
mConnectionMonitorTimer.start();
mIdleMonitorTimer.start();
mConnecting = true;
mSessionConflict = false;
mLoginFailed = false;
mConnection.connect(xiffConnectionType);
dispatchEvent(new JabberEvent(JabberEvent.CONNECTION_ATTEMPT, {}));
};
}
private function onIncomingData(e:IncomingDataEvent):void{
mLastPacketReceived = getTimer();
}
private function initializeBOSHConnection():void{
removeConnectionEventHandlers();
var bosh:XMPPBOSHConnection = new XMPPBOSHConnection();
bosh.server = mOptions.host;
bosh.serverAddress = mOptions.bosh_host;
bosh.port = mOptions.bosh_port;
bosh.secure = false;
bosh.useSasl = false;
mConnection = bosh;
postInitializeConnection();
}
private function onLogin(e:LoginEvent):void{
var roomType:String;
var data:Object;
var loginEvent:JabberEvent;
var room:JabberChatRoom;
Log.info(("Logged in successfully as " + mConnection.username));
mPresence = Presence.SHOW_CHAT;
var rosterPresence:Presence = new Presence(null, null, null, mPresence, null, 5);
mConnection.send(rosterPresence);
for (roomType in mRooms) {
room = mRooms[roomType];
room.join();
};
data = {username:mConnection.username, success:true, bosh:isBosh};
loginEvent = new JabberEvent(JabberEvent.LOGIN, data);
dispatchEvent(loginEvent);
}
private function onXiffError(e:XIFFErrorEvent):void{
var connectionEvent:JabberEvent;
var errorString:String = ((((("XMPP error (" + e.errorCode) + "/") + e.errorType) + "): ") + e.errorCondition);
mLastError = errorString;
Log.warn(errorString);
if (mConnecting){
mConnecting = false;
if (!mConnection.isActive()){
if (((boshEnabled) && (isSocket))){
Log.info((("Socket connection failed (Attempt #" + mSocketConnectionAttemptCount) + ")"));
if (mSocketConnectionAttemptCount >= SOCKET_ATTEMPTS_BEFORE_BOSH){
Log.info("Socket failed too many times, switching to BOSH");
connect();
};
return;
};
Log.error("Error during connection, broadcasting failed connection event");
connectionEvent = new JabberEvent(JabberEvent.CONNECT, {success:false});
dispatchEvent(connectionEvent);
};
} else {
if (!mConnection.isLoggedIn()){
Log.error((("Error during authentication (" + mConnection.username) + "), disconnecting with login_failed"));
mLoginFailed = true;
disconnect();
} else {
if (e.errorMessage == "conflict"){
Log.info("Session conflict detected");
mSessionConflict = true;
} else {
if ((((e.errorCode == 502)) && ((e.errorMessage == "policy-violation")))){
Log.info("Disconnection from ban detected.");
mBanned = true;
};
};
};
};
}
public function destroy():void{
if ((this is BufferedEventDispatcher)){
var _local1 = this;
_local1["shutdown"]();
};
removeEventHandlers();
disconnect();
}
private function onIdleMonitorTimer(e:TimerEvent):void{
if (((!(mConnection.isActive())) || (user.isGuest()))){
return;
};
var idleTime:int = (getTimer() - mLastPresenceSent);
if (idleTime >= IDLE_TIMEOUT){
setPresence(Presence.SHOW_AWAY);
};
}
private function removeEventHandlers():void{
var type:String;
removeConnectionEventHandlers();
if (mConnectionMonitorTimer){
mConnectionMonitorTimer.removeEventListener(TimerEvent.TIMER, onConnectionMonitorTimer);
mConnectionMonitorTimer.stop();
};
if (mIdleMonitorTimer){
mIdleMonitorTimer.removeEventListener(TimerEvent.TIMER, onIdleMonitorTimer);
mIdleMonitorTimer.stop();
};
if (mGameApiService){
gameApi = null;
};
for (type in mRooms) {
if (mRooms[type]){
mRooms[type].destroy();
};
};
}
private static function staticInit():Boolean{
KongregateIQExtension.enable();
return (true);
}
}
}//package com.kongregate.as3.chat
Section 31
//KongregateIQExtension (com.kongregate.as3.chat.KongregateIQExtension)
package com.kongregate.as3.chat {
import com.kongregate.as3.common.util.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
import com.adobe.serialization.json.*;
public class KongregateIQExtension extends Extension implements IExtension, ISerializable {
private var mMessage:XMLNode;
private var mOpcode:String;
private var mParams:Object;
public static var ELEMENT:String = "query";
public static var NS:String = "kongregate:iq:msg";
public function KongregateIQExtension(parent:XMLNode=null){
super(parent);
mParams = null;
mOpcode = null;
mMessage = null;
}
public function serialize(parent:XMLNode):Boolean{
mMessage = replaceTextNode(getNode(), mMessage, "msg", Base64.encode(JSON.encode(mParams)));
mMessage.attributes["opcode"] = mOpcode;
if (!exists(getNode().parentNode)){
parent.appendChild(getNode().cloneNode(true));
};
return (true);
}
public function getNS():String{
return (KongregateIQExtension.NS);
}
public function set params(theParams:Object):void{
mParams = theParams;
}
public function get params():Object{
return (mParams);
}
public function getElementName():String{
return (KongregateIQExtension.ELEMENT);
}
public function get opcode():String{
return (mOpcode);
}
public function set opcode(theOpcode:String):void{
mOpcode = theOpcode;
}
public function deserialize(node:XMLNode):Boolean{
var children:Array;
var i:int;
var newlines:RegExp;
var base64:String;
var node = node;
setNode(node);
children = node.childNodes;
i = 0;
for (;i < children.length;(var _local3 = children[i].nodeName), if ("msg" === _local3){
} else {
//unresolved jump
continue;
}, //unexpected switch
, (i = (i + 1))) {
continue;
mOpcode = children[i].attributes.opcode;
newlines = /\n/g;
base64 = children[i].firstChild.nodeValue.replace(newlines, "");
mParams = JSON.decode(Base64.decode(base64));
//unresolved jump
var _slot1 = e;
mParams = {};
Log.error(((("Error deserializing kongregate IQ: (" + _slot1.toString()) + ")") + base64));
};
return (true);
}
public static function enable():void{
ExtensionClassRegistry.register(KongregateIQExtension);
}
}
}//package com.kongregate.as3.chat
Section 32
//SpamService (com.kongregate.as3.chat.SpamService)
package com.kongregate.as3.chat {
import com.kongregate.as3.common.events.*;
import flash.events.*;
import com.kongregate.as3.common.util.*;
import flash.utils.*;
public class SpamService {
private var mLastToggledAt:Array;
private var mNumTogglers:int;
private var mPort:String;
private var mUserList:Array;
private var mToggleTimer:Timer;
private var mConnections:Object;
private var mIp:String;
private var mHost:String;
private var mRoomInfo:Array;
public function SpamService(config:Object){
super();
mConnections = {};
mIp = config.ip;
mHost = config.host;
mPort = config.port;
}
private function onLogin(e:JabberEvent):void{
var username:String = e.data.username;
var jabber:JabberConnection = mConnections[username];
if (jabber == null){
return;
};
jabber.joinRoom(mRoomInfo[0], mRoomInfo[1], mRoomInfo[2]);
}
public function spamToggles(config:Object):void{
var interval:int = (config.interval) ? config.interval : 500;
mNumTogglers = (config.numToggle) ? config.numToggle : 5;
mLastToggledAt = [];
if (mToggleTimer){
mToggleTimer.stop();
mToggleTimer.removeEventListener(TimerEvent.TIMER, onToggleTimer);
mToggleTimer = null;
};
Log.warn("starting timer");
mToggleTimer = new Timer(interval);
mToggleTimer.addEventListener(TimerEvent.TIMER, onToggleTimer, false, 0, true);
mToggleTimer.start();
}
private function toggleRandomUser():void{
var i:int = Math.floor((Math.random() * mUserList.length));
if (((mLastToggledAt[i]) && (((getTimer() - mLastToggledAt[i]) < 2000)))){
return;
};
var jabber:JabberConnection = mConnections[mUserList[i]];
if (jabber.getRoom("chat")){
Log.warn((("user " + mUserList[i]) + " leaving the room"));
jabber.leaveRoom("chat");
} else {
Log.warn((("user " + mUserList[i]) + " joining the room"));
jabber.joinRoom(mRoomInfo[0], mRoomInfo[1], mRoomInfo[2]);
};
mLastToggledAt[i] = getTimer();
}
public function spamRoomJoins(config:Object):void{
var userArray:Array;
var connectTimer:Timer;
var jabber:JabberConnection;
var signedUserVariables:Array;
mUserList = [];
for each (userArray in config.users) {
mUserList.push(userArray[0]);
jabber = new JabberConnection({ip:mIp, host:mHost, port:mPort});
jabber.addEventListener(JabberEvent.LOGIN, onLogin);
signedUserVariables = [userArray[2].user_vars_sig, userArray[2].user_vars];
jabber.user = new User(userArray[0], userArray[1], signedUserVariables);
mConnections[userArray[0]] = jabber;
};
Log.warn("starting spam connect timer!");
connectTimer = new Timer(250, mUserList.length);
connectTimer.addEventListener(TimerEvent.TIMER, onConnectTimer);
connectTimer.start();
}
public function setRoomInfo(type:String, xName:String, name:String):void{
mRoomInfo = [type, xName, name];
}
private function onToggleTimer(e:TimerEvent):void{
var i:int;
Log.warn("on toggle timer");
while (i < mNumTogglers) {
toggleRandomUser();
i++;
};
}
private function onConnectTimer(e:TimerEvent):void{
var i:int = (e.target.currentCount - 1);
Log.warn(("currentCount - " + i));
mConnections[mUserList[i]].connect();
}
}
}//package com.kongregate.as3.chat
Section 33
//User (com.kongregate.as3.chat.User)
package com.kongregate.as3.chat {
import com.kongregate.as3.common.util.*;
import flash.utils.*;
import com.adobe.serialization.json.*;
import com.kongregate.as3.security.*;
public class User {
private var mUsername:String;
private var mPassword:String;
private var mVariables:Object;
private var mSignedVariables:Array;
private static const GUEST_PREFIX:String = "guest";
private static const KEY_MAP:Object = {username:0, type:1, level:2, chat_avatar_url:3, game_title:4, game_url:5};
public function User(username:String, password:String=null, signedVariables:Array=null){
super();
mUsername = username;
mPassword = (("{'k':'" + password) + "'}");
if (((!(isGuest())) && (!((signedVariables == null))))){
mSignedVariables = signedVariables;
parseSignedVariables(signedVariables);
} else {
mVariables = {};
};
}
public function getCompressedVariables():String{
return (this.compressedVariables);
}
private function processRemoteVariables():void{
var components:Array;
var subdomain:String;
var path:String;
var httpRegExp:RegExp = /^http:/;
var gamesRegExp:RegExp = /^\/games/;
var gameUrl:String = variables.game_url;
var avatarUrl:String = variables.chat_avatar_url;
if (((!(gameUrl.match(httpRegExp))) && (!(gameUrl.match(gamesRegExp))))){
gameUrl = ("/games" + gameUrl);
};
if (((!(avatarUrl.match(httpRegExp))) && (avatarUrl.match(/:/)))){
components = avatarUrl.split(":");
if (((!(components)) || ((components.length < 2)))){
throw (new Error(("Invalid short-form avatar url: " + avatarUrl)));
};
subdomain = components[0];
path = components[1];
avatarUrl = (((("http://" + subdomain) + ".") + Configuration.getConfigValue("base_domain")) + path);
};
variables.chat_avatar_url = encodeURI(avatarUrl);
variables.game_url = encodeURI(gameUrl);
}
function get compressedVariables():String{
var byteArray:ByteArray = new ByteArray();
byteArray.writeObject(mSignedVariables);
byteArray.compress();
return (Base64.encodeByteArray(byteArray));
}
public function isGuest():Boolean{
return ((0 == username.toLowerCase().indexOf(GUEST_PREFIX)));
}
private function parseSignedVariables(signedVariables:Array):void{
var keyName:String;
var sig:*;
var json:String;
var unsignedVars:Object;
var variables:Array;
var userType:String;
var signedVariables = signedVariables;
mVariables = {};
if (isGuest()){
return;
};
if (signedVariables.length > 2){
unsignedVars = signedVariables[2];
for (keyName in unsignedVars) {
if (!mVariables[keyName]){
mVariables[keyName] = unsignedVars[keyName];
};
};
};
sig = signedVariables[0];
json = signedVariables[1];
if (EncryptionUtils.verifyRSASignature(json, sig)){
variables = JSON.decode(json);
if (variables[KEY_MAP.username] == username){
for (keyName in KEY_MAP) {
mVariables[keyName] = variables[KEY_MAP[keyName]];
};
userType = (variables[KEY_MAP.type]) ? variables[KEY_MAP.type] : "";
mVariables.developer = (userType.indexOf("d") >= 0);
mVariables.admin = (userType.indexOf("a") >= 0);
mVariables.moderator = (userType.indexOf("m") >= 0);
mVariables.curator = (userType.indexOf("c") >= 0);
return;
};
Log.error(((("parseSignedVariables: expected username " + username) + ", but got ") + variables[username]));
};
//unresolved jump
var _slot1 = e;
Log.error(("parseSignedVariables: " + _slot1.toString()));
Log.error(("Failed to parse signed user vars: " + JSON.encode(signedVariables)));
mVariables = {};
}
public function parseCompressedVariables(compressedVars:String):void{
var byteArray:ByteArray;
var signedVariables:Array;
var compressedVars = compressedVars;
mVariables = new Object();
if (compressedVars != null){
byteArray = Base64.decodeToByteArray(compressedVars);
byteArray.uncompress();
signedVariables = byteArray.readObject();
parseSignedVariables(signedVariables);
//unresolved jump
var _slot1 = e;
Log.error(((("Error while decompressing variables: " + compressedVars) + ", ") + _slot1.toString()));
mVariables = {};
};
}
public function set variables(vars:Object):void{
mVariables = vars;
}
public function get username():String{
return (mUsername);
}
public function get variables():Object{
return (mVariables);
}
function get password():String{
return (mPassword);
}
public function validateUserVariables(remote:Boolean=true):Boolean{
var chatAvatarUrl:String;
var gameUrl:String;
var tagExp:RegExp;
var quoteOrSpaceExp:RegExp;
var remote = remote;
if (isGuest()){
return (true);
};
if (username != variables.username){
return (false);
};
if (((!((variables.level is Number))) || ((variables.level <= 0)))){
return (false);
};
chatAvatarUrl = variables.chat_avatar_url;
gameUrl = variables.game_url;
tagExp = /\<.+?\>/;
if (((((chatAvatarUrl.match(tagExp)) || (gameUrl.match(tagExp)))) || (variables.game_title.match(tagExp)))){
return (false);
};
quoteOrSpaceExp = /['" ]+/;
if (((chatAvatarUrl.match(quoteOrSpaceExp)) || (gameUrl.match(quoteOrSpaceExp)))){
return (false);
};
if (remote){
processRemoteVariables();
};
return (true);
//unresolved jump
var _slot1 = e;
Log.error(("Error while validating user variables: " + _slot1.toString()));
return (false);
}
public static function isValidUsername(username:String):Boolean{
return ((username.search(/^[^_]\w*$/) >= 0));
}
}
}//package com.kongregate.as3.chat
Section 34
//ExternalMessageDispatcher (com.kongregate.as3.common.comm.external.ExternalMessageDispatcher)
package com.kongregate.as3.common.comm.external {
import com.kongregate.as3.common.comm.*;
import com.kongregate.as3.common.util.*;
import flash.external.*;
public class ExternalMessageDispatcher implements IMessageHandler {
private var mListeners:Array;
private static var mInstance:ExternalMessageDispatcher;
public function ExternalMessageDispatcher(){
mListeners = new Array();
super();
}
public function addListener(listener:Function):void{
mListeners.push(listener);
}
public function handleExternalMessage(event:Object):void{
var cmd:String = event.type;
var params:Object = event.data;
var msg:Message = Message.fromOpcode(cmd);
msg.setParams(params);
broadcastMessage(msg);
}
public function addCallbacks():void{
ExternalInterface.addCallback("dispatchEvent", handleExternalMessage);
//unresolved jump
var _slot1 = e;
Log.info(("Error while trying to add callback: " + _slot1.toString()));
}
private function broadcastMessage(msg:Message):void{
Log.debug(("External message received: " + msg.toString()));
var i:Number = 0;
while (i < mListeners.length) {
var _local3 = mListeners;
_local3[i](msg);
i++;
};
}
public function handleMessage(localMessage:Message):void{
var msg:Message;
if (localMessage.getOpcode() == Opcode.OP_EXTERNAL_MESSAGE){
msg = Message.fromOpcode(localMessage.getParam(Opcode.PARAM_OPCODE));
msg.setParams(localMessage.getParam(Opcode.PARAM_DATA));
broadcastMessage(msg);
};
}
public static function getInstance():ExternalMessageDispatcher{
if (!mInstance){
mInstance = new (ExternalMessageDispatcher);
};
return (mInstance);
}
}
}//package com.kongregate.as3.common.comm.external
Section 35
//MessageConnection (com.kongregate.as3.common.comm.local.MessageConnection)
package com.kongregate.as3.common.comm.local {
import com.kongregate.as3.common.events.*;
import flash.events.*;
import com.kongregate.as3.common.comm.*;
import com.kongregate.as3.common.util.*;
import flash.utils.*;
import flash.net.*;
public class MessageConnection extends LocalConnection {
private var mAttemptingConnection:Boolean;// = false
private var mChannelName:String;// = ""
private var mConnectionAttempts:Number;// = 0
private var mConnectionTimer:Timer;
private var mIsClient:Boolean;// = false
private var mConnected:Boolean;// = false
private var mReceivedMessageParts:Object;
private var mReceiveChannel:String;// = ""
private var mClientCapabilities:uint;// = 0
private var mSendChannel:String;// = ""
private var mSequenceNumber:uint;// = 0
private var mReportSent:Boolean;// = false
private static const SERVICE_CHAT:String = "Chat";
private static const CONNECT_RETRY_COUNT:Number = 0;
private static const FULL_RECEIVE_FUNCTION:String = "handleMessage";
private static const SERVICE_GAME:String = "Game";
private static const LC_BYTE_LIMIT:uint = 39000;
private static const CHANNEL_PREFIX:String = "_";
public static const MY_CAPABILITIES:uint = 1;
private static const CONNECT_RETRY_INTERVAL:Number = 3500;
private static const PARTIAL_RECEIVE_FUNCTION:String = "handleMessagePart";
public static const SERVICE_NAME:String = "KongregateService";
public static const PARTIAL_MESSAGES:uint = 1;
private static const SERVICE_STRING:String = "Service";
public static const CLIENT_NAME:String = "KongregateClient";
public function MessageConnection($isClient:Boolean, channelName:String, autoConnect:Boolean=true){
var domain:String;
var prefix:String;
var theDomain:String;
var subdomain:String;
mReceivedMessageParts = {};
super();
this.addEventListener(StatusEvent.STATUS, onStatus);
mIsClient = $isClient;
mChannelName = channelName;
mSendChannel = (((CHANNEL_PREFIX + (isClient()) ? SERVICE_NAME : CLIENT_NAME) + "_") + mChannelName);
for each (domain in Utils.ALLOWED_DOMAINS) {
allowDomain(domain);
allowInsecureDomain(domain);
for each (prefix in Utils.ALLOWED_PREFIXES) {
theDomain = ((prefix + ".") + domain);
allowDomain(theDomain);
allowInsecureDomain(theDomain);
};
};
allowDomain(this.domain);
allowInsecureDomain(this.domain);
for each (prefix in Utils.ALLOWED_PREFIXES) {
subdomain = ((prefix + ".") + this.domain);
};
mConnectionTimer = new Timer(CONNECT_RETRY_INTERVAL, CONNECT_RETRY_COUNT);
mConnectionTimer.addEventListener(TimerEvent.TIMER, retryConnection);
if (autoConnect){
startListening();
};
}
public function isConnected():Boolean{
return (mConnected);
}
public function startListening():void{
listen((((isClient()) ? CLIENT_NAME : SERVICE_NAME + "_") + mChannelName));
}
private function sendMessagePart(messageNumber:uint, totalBytes:uint, part:ByteArray):Boolean{
var messageNumber = messageNumber;
var totalBytes = totalBytes;
var part = part;
Log.debug(((((("sending message part # - " + messageNumber) + ", totalBytes ") + totalBytes) + ", cursize ") + part.length));
send(mSendChannel, PARTIAL_RECEIVE_FUNCTION, messageNumber, totalBytes, part);
return (true);
//unresolved jump
var _slot1 = e;
Log.error(("MessageConnection error: " + _slot1.toString()));
return (false);
}
private function dumpMessage(msg:Message):String{
var fwdMsg:Message;
var url:String;
var opcode:String = msg.getOpcode();
if (msg.getOpcode() == Opcode.OP_FORWARD){
fwdMsg = Message.fromObject(msg.getParam(Opcode.PARAM_DATA));
return (((("<FWD:" + msg.getParam(Opcode.PARAM_USER)) + "> ") + dumpMessage(fwdMsg)));
};
if (opcode == Opcode.OP_PING){
return (undefined);
};
if (opcode == Opcode.OP_HTTP_REQUEST){
url = msg.getParam(Opcode.PARAM_URL);
if (!url){
return ((("<HTTP_RESPONSE, success=" + msg.getParam(Opcode.PARAM_SUCCESS)) + ">"));
};
return ((("<HTTP: " + url) + ">"));
} else {
if (opcode == Opcode.OP_META_INVALIDATE){
return ((((("<META.INVAL, phase_no=" + msg.getParam(Opcode.PARAM_STATE)["metagame"]["phase_no"]) + ", state=") + msg.getParam(Opcode.PARAM_STATE)["metagame"]["state"]) + ">"));
};
//unresolved if
};
return (!NULL!);
return (opcode);
}
public function sendMessage(msg:Message):Boolean{
var debugString:String;
var bytes:ByteArray;
var bytesLength:uint;
var byteOffset:uint;
var part:ByteArray;
var msg = msg;
if (Log.isDebug()){
debugString = dumpMessage(msg);
if (((debugString) && ((debugString.length > 0)))){
Log.debug(((((("[" + getReceiveNickname()) + "->") + getSendNickname()) + "]: ") + debugString));
};
};
if (usePartialMessages){
bytes = new ByteArray();
bytes.writeObject({opcode:msg.getOpcode(), params:msg.getParams()});
bytesLength = bytes.length;
mSequenceNumber++;
byteOffset = 0;
while (byteOffset < bytesLength) {
part = new ByteArray();
if ((bytesLength - byteOffset) > LC_BYTE_LIMIT){
part.length = LC_BYTE_LIMIT;
} else {
part.length = (bytesLength - byteOffset);
};
part.writeBytes(bytes, byteOffset, part.length);
if (!sendMessagePart(mSequenceNumber, bytesLength, part)){
return (false);
};
byteOffset = (byteOffset + part.length);
};
return (true);
} else {
send(mSendChannel, FULL_RECEIVE_FUNCTION, {opcode:msg.getOpcode(), params:msg.getParams()});
return (true);
//unresolved jump
var _slot1 = e;
Log.error(("MessageConnection error: " + _slot1.toString()));
};
return (false);
}
public function isServer():Boolean{
return (!(isClient()));
}
public function handleMessagePart(messageNumber:uint, totalBytes:uint, part:Object):void{
var byteHolder:ByteArray;
var messageNumber = messageNumber;
var totalBytes = totalBytes;
var part = part;
Log.debug(((((("handling message part # - " + messageNumber) + ", totalBytes ") + totalBytes) + ", cursize ") + part.length));
var bytePart:ByteArray = (part as ByteArray);
if (!mReceivedMessageParts[messageNumber]){
mReceivedMessageParts[messageNumber] = new ByteArray();
mReceivedMessageParts[messageNumber].length = totalBytes;
mReceivedMessageParts[messageNumber].position = 0;
};
byteHolder = mReceivedMessageParts[messageNumber];
byteHolder.writeBytes(bytePart);
//unresolved jump
var _slot1 = e;
Log.debug(((((("failed on part # - " + messageNumber) + ", totalBytes ") + totalBytes) + ", cursize ") + part.length));
if (0 == byteHolder.bytesAvailable){
byteHolder.position = 0;
handleMessage(byteHolder.readObject());
delete mReceivedMessageParts[messageNumber];
};
}
private function getSendNickname():String{
return (((mSendChannel.indexOf(SERVICE_STRING) >= 0)) ? SERVICE_CHAT : SERVICE_GAME);
}
public function isClient():Boolean{
return (mIsClient);
}
private function listen(channelName:String):void{
var channelName = channelName;
Log.info("Listening for connection...");
mReceiveChannel = (CHANNEL_PREFIX + channelName);
connect(mReceiveChannel);
Log.debug((("Channel: " + channelName) + ", success=true"));
//unresolved jump
var _slot1 = error;
Log.error((("Can't connect on channel: " + mReceiveChannel) + ". The connection name is already being used"));
}
public function doConnect():void{
Log.debug("MessageConnection.doConnect()");
mAttemptingConnection = true;
mConnectionAttempts = 0;
sendConnectionRequest();
if (mConnectionTimer.running){
mConnectionTimer.reset();
};
mConnectionTimer.start();
}
private function retryConnection(e:TimerEvent=null):void{
if (((mAttemptingConnection) && (!(mConnected)))){
mConnectionAttempts++;
sendConnectionRequest();
};
}
private function sendConnectionRequest():void{
Log.debug((("Attempting connection (Retry #" + mConnectionAttempts) + ")"));
var msg:Message = Message.fromOpcode(Opcode.OP_CONNECT);
msg.addParam(Opcode.PARAM_CHANNEL, mReceiveChannel);
msg.addParam(Opcode.PARAM_CAPABILITIES, MY_CAPABILITIES);
sendMessage(msg);
}
private function onStatus(e:StatusEvent):void{
var mEvent:MessageEvent;
var success:Boolean;
switch (e.level){
case "error":
Log.error("MessageConnection Error");
if (!mAttemptingConnection){
mEvent = new MessageEvent(MessageEvent.CONNECT);
success = this.dispatchEvent(mEvent);
};
break;
};
}
public function handleConnect(connectMessage:Message):void{
var msg:Message;
var e:MessageEvent;
var success:Boolean;
Log.info((((getReceiveNickname() + " received connect from ") + getSendNickname()) + "..."));
Log.debug((((", isConnected=" + mConnected) + ", attemptingConnection=") + mAttemptingConnection));
if (!mConnected){
mConnected = true;
mClientCapabilities = connectMessage.getParam(Opcode.PARAM_CAPABILITIES);
msg = Message.fromOpcode(Opcode.OP_CONNECTED);
sendMessage(msg);
e = new MessageEvent(MessageEvent.CONNECT);
success = this.dispatchEvent(e);
};
}
private function getReceiveNickname():String{
return (((mReceiveChannel.indexOf(SERVICE_STRING) >= 0)) ? SERVICE_CHAT : SERVICE_GAME);
}
private function get usePartialMessages():Boolean{
return (((isClient()) || ((mClientCapabilities & PARTIAL_MESSAGES))));
}
public function handleMessage(msgObject:Object):void{
var e:MessageEvent;
var success:Boolean;
var debugString:String;
var msg:Message = new Message();
msg.setOpcode(msgObject.opcode);
msg.setParams(msgObject.params);
if (Log.isDebug()){
debugString = dumpMessage(msg);
if (((debugString) && ((debugString.length > 0)))){
Log.debug(((((("[" + getSendNickname()) + "->") + getReceiveNickname()) + "]: ") + debugString));
};
Log.debug((("\nMessageConnection.handleMessage ['" + msg.getOpcode()) + "']"));
};
switch (msg.getOpcode()){
case Opcode.OP_CONNECT:
handleConnect(msg);
break;
case Opcode.OP_CONNECTED:
Log.info((("MessageConnection established for " + getReceiveNickname()) + "!"));
mAttemptingConnection = false;
mConnectionTimer.stop();
if (!mConnected){
mConnected = true;
e = new MessageEvent(MessageEvent.CONNECT);
success = this.dispatchEvent(e);
};
break;
default:
e = new MessageEvent(MessageEvent.MESSAGE, msg);
success = this.dispatchEvent(e);
};
}
}
}//package com.kongregate.as3.common.comm.local
Section 36
//IMessageHandler (com.kongregate.as3.common.comm.IMessageHandler)
package com.kongregate.as3.common.comm {
public interface IMessageHandler {
function handleMessage(:Message):void;
}
}//package com.kongregate.as3.common.comm
Section 37
//Message (com.kongregate.as3.common.comm.Message)
package com.kongregate.as3.common.comm {
import com.kongregate.as3.common.util.*;
import com.kongregate.as3.common.error.*;
public class Message {
private var mParams:Object;
private var mOpcode:String;
public function Message(){
super();
mOpcode = "";
mParams = new Object();
}
public function getOpcode():String{
return (mOpcode);
}
public function setParams(params:Object):void{
mParams = params;
}
public function toBase64():String{
return (Base64.encode(JSON.encode({mOpcode:mOpcode, mParams:mParams})));
}
public function isSuccessful():Boolean{
return (getParam(Opcode.PARAM_SUCCESS));
}
public function addParam(key:String, value):void{
mParams[key] = value;
}
public function getMessageID():Number{
return (getParam(Opcode.PARAM_MESSAGE_ID));
}
public function setOpcode(opcode:String):void{
mOpcode = opcode;
}
public function getError():int{
var error:int = getParam(Opcode.PARAM_ERROR);
return ((error) ? ErrorCode.NONE : error);
}
public function getRequestID():Number{
return (getParam(Opcode.PARAM_REQUEST_ID));
}
public function getParam(key:String){
return (mParams[key]);
}
public function toString():String{
return (((getOpcode() + ": ") + JSON.encode(getParams())));
}
public function getParams():Object{
return (mParams);
}
public static function fromObject(obj:Object):Message{
var msg:Message = Message.fromOpcode(obj.mOpcode);
msg.setParams(obj.mParams);
return (msg);
}
public static function fromBase64(base64:String):Message{
return (fromString(Base64.decode(base64)));
}
public static function fromString(text:String):Message{
var jsonObject:Object;
var msg:Message;
var key:String;
var text = text;
jsonObject = JSON.decode(text);
msg = Message.fromOpcode(jsonObject.mOpcode);
for (key in jsonObject.mParams) {
msg.addParam(key, jsonObject.mParams[key]);
};
return (msg);
//unresolved jump
var _slot1 = e;
return (null);
}
public static function fromOpcode(opcode:String):Message{
var msg:Message = new (Message);
msg.setOpcode(opcode);
return (msg);
}
}
}//package com.kongregate.as3.common.comm
Section 38
//Opcode (com.kongregate.as3.common.comm.Opcode)
package com.kongregate.as3.common.comm {
public class Opcode {
public static const PARAM_REQUEST_ID:String = "req.id";
public static const PARAM_WAIT:String = "wait";
public static const OP_CONNECTED:String = "connected";
public static const PARAM_RESULTS:String = "results";
public static const PARAM_MESSAGE:String = "message";
public static const PARAM_SUCCESS:String = "success";
public static const PARAM_GAME_TYPE:String = "game_type";
public static const PARAM_ROOM_NAME:String = "room.name";
public static const PARAM_STATE:String = "state";
public static const PARAM_SAVE_GAME:String = "game";
public static const OP_SCORE_SUBMIT:String = "score.submit";
public static const PARAM_SCORE:String = "score";
public static const PARAM_STATS:String = "stats";
public static const PARAM_RESULT:String = "result";
public static const OP_SAVE_SHARED_CONTENT:String = "save_shared_content";
public static const PARAM_ID:String = "id";
public static const OP_GAME_LOAD:String = "gm.load";
public static const PARAM_SORT:String = "sort_order";
public static const OP_AVATAR_FINISHED:String = "avatar.finished";
public static const PARAM_DATA:String = "data";
public static const PARAM_USER_ID:String = "user_id";
public static const PARAM_SCORE_POSTED:String = "posted";
public static const OP_STATS_PLAYER:String = "stat.player";
public static const OP_GAME_RESTART:String = "game_restart";
public static const OP_FORWARD:String = "fwd";
public static const PARAM_CAPABILITIES:String = "caps";
public static const PARAM_STAT_NAME:String = "stat";
public static const OP_META_JOIN:String = "meta.join";
public static const PARAM_FROM_PLAYER:String = "from.pl";
public static const PARAM_RESEND:String = "resend";
public static const PARAM_REASON:String = "reason";
public static const OP_GAME_SETTING_ON:String = "game_setting_on";
public static const OP_PARTICIPATE:String = "participate";
public static const OP_REQUEST_GAME_ROOM:String = "room.rq";
public static const PARAM_SCORE_MODE:String = "mode";
public static const PARAM_USER:String = "user";
public static const PARAM_CLIENT_VERSION:String = "client.ver";
public static const OP_META_PLAYNOW:String = "meta.playnow";
public static const OP_GAME_PAUSE:String = "game_pause";
public static const PARAM_SCORE_POSITION:String = "pos";
public static const PARAM_STAT_MAX:String = "max";
public static const OP_CONNECT:String = "connect";
public static const OP_SCORE_MODE:String = "score.mode";
public static const PARAM_SAVE_GAMES:String = "games";
public static const PARAM_SESSION_LOOKUP_KEY:String = "slk";
public static const OP_GAME_CONTINUE:String = "game_cont";
public static const OP_GAME_LOAD_ALL:String = "gm.load.all";
public static const PARAM_DECKS:String = "decks";
public static const PARAM_PATHS:String = "paths";
public static const PARAM_URL:String = "url";
public static const OP_SILENCED:String = "silenced";
public static const PARAM_FROM:String = "from";
public static const PARAM_GAME_END:String = "game_end";
public static const PARAM_LABEL:String = "label";
public static const PARAM_PRESENCE:String = "presence";
public static const OP_ALERT_REQUEST:String = "alert.rq";
public static const PARAM_SLOT:String = "slot";
public static const OP_GAME_SETTING_OFF:String = "game_setting_off";
public static const OP_GOODBYE:String = "goodbye";
public static const PARAM_PLAYER_NO:String = "player_no";
public static const PARAM_SESSION_ID:String = "sessionid";
public static const PARAM_JAVASCRIPT:String = "javascript";
public static const OP_STATS_REGISTER:String = "stat.reg";
public static const PARAM_ROOM_NATURAL_NAME:String = "room.natural";
public static const PARAM_SCORE_LOW:String = "lowscore";
public static const OP_PRIVATE_MESSAGE:String = "chat.pm";
public static const OP_GAME_MENU:String = "game_menu";
public static const PARAM_GAME_ID:String = "game_id";
public static const PARAM_PHASE_NO:String = "phase_no";
public static const PARAM_ALERT_NAME:String = "alert.name";
public static const PARAM_TASKS_COMPLETED:String = "stats.tc";
public static const OP_GAME_SAVE:String = "gm.save";
public static const PARAM_SAVE_LIST:String = "list";
public static const OP_GAME_START:String = "game_start";
public static const OP_HELLO:String = "hello";
public static const OP_META_EVENT:String = "meta.event";
public static const PARAM_GAME_START:String = "game_start";
public static const OP_META_STATE:String = "meta.state";
public static const PARAM_CONFIRMATION:String = "conf";
public static const PARAM_STATS_PROGRESSED:String = "stats.prgs";
public static const PARAM_OPPONENT:String = "opponent";
public static const OP_CHAT:String = "chat";
public static const OP_BROWSE_SHARED_CONTENT:String = "browse_shared_content";
public static const PARAM_DESCRIPTION:String = "desc";
public static const PARAM_MESSAGES:String = "msgs";
public static const OP_PING:String = "ping";
public static const PARAM_CHANNEL:String = "chnl";
public static const PARAM_NAME:String = "name";
public static const OP_META_CREATE:String = "meta.create";
public static const PARAM_GAME_AUTH_TOKEN:String = "auth_token";
public static const OP_GAME_UNPAUSE:String = "game_unpause";
public static const PARAM_IMAGE:String = "image";
public static const OP_GAME_DELETE:String = "gm.del";
public static const PARAM_DURATION:String = "duration";
public static const PARAM_LIST:String = "list";
public static const OP_GAME_SET_MODE:String = "game_set_mode";
public static const OP_HTTP_REQUEST:String = "http";
public static const PARAM_STAT_SORT:String = "sort";
public static const PARAM_SCORE_LIST:String = "list";
public static const OP_ALERT:String = "alert";
public static const PARAM_TIME:String = "time";
public static const PARAM_OPCODE:String = "opcode";
public static const PARAM_GAME_BREAK:String = "game_break";
public static const OP_GAME_MUTE:String = "game_mute";
public static const OP_SCORE_LIST:String = "score.list";
public static const OP_META_QUIT:String = "meta.quit";
public static const PARAM_CONFLICTS:String = "conflicts";
public static const OP_GAME_BREAK:String = "game_break";
public static const PARAM_GAME_NAME:String = "game_name";
public static const OP_STATS_SUBMIT:String = "stat.submit";
public static const OP_META_INVALIDATE:String = "meta.inval";
public static const OP_STATS_LIST:String = "stat.list";
public static const OP_META_JOINED:String = "meta.joined";
public static const PARAM_MESSAGE_ID:String = "msg.id";
public static const OP_GAME_END:String = "game_end";
public static const PARAM_STATS_CURRENT_HIGH_SCORE:String = "stats.current_high";
public static const PARAM_KEY:String = "key";
public static const OP_META_WAITING:String = "meta.waiting";
public static const PARAM_ERROR:String = "error";
public static const PARAM_INVALIDATED:String = "invalidated";
public static const PARAM_FILENAME:String = "filename";
public static const OP_LOAD_SHARED_CONTENT:String = "load_shared_content";
public static const PARAM_PERMALINK:String = "permalink";
public static const OP_SHARED_CONTENT_SAVE_COMPLETE:String = "shared_content_save_complete";
public static const OP_GAME_LIST_SAVES:String = "gm.list";
public static const PARAM_TO:String = "to";
public static const PARAM_STAT_START:String = "start";
public static const PARAM_CHOICE:String = "choice";
public static const OP_META_LIST:String = "meta.list";
public static const OP_DISCONNECT:String = "disconnect";
public static const OP_USER_INFO:String = "user.info";
public static const OP_GAME_UNMUTE:String = "game_unmute";
public static const OP_META_INFO:String = "meta.info";
public static const PARAM_TYPE:String = "type";
public static const OP_DISCONNECTED:String = "disconnected";
public static const OP_AVATAR_SUBMIT:String = "avatar.submit";
public static const OP_KICK:String = "kick";
public static const PARAM_CONTENT_TYPE:String = "content_type";
public static const OP_SET_PRESENCE:String = "set_presence";
public static const PARAM_GAME_VERSION:String = "gm.ver";
public static var OP_EXTERNAL_MESSAGE:String = "ext.msg";
public static var OP_CHAT_CLEAR_DIALOG:String = "chat.dlg.clear";
public static var OP_ITEM_INSTANCES:String = "mtx.item_instances";
public static var OP_CHAT_DISPLAY:String = "chat.disp";
public static var PARAM_ITEM_TAGS:String = "item_tags";
public static var OP_USE_ITEM_INSTANCE:String = "mtx.use_item_instance";
public static var OP_CHAT_MSG:String = "chat.msg";
public static var OP_CHAT_TAB:String = "chat.tab";
public static var OP_USER_PROFILE:String = "user.profile";
public static var OP_CHAT_DISPLAY_SIGN_IN:String = "chat.sign";
public static var OP_ITEM_CHECKOUT:String = "mtx.checkout";
public static var PARAM_ITEM_IDENTIFIERS:String = "item_ids";
public static var PARAM_ITEMS:String = "items";
public static var OP_CHAT_CANVAS_ELEMENT:String = "chat.elm";
public static var OP_ITEM_LIST:String = "mtx.item_list";
public static var PARAM_CANVAS_SIZE:String = "chat.canvas.size";
public function Opcode(){
super();
}
}
}//package com.kongregate.as3.common.comm
Section 39
//ErrorCode (com.kongregate.as3.common.error.ErrorCode)
package com.kongregate.as3.common.error {
public class ErrorCode {
public static const SAVE_TOO_LARGE:int = 3;
public static const NOT_AUTHORIZED:int = 1;
public static const NONE:int = 0;
public static const NOT_INITIALIZED:int = 4;
public static const SERVER_ERROR:int = 2;
public function ErrorCode(){
super();
}
}
}//package com.kongregate.as3.common.error
Section 40
//BufferedEventDispatcher (com.kongregate.as3.common.events.BufferedEventDispatcher)
package com.kongregate.as3.common.events {
import flash.events.*;
import flash.utils.*;
public class BufferedEventDispatcher extends EventDispatcher {
private var mEventQueue:Array;
private var mDispatchInterval:int;
private var mBatchSize:int;
private var mDispatchTimer:Timer;
public function BufferedEventDispatcher(dispatchInterval:int=50, batchSize:int=4){
super();
mDispatchInterval = dispatchInterval;
mBatchSize = batchSize;
mEventQueue = new Array();
mDispatchTimer = new Timer(dispatchInterval);
mDispatchTimer.addEventListener(TimerEvent.TIMER, onDispatchTimer, false, 0, true);
mDispatchTimer.start();
}
override public function dispatchEvent(e:Event):Boolean{
mEventQueue.unshift(e);
return (true);
}
public function shutdown():void{
mEventQueue = new Array();
mDispatchTimer.removeEventListener(TimerEvent.TIMER, onDispatchTimer);
mDispatchTimer.stop();
}
private function onDispatchTimer(e:TimerEvent):void{
var event:Event;
var numToDispatch:int = Math.min(mEventQueue.length, mBatchSize);
var i:int;
while (i < numToDispatch) {
event = mEventQueue.pop();
if (event){
super.dispatchEvent(event);
};
i++;
};
}
}
}//package com.kongregate.as3.common.events
Section 41
//ChatAPIEvent (com.kongregate.as3.common.events.ChatAPIEvent)
package com.kongregate.as3.common.events {
public class ChatAPIEvent extends KongregateEvent {
public static const CLEAR_CHAT:String = "custom_tab_clear_messages";
public static const SHOW_TAB:String = "custom_tab_show";
public static const DISPLAY_MESSAGE:String = "custom_tab_message";
public static const CLOSE_TAB:String = "custom_tab_close";
public function ChatAPIEvent(type:String, data:Object){
super(type, data);
}
}
}//package com.kongregate.as3.common.events
Section 42
//ClientMessageEvent (com.kongregate.as3.common.events.ClientMessageEvent)
package com.kongregate.as3.common.events {
import com.kongregate.as3.common.comm.*;
public class ClientMessageEvent extends MessageEvent {
public static const CLIENT_MESSAGE:String = "client_message";
public function ClientMessageEvent(msg:Message){
super(CLIENT_MESSAGE, msg);
}
}
}//package com.kongregate.as3.common.events
Section 43
//GameAPIEvent (com.kongregate.as3.common.events.GameAPIEvent)
package com.kongregate.as3.common.events {
public class GameAPIEvent extends KongregateEvent {
public static const SAVE_SHARED_CONTENT:String = "save_shared_content";
public static const STATISTIC_UPDATED:String = "statistic_updated";
public static const API_INITIALIZED:String = "api_initialized";
public static const SHARED_CONTENT_SAVE_COMPLETE:String = "shared_content_save_complete";
public static const NEW_HIGH_SCORE:String = "new_high_score";
public static const PROCESSING_SAVE_SHARED_CONTENT:String = "processing_save_shared_content";
public static const LOAD_SHARED_CONTENT:String = "load_shared_content";
public static const BROWSE_SHARED_CONTENT:String = "browse_shared_content";
public function GameAPIEvent(type:String, data:Object=null){
super(type, data);
}
}
}//package com.kongregate.as3.common.events
Section 44
//JabberEvent (com.kongregate.as3.common.events.JabberEvent)
package com.kongregate.as3.common.events {
public class JabberEvent extends KongregateEvent {
public static const LEAVE_ROOM:String = "leave_room";
public static const LOGIN:String = "login";
public static const CONNECT:String = "connect";
public static const PRIVATE_MESSAGE:String = "private_message";
public static const CONNECTION_ATTEMPT:String = "connection_attempt";
public static const JOIN_ROOM:String = "join_room";
public static const ERROR_MSG_RATE_LIMIT:String = "error_msg_rate_limit";
public static const MESSAGE_ERROR:String = "message_error";
public static const ROOM_MESSAGE:String = "room_message";
public static const DISCONNECT:String = "disconnect";
public static const USER_JOIN:String = "user_join";
public static const SILENCED:String = "silenced";
public static const USER_CHANGED:String = "user_changed";
public static const GUEST_COUNT:String = "guest_count";
public static const ERROR_MSG_TOO_LONG:String = "error_msg_too_long";
public static const USER_DEPARTURE:String = "user_departure";
public static const PARTICIPATE:String = "participate";
public function JabberEvent(type:String, data:Object=null){
super(type, data);
}
}
}//package com.kongregate.as3.common.events
Section 45
//KongregateEvent (com.kongregate.as3.common.events.KongregateEvent)
package com.kongregate.as3.common.events {
import flash.events.*;
public class KongregateEvent extends Event {
protected var mData:Object;
public function KongregateEvent(type:String, data:Object=null){
super(type);
mData = data;
}
public function toObject():Object{
return ({type:type, data:mData});
}
public function get data():Object{
return (mData);
}
public function get success():Boolean{
if (mData["success"] != null){
return (mData["success"]);
};
return (true);
}
}
}//package com.kongregate.as3.common.events
Section 46
//LogEvent (com.kongregate.as3.common.events.LogEvent)
package com.kongregate.as3.common.events {
import flash.events.*;
public class LogEvent extends Event {
private var _text;
public static const WARN:String = "Warn";
public static const ERROR:String = "Error";
public static const SPAM:String = "Spam";
public static const INFO:String = "Info";
public static const DEBUG:String = "Debug";
public static const TYPE_ALL:String = "All";
public function LogEvent(type:String, text){
super(type);
_text = text;
}
public function get text(){
return (_text);
}
}
}//package com.kongregate.as3.common.events
Section 47
//MessageEvent (com.kongregate.as3.common.events.MessageEvent)
package com.kongregate.as3.common.events {
import flash.events.*;
import com.kongregate.as3.common.comm.*;
public class MessageEvent extends Event {
private var mMessage:Message;
public static const MESSAGE:String = "msg_message";
public static const ERROR:String = "msg_error";
public static const CONNECT:String = "msg_connect";
public static const RECEIVED_KONG_IQ:String = "received_kong_iq";
public static const CLOSE:String = "msg_close";
public function MessageEvent(type:String, msg:Message=null){
super(type);
mMessage = msg;
}
public function get msg():Message{
return (mMessage);
}
}
}//package com.kongregate.as3.common.events
Section 48
//PeerMessageEvent (com.kongregate.as3.common.events.PeerMessageEvent)
package com.kongregate.as3.common.events {
import com.kongregate.as3.common.comm.*;
public class PeerMessageEvent extends MessageEvent {
public static const PEER_MESSAGE:String = "peer_message";
public function PeerMessageEvent(msg:Message){
super(PEER_MESSAGE, msg);
}
}
}//package com.kongregate.as3.common.events
Section 49
//ServerMessageEvent (com.kongregate.as3.common.events.ServerMessageEvent)
package com.kongregate.as3.common.events {
import com.kongregate.as3.common.comm.*;
public class ServerMessageEvent extends MessageEvent {
public static const SERVER_MESSAGE:String = "server_message";
public function ServerMessageEvent(msg:Message){
super(SERVER_MESSAGE, msg);
}
}
}//package com.kongregate.as3.common.events
Section 50
//ItemUtils (com.kongregate.as3.common.items.ItemUtils)
package com.kongregate.as3.common.items {
import com.adobe.serialization.json.*;
public class ItemUtils {
public function ItemUtils(){
super();
}
public static function buildCartJSON(items:Array):String{
var item:*;
var identifier:String;
var data:Object;
var cart:Array = [];
var i:int;
while (i < items.length) {
item = items[i];
if ((item is String)){
cart.push({identifier:item});
} else {
if ((item is Object)){
identifier = item["identifier"];
if (((identifier) && ((identifier.length > 0)))){
data = item["data"];
cart.push({identifier:identifier, data:data});
};
} else {
if ((((item is Array)) && ((item.length == 2)))){
cart.push({identifier:item[0], data:item[1]});
};
};
};
i++;
};
return (JSON.encode(cart));
}
}
}//package com.kongregate.as3.common.items
Section 51
//Statistic (com.kongregate.as3.common.stats.Statistic)
package com.kongregate.as3.common.stats {
import com.kongregate.as3.chat.*;
import com.kongregate.as3.service.*;
import com.kongregate.as3.common.util.*;
import flash.utils.*;
public class Statistic {
private var mCurrentValue:Number;
private var mName:String;
private var mSentAt:int;
private var mType:String;
private var mTaskProgresses:Array;
private var mStatisticService:StatisticService;
private var mDisplayInTable:Boolean;
private var mLastSentValue:Number;
private var mAccumulatedValue:Number;
private var mUpdatedAt:int;
private var mId:int;
private var mSavedValue:Number;
public static const MEDIUM_PRIORITY_MIN_WAIT_INTERVAL:int = 30000;
public static const MEDIUM:String = "medium";
public static const HIGH_PRIORITY_MIN_WAIT_INTERVAL:int = 15000;
public static const HIGH:String = "high";
public static const TYPE_MIN:String = "Min";
public static const TYPE_REPLACE:String = "Replace";
public static const LOW_PRIORITY_MIN_WAIT_INTERVAL:int = 120000;
public static const LOW:String = "low";
public static const HIGH_SCORE:String = "HighScore";
public static const TYPE_ADD:String = "Add";
public static const TYPE_MAX:String = "Max";
public function Statistic(id:int=0, name:String=null, type:String=null, show:Boolean=false, tasks:Array=null){
super();
mId = id;
mName = name;
mType = type;
mDisplayInTable = show;
if (tasks){
mTaskProgresses = tasks;
} else {
mTaskProgresses = [];
};
mSentAt = 0;
mAccumulatedValue = 0;
}
public function get taskProgresses():Array{
if (mTaskProgresses == null){
return ([]);
};
return (mTaskProgresses);
}
public function set lastSentValue(newValue:Number):void{
if (TYPE_ADD == mType){
return;
};
mLastSentValue = newValue;
}
public function set taskProgresses(tps:Array):void{
mTaskProgresses = tps;
}
public function get name():String{
return (mName);
}
public function set statisticService(ss:StatisticService):void{
mStatisticService = ss;
}
public function betterThanLastSentValue(newValue:Number):Boolean{
return (Statistic.betterThanForType(mLastSentValue, newValue, mType));
}
public function get displayInTable():Boolean{
return (mDisplayInTable);
}
public function markAsSent():void{
mSentAt = getTimer();
mLastSentValue = currentValue;
if (TYPE_ADD == mType){
mCurrentValue = 0;
};
}
public function get id():int{
return (mId);
}
public function setId(newId:int):void{
mId = newId;
}
public function set accumulatedValue(newValue:Number):void{
mAccumulatedValue = newValue;
}
public function readyToSend():Boolean{
if (!dirty()){
return (false);
};
return ((((0 == sentAt)) || (((getTimer() - sentAt) >= minWaitInterval()))));
}
public function get savedValue():Number{
return (mSavedValue);
}
public function get priority():String{
if (taskProgresses.length > 0){
return (HIGH);
};
if (displayInTable){
return (MEDIUM);
};
return (LOW);
}
public function get type():String{
return (mType);
}
public function betterThanSavedValue(newValue:Number):Boolean{
return (Statistic.betterThanForType(mSavedValue, newValue, mType));
}
public function get lastSentValue():Number{
return (mLastSentValue);
}
public function betterThanCurrentValue(newValue:Number):Boolean{
return (Statistic.betterThanForType(currentValue, newValue, mType));
}
public function get user():User{
if (!mStatisticService){
return (null);
};
return (mStatisticService.user);
}
private function minWaitInterval():int{
switch (priority){
case LOW:
return (LOW_PRIORITY_MIN_WAIT_INTERVAL);
case MEDIUM:
return (MEDIUM_PRIORITY_MIN_WAIT_INTERVAL);
case HIGH:
return (HIGH_PRIORITY_MIN_WAIT_INTERVAL);
};
return (300000);
}
public function get accumulatedValue():Number{
if (TYPE_ADD == type){
return (mAccumulatedValue);
};
return (value);
}
public function dirty():Boolean{
var i:int;
if (isNaN(currentValue)){
return (false);
};
if (TYPE_ADD == mType){
return (!((currentValue == 0)));
};
i = 0;
while (i < taskProgresses.length) {
if (betterThanForType(taskProgresses[i].currentProgress, currentValue, mType)){
return (true);
};
i++;
};
return (((betterThanSavedValue(currentValue)) && (betterThanLastSentValue(currentValue))));
}
public function set savedValue(newValue:Number):void{
mSavedValue = newValue;
}
public function sendImmediately():Boolean{
if (!dirty()){
return (false);
};
if (taskProgresses.length <= 0){
return (false);
};
var i:int;
while (i < taskProgresses.length) {
if (taskProgresses[i].isCompleted()){
Log.debug({taskCompleted:taskProgresses[i], value:value});
return (true);
};
i++;
};
return (false);
}
public function attemptTaskProgressUpdate(newValue:Number):void{
var tp:TaskProgress;
var i:int;
while (i < taskProgresses.length) {
tp = taskProgresses[i];
tp.attemptUpdate(newValue);
i++;
};
}
public function get sentAt():int{
return (mSentAt);
}
private function set currentValue(value:Number):void{
mUpdatedAt = getTimer();
mCurrentValue = value;
}
public function get value():Number{
return (currentValue);
}
public function attemptUpdate(newValue:Number):Boolean{
if (TYPE_ADD == mType){
if (isNaN(mCurrentValue)){
mCurrentValue = 0;
};
if (((!(user)) || (user.isGuest()))){
mAccumulatedValue = (mAccumulatedValue + newValue);
};
mCurrentValue = (mCurrentValue + newValue);
return (!((0 == newValue)));
};
if (!betterThanCurrentValue(newValue)){
return (false);
};
mCurrentValue = newValue;
return (true);
}
private function get currentValue():Number{
return (mCurrentValue);
}
public static function fromObject(o:Object):Statistic{
var task:TaskProgress;
var i:int;
var statistic:Statistic = new Statistic(o.id, o.name, o.stat_type, o.display_in_table);
if ((o.accomplishment_tasks is Array)){
i = 0;
while (i < o.accomplishment_tasks.length) {
task = TaskProgress.fromStatisticAndObject(statistic, o.accomplishment_tasks[i]);
statistic.taskProgresses.push(task);
i++;
};
};
return (statistic);
}
public static function betterThanForType(oldValue:Number, newValue:Number, type:String):Boolean{
if (TYPE_ADD == type){
throw (new Error("Cannot call betterThanCurrentValue() for add stats"));
};
if (isNaN(oldValue)){
return (true);
};
if (TYPE_MIN == type){
return ((newValue < oldValue));
};
if (TYPE_MAX == type){
return ((newValue > oldValue));
};
return (!((newValue == oldValue)));
}
}
}//package com.kongregate.as3.common.stats
Section 52
//TaskProgress (com.kongregate.as3.common.stats.TaskProgress)
package com.kongregate.as3.common.stats {
public class TaskProgress {
private var mStatistic:Statistic;
private var mId:int;
private var mQuota:Number;
private var mName:String;
private var mCurrentProgress:Number;
public function TaskProgress(statistic:Statistic, id:int=0, name:String=null, quota:Number=0){
super();
mStatistic = statistic;
mId = id;
mName = name;
mQuota = quota;
}
public function getStatistic():Statistic{
return (mStatistic);
}
public function setCurrentProgress(value:Number):void{
if (isNaN(value)){
return;
};
if (Statistic.TYPE_MIN == mStatistic.type){
if (value >= mCurrentProgress){
return;
};
} else {
if (value <= mCurrentProgress){
return;
};
};
mCurrentProgress = value;
}
public function get currentProgress():Number{
return (mCurrentProgress);
}
public function isCompleted():Boolean{
if (isNaN(mCurrentProgress)){
return (false);
};
if (Statistic.TYPE_MIN == mStatistic.type){
return ((mCurrentProgress <= mQuota));
};
return ((mCurrentProgress >= mQuota));
}
public function attemptUpdate(newValue:Number):Boolean{
if (Statistic.TYPE_ADD == mStatistic.type){
if (isNaN(mCurrentProgress)){
mCurrentProgress = 0;
};
mCurrentProgress = (mCurrentProgress + newValue);
return (!((0 == newValue)));
};
if (!Statistic.betterThanForType(mCurrentProgress, newValue, mStatistic.type)){
return (false);
};
mCurrentProgress = newValue;
return (true);
}
public function get name():String{
return (mName);
}
public function get id():Number{
return (mId);
}
public function get quota():Number{
return (mQuota);
}
public static function fromStatisticAndObject(s:Statistic, tp:Object):TaskProgress{
return (new TaskProgress(s, tp.id, tp.name, tp.quota));
}
}
}//package com.kongregate.as3.common.stats
Section 53
//BadLanguageFilter (com.kongregate.as3.common.util.BadLanguageFilter)
package com.kongregate.as3.common.util {
public class BadLanguageFilter {
private static const BAD_PHRASES:Array = ["fuck", "cunt", "cocksuck", "nigger", "faggot"];
private static const BAD_WORDS:Array = ["fag"];
private static var gBadRegExp:RegExp;
public function BadLanguageFilter(){
super();
}
public static function filter(text:String):String{
var ch:Number;
if (!gBadRegExp){
initialize();
};
var cleanMessage:String = "";
var i:int;
while (i < text.length) {
ch = text.charCodeAt(i);
if ((((((((ch < 32)) && (!((ch == 9))))) && (!((ch == 10))))) && (!((ch == 13))))){
} else {
cleanMessage = (cleanMessage + text.charAt(i));
};
i++;
};
return (cleanMessage.replace(gBadRegExp, "****"));
}
public static function initialize():void{
var i:int;
var singleWord:String;
var badWord:String;
var regExps:Array = [];
i = 0;
while (i < BAD_PHRASES.length) {
badWord = BAD_PHRASES[i];
singleWord = badWord.replace(/\w(?=\w)/g, "$&[\\s;]*");
regExps.push((("(" + singleWord) + ")"));
i++;
};
i = 0;
while (i < BAD_WORDS.length) {
badWord = BAD_WORDS[i];
singleWord = badWord.replace(/\w(?=\w)/g, "$&[\\s;]*");
singleWord = (("\\b(" + singleWord) + ")\\b");
regExps.push(singleWord);
i++;
};
gBadRegExp = new RegExp(regExps.join("|"), "gi");
}
}
}//package com.kongregate.as3.common.util
Section 54
//Base64 (com.kongregate.as3.common.util.Base64)
package com.kongregate.as3.common.util {
import flash.utils.*;
public class Base64 {
public static const version:String = "1.0.0";
private static const BASE64_CHARS:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
public function Base64(){
super();
throw (new Error("Base64 class is static container only"));
}
public static function encode(data:String):String{
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(data);
return (encodeByteArray(bytes));
}
public static function encodeByteArray(data:ByteArray):String{
var dataBuffer:Array;
var i:uint;
var j:uint;
var k:uint;
var output:String = "";
var outputBuffer:Array = new Array(4);
data.position = 0;
while (data.bytesAvailable > 0) {
dataBuffer = new Array();
i = 0;
while ((((i < 3)) && ((data.bytesAvailable > 0)))) {
dataBuffer[i] = data.readUnsignedByte();
i++;
};
outputBuffer[0] = ((dataBuffer[0] & 252) >> 2);
outputBuffer[1] = (((dataBuffer[0] & 3) << 4) | (dataBuffer[1] >> 4));
outputBuffer[2] = (((dataBuffer[1] & 15) << 2) | (dataBuffer[2] >> 6));
outputBuffer[3] = (dataBuffer[2] & 63);
j = dataBuffer.length;
while (j < 3) {
outputBuffer[(j + 1)] = 64;
j++;
};
k = 0;
while (k < outputBuffer.length) {
output = (output + BASE64_CHARS.charAt(outputBuffer[k]));
k++;
};
};
return (output);
}
public static function decode(data:String):String{
var bytes:ByteArray = decodeToByteArray(data);
return (bytes.readUTFBytes(bytes.length));
}
public static function decodeToByteArray(data:String):ByteArray{
var j:uint;
var k:uint;
var output:ByteArray = new ByteArray();
var dataBuffer:Array = new Array(4);
var outputBuffer:Array = new Array(3);
var i:uint;
while (i < data.length) {
j = 0;
while ((((j < 4)) && (((i + j) < data.length)))) {
dataBuffer[j] = BASE64_CHARS.indexOf(data.charAt((i + j)));
j++;
};
outputBuffer[0] = ((dataBuffer[0] << 2) + ((dataBuffer[1] & 48) >> 4));
outputBuffer[1] = (((dataBuffer[1] & 15) << 4) + ((dataBuffer[2] & 60) >> 2));
outputBuffer[2] = (((dataBuffer[2] & 3) << 6) + dataBuffer[3]);
k = 0;
while (k < outputBuffer.length) {
if (dataBuffer[(k + 1)] == 64){
break;
};
output.writeByte(outputBuffer[k]);
k++;
};
i = (i + 4);
};
output.position = 0;
return (output);
}
}
}//package com.kongregate.as3.common.util
Section 55
//Configuration (com.kongregate.as3.common.util.Configuration)
package com.kongregate.as3.common.util {
import flash.display.*;
public class Configuration {
private static var gConfig:Object = null;
public function Configuration(){
super();
}
public static function initialize(parent:DisplayObject, config:Object=null):void{
var parent = parent;
var config = config;
if (config != null){
gConfig = config;
} else {
gConfig = parent.loaderInfo.parameters;
if (getConfigValue("debug_level")){
Log.setLogLevel(int(getConfigValue("debug_level")));
} else {
Log.setLogLevel(1);
};
Log.debug({Flashvars:gConfig});
//unresolved jump
var _slot1 = e;
gConfig = null;
Log.error(("Couldn't get configuration object: " + _slot1.toString()));
};
}
public static function getConfigValue(key:String):String{
return (gConfig[key]);
}
public static function getConfig():Object{
return (gConfig);
}
}
}//package com.kongregate.as3.common.util
Section 56
//JSON (com.kongregate.as3.common.util.JSON)
package com.kongregate.as3.common.util {
public class JSON {
public function JSON(){
super();
}
public static function encode(o):String{
var c:String;
var i:Number;
var l:Number;
var v:*;
var prop:String;
var _local8:Number;
var s:String = "";
switch (typeof(o)){
case "object":
if (o){
if ((o is Array)){
l = o.length;
i = 0;
while (i < l) {
v = encode(o[i]);
if (s){
s = (s + ",");
};
s = (s + v);
i++;
};
return ((("[" + s) + "]"));
} else {
if (typeof(o.toString) != "undefined"){
for (prop in o) {
v = o[prop];
if (((!((typeof(v) == "undefined"))) && (!((typeof(v) == "function"))))){
v = encode(v);
if (s){
s = (s + ",");
};
s = (s + ((encode(prop) + ":") + v));
};
};
return ((("{" + s) + "}"));
};
};
};
return ("null");
case "number":
return ((isFinite(o)) ? String(o) : "null");
case "string":
l = o.length;
s = "\"";
i = 0;
while (i < l) {
c = o.charAt(i);
if (c >= " "){
if ((((c == "\\")) || ((c == "\"")))){
s = (s + "\\");
};
s = (s + c);
} else {
switch (c){
case "\b":
s = (s + "\\b");
break;
case "\f":
s = (s + "\\f");
break;
case "\n":
s = (s + "\\n");
break;
case "\r":
s = (s + "\\r");
break;
case "\t":
s = (s + "\\t");
break;
default:
_local8 = c.charCodeAt();
s = (s + (("\\u00" + Math.floor((_local8 / 16)).toString(16)) + (_local8 % 16).toString(16)));
};
};
i = (i + 1);
};
return ((s + "\""));
case "boolean":
return (String(o));
default:
return ("null");
};
}
public static function decode(source:String){
var at:Number;
var ch:String;
var _isDigit:Function;
var _isHexDigit:Function;
var _white:Function;
var _string:Function;
var _next:Function;
var _array:Function;
var _object:Function;
var _number:Function;
var _word:Function;
var _value:Function;
var _error:Function;
var source = source;
source = new String(source);
at = 0;
ch = " ";
_isDigit = function (c:String){
return (((("0" <= c)) && ((c <= "9"))));
};
_isHexDigit = function (c:String){
return (((((_isDigit(c)) || (((("A" <= c)) && ((c <= "F")))))) || (((("a" <= c)) && ((c <= "f"))))));
};
_error = function (m:String):void{
throw (new Error(m, (at - 1)));
};
_next = function (){
ch = source.charAt(at);
at = (at + 1);
return (ch);
};
_white = function ():void{
while (ch) {
if (ch <= " "){
_next();
} else {
if (ch == "/"){
switch (_next()){
case "/":
do {
} while (((((_next()) && (!((ch == "\n"))))) && (!((ch == "\r")))));
break;
case "*":
_next();
while (true) {
if (ch){
if (ch == "*"){
if (_next() == "/"){
_next();
break;
};
} else {
_next();
};
} else {
_error("Unterminated Comment");
};
};
break;
default:
_error("Syntax Error");
};
} else {
break;
};
};
};
};
_string = function (){
var t:*;
var u:*;
var i:* = "";
var s:* = "";
var outer:Boolean;
if (ch == "\""){
while (_next()) {
if (ch == "\""){
_next();
return (s);
};
if (ch == "\\"){
switch (_next()){
case "b":
s = (s + "\b");
break;
case "f":
s = (s + "\f");
break;
case "n":
s = (s + "\n");
break;
case "r":
s = (s + "\r");
break;
case "t":
s = (s + "\t");
break;
case "u":
u = 0;
i = 0;
while (i < 4) {
t = parseInt(_next(), 16);
if (!isFinite(t)){
outer = true;
break;
};
u = ((u * 16) + t);
i = (i + 1);
};
if (outer){
outer = false;
break;
};
s = (s + String.fromCharCode(u));
break;
default:
s = (s + ch);
};
} else {
s = (s + ch);
};
};
};
_error("Bad String");
return (null);
};
_array = function (){
var a:Array = [];
if (ch == "["){
_next();
_white();
if (ch == "]"){
_next();
return (a);
};
while (ch) {
a.push(_value());
_white();
if (ch == "]"){
_next();
return (a);
};
if (ch != ","){
break;
};
_next();
_white();
};
};
_error("Bad Array");
return (null);
};
_object = function (){
var k:* = {};
var o:* = {};
if (ch == "{"){
_next();
_white();
if (ch == "}"){
_next();
return (o);
};
while (ch) {
k = _string();
_white();
if (ch != ":"){
break;
};
_next();
o[k] = _value();
_white();
if (ch == "}"){
_next();
return (o);
};
if (ch != ","){
break;
};
_next();
_white();
};
};
_error("Bad Object");
};
_number = function (){
var v:*;
var n:* = "";
var hex:String = "";
var sign:String = "";
if (ch == "-"){
n = "-";
sign = n;
_next();
};
if (ch == "0"){
_next();
if ((((ch == "x")) || ((ch == "X")))){
_next();
while (_isHexDigit(ch)) {
hex = (hex + ch);
_next();
};
if (hex == ""){
_error("mal formed Hexadecimal");
} else {
return (Number(((sign + "0x") + hex)));
};
} else {
n = (n + "0");
};
};
while (_isDigit(ch)) {
n = (n + ch);
_next();
};
if (ch == "."){
n = (n + ".");
while (((((_next()) && ((ch >= "0")))) && ((ch <= "9")))) {
n = (n + ch);
};
};
v = (1 * n);
if (!isFinite(v)){
_error("Bad Number");
} else {
return (v);
};
return (NaN);
};
_word = function (){
switch (ch){
case "t":
if ((((((_next() == "r")) && ((_next() == "u")))) && ((_next() == "e")))){
_next();
return (true);
};
break;
case "f":
if ((((((((_next() == "a")) && ((_next() == "l")))) && ((_next() == "s")))) && ((_next() == "e")))){
_next();
return (false);
};
break;
case "n":
if ((((((_next() == "u")) && ((_next() == "l")))) && ((_next() == "l")))){
_next();
return (null);
};
break;
};
_error("Syntax Error");
return (null);
};
_value = function (){
_white();
switch (ch){
case "{":
return (_object());
case "[":
return (_array());
case "\"":
return (_string());
case "-":
return (_number());
default:
return (((((ch >= "0")) && ((ch <= "9")))) ? _number() : _word());
};
};
return (_value());
}
}
}//package com.kongregate.as3.common.util
Section 57
//Log (com.kongregate.as3.common.util.Log)
package com.kongregate.as3.common.util {
import com.kongregate.as3.common.events.*;
import flash.events.*;
import flash.system.*;
import flash.external.*;
public class Log extends EventDispatcher {
private var mLogName:String;// = ""
private var mInitialized:Boolean;// = false
private var mLogLevel:Number;// = 3
private var mLogEntries:Array;
public static const MAX_LOG_ENTRIES:Number = 250;
private static var LEVELS:Array = ["Error", "Warn", "Info", "Debug", "Spam"];
private static var gInstance:Log;
public function Log(){
super();
}
public function getOSInfo():String{
return (((((((("OS: " + Capabilities.os) + ", ") + Capabilities.screenResolutionX) + "x") + Capabilities.screenResolutionY) + ", current version: ") + Capabilities.version));
}
private function onWarnMessage(e:LogEvent):void{
logToFirebug("warn", e.text);
}
private function setName(name:String):void{
mLogName = name;
}
public function addLogEntry(type:String, text):void{
if ((text is String)){
if (mLogEntries.length > MAX_LOG_ENTRIES){
mLogEntries.splice(0, 1);
};
mLogEntries.push({type:type, time:getTimestamp(), text:sanitize(text)});
};
}
private function init():void{
if (!mInitialized){
mInitialized = true;
this.addEventListener(LogEvent.DEBUG, onDebugMessage);
this.addEventListener(LogEvent.INFO, onInfoMessage);
this.addEventListener(LogEvent.WARN, onWarnMessage);
this.addEventListener(LogEvent.ERROR, onErrorMessage);
this.addEventListener(LogEvent.SPAM, onSpamMessage);
mLogEntries = new Array();
Log.info("kongregate log initialized.");
Log.info(getOSInfo());
};
}
private function log(level:int, text):void{
var levelString:String;
addLogEntry(levelString, text);
if (mLogLevel >= level){
levelString = getLevelString(level);
dispatch(levelString, text);
};
}
private function onDebugMessage(e:LogEvent):void{
logToFirebug("debug", e.text);
}
private function isDebug():Boolean{
return ((mLogLevel >= 4));
}
private function onErrorMessage(e:LogEvent):void{
logToFirebug("error", e.text);
}
private function onSpamMessage(e:LogEvent):void{
logToFirebug("debug", e.text);
}
private function getTimestamp():String{
var date:Date = new Date();
return (date.toString().split("GMT")[0]);
}
private function onInfoMessage(e:LogEvent):void{
logToFirebug("info", e.text);
}
public function setLogLevel(level:Number):void{
mLogLevel = level;
}
private function getErrorReport():Array{
return (mLogEntries);
}
private function sanitize(text:String):String{
return (text.split("<").join("<"));
}
private function logToFirebug(type:String, text):void{
var type = type;
var text = text;
var oldMarshalExceptions:Boolean = ExternalInterface.marshallExceptions;
ExternalInterface.marshallExceptions = true;
try {
ExternalInterface.call(("console." + type), text);
//unresolved jump
var _slot1 = e;
} finally {
ExternalInterface.marshallExceptions = oldMarshalExceptions;
};
}
private function dispatch(type:String, text):Boolean{
if (((!((mLogName == null))) && ((mLogName.length > 0)))){
if ((text is String)){
text = ((("[" + mLogName) + "] ") + text);
};
};
var success:Boolean = dispatchEvent(new LogEvent(type, text));
return (success);
}
private function getLevelString(level:int):String{
return (LEVELS[(level - 1)]);
}
public static function setName(name:String):void{
getInstance().setName(name);
}
public static function isDebug():Boolean{
return (getInstance().isDebug());
}
public static function setLogLevel(level:Number):void{
getInstance().setLogLevel(level);
}
public static function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void{
getInstance().addEventListener(type, listener, useCapture, priority, useWeakReference);
}
public static function warn(text):void{
getInstance().log(2, text);
}
public static function error(text):void{
getInstance().log(1, text);
}
public static function spam(text):void{
getInstance().log(5, text);
}
public static function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void{
getInstance().removeEventListener(type, listener, useCapture);
}
public static function getInstance():Log{
if (gInstance == null){
gInstance = new (Log);
gInstance.init();
};
return (gInstance);
}
public static function info(text):void{
getInstance().log(3, text);
}
public static function init():void{
getInstance().init();
}
public static function debug(text):void{
getInstance().log(4, text);
}
public static function getErrorReport():Array{
return (getInstance().getErrorReport());
}
public static function hasEventListener(type:String):Boolean{
return (getInstance().hasEventListener(type));
}
}
}//package com.kongregate.as3.common.util
Section 58
//RateLimiter (com.kongregate.as3.common.util.RateLimiter)
package com.kongregate.as3.common.util {
import flash.utils.*;
public class RateLimiter {
private var mLongestDuration:Number;
private var mRules:Array;
private var mTimestamps:Array;
public function RateLimiter(rateLimitRules:Array){
var rateLimitRules = rateLimitRules;
super();
mTimestamps = [];
mRules = rateLimitRules;
mLongestDuration = 0;
mRules.forEach(function (rule:Object, a, b):void{
if (rule.duration > mLongestDuration){
mLongestDuration = rule.duration;
};
});
}
public function ruleViolated():Object{
var now:int;
var occurenceCounts:Object;
var latest:int;
now = getTimer();
cull((now - mLongestDuration));
var cutoffTimes:Array = [];
cutoffTimes = mRules.map(function (rule:Object, a, b):int{
return ((now - rule.duration));
});
occurenceCounts = {};
cutoffTimes.sort();
var i:int = (cutoffTimes.length - 1);
while (i >= 0) {
latest = cutoffTimes[i];
occurenceCounts[(now - latest)] = mTimestamps.filter(function (timestamp:int, a, b):Boolean{
return ((timestamp >= latest));
}).length;
i = (i - 1);
};
if (Log.isDebug()){
Log.spam({rateLimiterOccurenceCounts:occurenceCounts});
};
var rulesViolated:Array = mRules.filter(function (rule:Object, aa, b):Boolean{
return ((occurenceCounts[rule.duration] > rule.capacity));
});
if (0 == rulesViolated.length){
mTimestamps.push(now);
};
return (rulesViolated[0]);
}
private function cull(cutoffTime:int):void{
var cutoffTime = cutoffTime;
mTimestamps = mTimestamps.filter(function (timestamp:int, a, b):Boolean{
return ((timestamp >= cutoffTime));
});
}
}
}//package com.kongregate.as3.common.util
Section 59
//StringTruncate (com.kongregate.as3.common.util.StringTruncate)
package com.kongregate.as3.common.util {
public class StringTruncate {
public function StringTruncate(){
super();
}
public static function truncateOn(originalString:String, newLength:int, truncateCharacter:String, truncationIndicator:String=""):String{
var nextTrunc:int;
if (originalString.length < newLength){
return (originalString);
};
newLength = (newLength - truncationIndicator.length);
var truncatedString:String = originalString.substr(0, newLength);
if (originalString.substr(newLength, truncateCharacter.length) != truncateCharacter){
nextTrunc = truncatedString.lastIndexOf(truncateCharacter);
truncatedString = truncatedString.substr(0, (newLength - (newLength - nextTrunc)));
};
truncatedString = (truncatedString + truncationIndicator);
return (truncatedString);
}
}
}//package com.kongregate.as3.common.util
Section 60
//Utils (com.kongregate.as3.common.util.Utils)
package com.kongregate.as3.common.util {
import flash.events.*;
import flash.utils.*;
import flash.net.*;
import flash.system.*;
import flash.external.*;
public class Utils {
public static const ALLOWED_PREFIXES:Array = ["a", "www", "chat", "internal"];
public static const ALLOWED_DOMAINS:Array = ["kongregate.com", "kongregatestage.com", "kongregatetrunk.com", "kongshred.com", "kongregatedev.com"];
public function Utils(){
super();
}
public static function getTimeStamp():String{
return (((Math.floor((Math.random() * 10000000)).toString() + "_") + getTimer()));
}
public static function isFrameTopLevel():Boolean{
if (ExternalInterface.call("isTopLevel")){
return (true);
};
//unresolved jump
var _slot1 = e;
return (false);
}
public static function doHttpRequest(method:String, url:String, dataObj:Object, resultCallback:Function, timeout:Number):void{
var method = method;
var url = url;
var dataObj = dataObj;
var resultCallback = resultCallback;
var timeout = timeout;
var request:URLRequest = new URLRequest(url);
request.method = method;
dataObj.ts = getTimeStamp();
request.data = createURLVariables(dataObj);
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
var internalCallback:Function = function (e:Event):void{
if (resultCallback != null){
resultCallback(processHttpResponse(e));
};
};
loader.addEventListener(Event.COMPLETE, internalCallback);
loader.addEventListener(IOErrorEvent.IO_ERROR, internalCallback);
loader.load(request);
//unresolved jump
var _slot1 = error;
internalCallback(null);
}
public static function submitAlert(body:String, type:String, username:String, reportName:String, game_id:Number, automatic:Number, onComplete:Function=null):void{
var logObj:Object = Log.getErrorReport();
var variables:URLVariables = new URLVariables("name=Franklin");
if (body){
variables.body = body;
};
if (game_id){
variables.game_id = game_id;
};
variables.automatic = ((((automatic == 1)) || ((automatic == true)))) ? 1 : 0;
variables.report_name = reportName;
variables.username = username;
variables.version = logObj.version;
variables[type] = JSON.encode(logObj.log);
sendHttpRequest("/alerts", variables, onComplete, 0);
}
private static function processHttpResponse(e:Event):Object{
var response:Object;
var e = e;
if ((((e == null)) || (!((e.type == Event.COMPLETE))))){
return ({success:false, response:null, parsed_response:null});
};
var target:URLLoader = (e.target as URLLoader);
var data:String = (target.data as String);
response = JSON.decode(data);
return ({success:true, response:data, parsed_response:response});
//unresolved jump
var _slot1 = e;
return ({success:true, response:data, parsed_response:null});
}
public static function allowDomains():void{
var domain:String;
var subdomain:String;
for each (domain in ALLOWED_DOMAINS) {
Security.allowDomain(domain);
for each (subdomain in ALLOWED_PREFIXES) {
Security.allowDomain(((subdomain + ".") + domain));
};
};
}
public static function crudUpdate(url:String, dataObj:Object, resultCallback:Function=undefined, timeout:Number=0):void{
dataObj._method = "put";
sendHttpRequest(url, dataObj, resultCallback, timeout);
}
public static function httpPost(url:String, dataObj:Object, resultCallback:Function, timeout:Number):void{
doHttpRequest(URLRequestMethod.POST, url, dataObj, resultCallback, timeout);
}
private static function createURLVariables(dataObject:Object):URLVariables{
var key:String;
var vars:URLVariables = new URLVariables();
for (key in dataObject) {
vars[key] = dataObject[key];
};
return (vars);
}
public static function displayLightbox(url:String):void{
var url = url;
ExternalInterface.call("top.lightbox.prototype.initialize", url);
//unresolved jump
var _slot1 = e;
}
public static function sendImageToServer(image:ByteArray, server:String, callback:Function):void{
var image = image;
var server = server;
var callback = callback;
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var request:URLRequest = new URLRequest((server + "/image_importer"));
request.requestHeaders.push(header);
request.method = URLRequestMethod.POST;
request.data = image;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, function (e:Event):void{
callback(e.target.data);
});
loader.load(request);
}
public static function submitGameAlert(username:String, gameID:int, channelID:String):void{
Utils.submitAlert("Automatically generated game alert", "game_log", username, channelID, gameID, 1);
}
public static function httpGet(url:String, dataObj:Object, resultCallback:Function, timeout:Number):void{
doHttpRequest(URLRequestMethod.GET, url, dataObj, resultCallback, timeout);
}
public static function getFlashMajorVersion():Number{
var versionArray:Array;
var idxSpace:Number;
var version:String = Capabilities.version;
if (((!(version)) || ((version.length == 0)))){
return (5);
};
versionArray = version.split(",");
idxSpace = versionArray[0].indexOf(" ");
return (Number(versionArray[0].substr(idxSpace)));
}
public static function crudCreate(url:String, dataObj:Object, resultCallback:Function, timeout:Number=0):void{
dataObj._method = "post";
sendHttpRequest(url, dataObj, resultCallback, timeout);
}
public static function crudDestroy(url:String, resultCallback:Function, timeout:Number=0):void{
sendHttpRequest(url, {_method:"delete"}, resultCallback, timeout);
}
public static function bind(functionToApply:Function, object:Object){
var functionToApply = functionToApply;
var object = object;
var temporaryFunction:Function = function ():Function{
return (function (){
functionToApply.apply(object, arguments);
});
};
return (temporaryFunction.apply(undefined));
}
private static function populateURLVariablesWithObject(container, val, base_property_name:String=null):void{
var element:*;
var property_name:String;
var i:String;
if ("function" == typeof(val)){
return;
};
if ("object" != typeof(val)){
container[base_property_name] = val;
};
for (i in val) {
element = val[i];
if ((((undefined == element)) || (("function" == typeof(element))))){
} else {
if (!base_property_name){
property_name = i;
} else {
property_name = (((base_property_name + "[") + i) + "]");
};
populateURLVariablesWithObject(container, element, property_name);
};
};
}
public static function sendHttpRequest(url:String, dataObj:Object, resultCallback:Function, timeout:Number):void{
var url = url;
var dataObj = dataObj;
var resultCallback = resultCallback;
var timeout = timeout;
dataObj.ts = getTimeStamp();
var request:URLRequest = new URLRequest(url);
request.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
populateURLVariablesWithObject(variables, dataObj);
request.data = variables;
var loader:URLLoader = new URLLoader();
if ("function" == typeof(resultCallback)){
loader.addEventListener(Event.COMPLETE, resultCallback);
};
if (timeout > 0){
loader.addEventListener(IOErrorEvent.IO_ERROR, resultCallback);
};
loader.load(request);
//unresolved jump
var _slot1 = error;
}
}
}//package com.kongregate.as3.common.util
Section 61
//EncryptionUtils (com.kongregate.as3.security.EncryptionUtils)
package com.kongregate.as3.security {
import flash.utils.*;
import com.hurlant.crypto.rsa.*;
import com.meychi.ascrypt3.*;
import com.hurlant.crypto.hash.*;
import com.hurlant.util.*;
public class EncryptionUtils {
private static var gSHA1:SHA1 = new SHA1();
public function EncryptionUtils(){
super();
}
public static function verifyRSASignature(text:String, sig):Boolean{
var publicModulo:String;
var key:RSAKey;
var generatedSig:String;
var dest:ByteArray;
var text = text;
var sig = sig;
if ((sig is String)){
sig = Base64.decodeToByteArray(sig);
};
var keyBits:int = (sig.length * 8);
var keyBytes:int = Math.min(20, ((keyBits / 8) - 11));
var publicExponent = "010001";
switch (keyBits){
case 0x0800:
publicModulo = "99C611C9D836B25447585E452D2EE182B6000D17AFDB635BACAA9ACB771F7DA590C92BCDE0D2F9ED25C8E460385C2A0452D6CE7E9D555A4997B96E4133924D97DE70C9BFAEEFE36CFC19F40B43A21CAE542DEF5FBE1B1E135587B69B13621605FC39A1A12F8CE6535624B25D72CC5A8FA422548D3CBC6641DDBB10EC180EA35708268C6667A83820746BFD350ECBC992E4290618D0143141A447BBB04722F37663CE24FE8E2995E28F7C18AB63EFD0F75065C630D4C8133FCD8B497372D0A81412279AF2D17460C50923A4F149BD81C92ECBACE7A4ACC7634FAB0A8621BFB72982AD75E4E034CD3496D9D1D136E3C2073B82714E02B62E022B506430E034B163";
break;
case 0x0400:
publicModulo = "BE52250928CCE10B71B7A2A57B38C9350C64B32C7B9B898398C1A2ECE4909C9D60212F839D6AAC30E9BF34F8D1BF82262453EC2EB6021F839FF255BDB28D7B36CD8F194C1923B4DB85B8F23C9522C71D99515127D3E4001266730EA3EEF4B3D5D8D7CAA78ADB0F4D78A44B58E8B1045A859976052685B79B38A05FABAF182DAF";
break;
case 0x0200:
publicModulo = "AD1B37CBC2D0D25A0F0DBD43EE8DFA9A4E62D6D373EC2139A59145E646DF9D29D5501CD5296D4CE49BF70C15F3E9D319756EB0483AD8C52166E119B728A2265F";
break;
case 384:
publicModulo = "E1DA91108A58294F4E8DE463ABADE3D3137C73C58F2B631B1C7A1AEE0F16F7D2F22EE3E644C933FF1E14DC00663BCD5F";
break;
case 0x0100:
publicModulo = "D90F37EB8EE783E1EBF7DB3F8DF443C077C1CF457CBAB127A30D393DCFD0EC1D";
break;
case 192:
publicModulo = "B8948BED5C4B6EC845DC9E16D3DBA6DB1D8BDB67EDEC3F67";
break;
case 128:
publicModulo = "C7FDADF9564247416D811A6ECDA1BCDD";
break;
default:
return (false);
};
key = RSAKey.parsePublicKey(publicModulo, publicExponent);
generatedSig = Hex.fromArray(gSHA1.hash(Hex.toArray(Hex.fromString(text)))).substr(0, (keyBytes * 2));
dest = new ByteArray();
key.verify(sig, dest, sig.length);
return ((Hex.fromArray(dest).toLowerCase() == generatedSig.toLowerCase()));
//unresolved jump
var _slot1 = e;
return (false);
}
public static function aesEncrypt(key:String, text:String):String{
var aes:Rijndael = new Rijndael(0x0100, 128);
return (aes.encrypt(text, generateKey(key), "ECB"));
}
private static function trimBack(str:String):String{
if (str.charCodeAt((str.length - 1)) < 32){
str = trimBack(str.substring(0, (str.length - 1)));
};
return (str);
}
public static function generateKey(text:String):String{
return (MD5.calculate(text));
}
public static function aesDecrypt(key:String, text:String):String{
var aes:Rijndael = new Rijndael(0x0100, 128);
var decryptedText:String = aes.decrypt(text, generateKey(key), "ECB").split(String.fromCharCode(0))[0];
decryptedText = trimBack(decryptedText);
return (decryptedText);
}
}
}//package com.kongregate.as3.security
Section 62
//ChatService (com.kongregate.as3.service.ChatService)
package com.kongregate.as3.service {
import com.kongregate.as3.common.events.*;
import flash.events.*;
import com.kongregate.as3.common.comm.*;
import com.kongregate.as3.common.util.*;
import flash.external.*;
public class ChatService extends EventDispatcher {
private var mGameApiService:GameAPIService;
private var mQueuedMessages:Array;
private var mCustomTabShowing:Boolean;// = false
public static var CUSTOM_TAB:String = "custom";
public static var DEFAULT_TAB:String = "Default";
public function ChatService(gameApi:GameAPIService){
mQueuedMessages = [];
super();
mGameApiService = gameApi;
mGameApiService.addEventListener(ClientMessageEvent.CLIENT_MESSAGE, onClientMessage);
}
private function onClientMessage(e:ClientMessageEvent):void{
if (!mGameApiService.chatApiEnabled){
return;
};
var msg:Message = e.msg;
switch (msg.getOpcode()){
case Opcode.OP_CHAT_DISPLAY_SIGN_IN:
displaySignInLightbox();
break;
case Opcode.OP_CHAT_DISPLAY:
handleChatMessage(msg);
break;
case Opcode.OP_CHAT_TAB:
handleTabMessage(msg);
break;
case Opcode.OP_CHAT_CANVAS_ELEMENT:
forwardToCanvasSwf(msg);
break;
case Opcode.OP_CHAT_CLEAR_DIALOG:
clearChat();
break;
};
}
private function clearChat():void{
dispatchEvent(new ChatAPIEvent(ChatAPIEvent.CLEAR_CHAT, {}));
}
private function handleChatMessage(msg:Message):void{
var username:String = msg.getParam(Opcode.PARAM_USER);
var message:String = msg.getParam(Opcode.PARAM_DATA);
if ((((((((username == null)) || ((username.length == 0)))) || ((message == null)))) || ((message.length == 0)))){
return;
};
if (username.indexOf("@") == 0){
username = username.substr(1, (username.length - 1));
};
var data:Object = {user:{username:username}, message:BadLanguageFilter.filter(message)};
var event:ChatAPIEvent = new ChatAPIEvent(ChatAPIEvent.DISPLAY_MESSAGE, data);
dispatchEvent(event);
}
private function forwardToCanvasSwf(msg:Message):void{
mQueuedMessages.push({type:msg.getOpcode(), data:msg.getParam(Opcode.PARAM_DATA)});
if (mCustomTabShowing){
flushMessageQueue();
};
}
private function flushMessageQueue():void{
var i:int;
for (;i < mQueuedMessages.length;(i = (i + 1))) {
ExternalInterface.call("konduitToCanvas", mQueuedMessages[i]);
continue;
var _slot1 = e;
Log.error(("Error during external interface call: " + _slot1.toString()));
};
mQueuedMessages = [];
}
private function displaySignInLightbox():void{
var url:String;
url = ("/accounts/new/behind_login.js?game_id=" + mGameApiService.gameId);
ExternalInterface.call("displayLightbox", url);
//unresolved jump
var _slot1 = e;
Log.error(("Error displaying lightbox: " + _slot1.toString()));
}
private function handleTabMessage(msg:Message):void{
var event:ChatAPIEvent;
mQueuedMessages = [];
var tabName:String = msg.getParam(Opcode.PARAM_NAME);
if (DEFAULT_TAB == tabName){
closeTab();
return;
};
var size:Number = msg.getParam(Opcode.PARAM_CANVAS_SIZE);
if (((!(isFinite(size))) || ((size < 0)))){
size = 0.5;
};
size = (Math.min(size, 1) / 2);
clearChat();
var data:Object = {name:tabName, description:msg.getParam(Opcode.PARAM_DESCRIPTION), size:size};
event = new ChatAPIEvent(ChatAPIEvent.SHOW_TAB, data);
dispatchEvent(event);
}
public function onCustomTabShown(params:Object):void{
if (!mGameApiService.chatApiEnabled){
return;
};
Log.info("Custom tab visible!");
mCustomTabShowing = true;
flushMessageQueue();
var msg:Message = Message.fromOpcode(Opcode.OP_CHAT_TAB);
msg.addParam(Opcode.PARAM_CANVAS_SIZE, {width:params.width, height:params.height});
mGameApiService.sendClientMessage(msg);
}
private function closeTab():void{
Log.info("Closing tab!");
mCustomTabShowing = false;
mQueuedMessages = [];
clearChat();
dispatchEvent(new ChatAPIEvent(ChatAPIEvent.CLOSE_TAB, {}));
}
public function onUserMessage(params:Object):void{
if (!mGameApiService.chatApiEnabled){
return;
};
var msg:Message = Message.fromOpcode(Opcode.OP_CHAT_MSG);
msg.addParam(Opcode.PARAM_USER, params.user.username);
msg.addParam(Opcode.PARAM_DATA, params.message);
mGameApiService.sendClientMessage(msg);
}
}
}//package com.kongregate.as3.service
Section 63
//GameAPIService (com.kongregate.as3.service.GameAPIService)
package com.kongregate.as3.service {
import com.kongregate.as3.chat.*;
import com.kongregate.as3.common.events.*;
import flash.events.*;
import com.kongregate.as3.common.comm.*;
import com.kongregate.as3.common.util.*;
import com.kongregate.as3.common.comm.local.*;
import com.kongregate.as3.common.comm.external.*;
import com.kongregate.as3.common.stats.*;
public class GameAPIService extends EventDispatcher {
private var mGameId:int;
private var mSessionLookupKeyPermission:Boolean;
private var mMicrotransactionService:MicrotransactionService;
private var mChatService:ChatService;
private var mChannelId:String;
private var mHighScoreService:HighScoreService;
private var mExternalMessageDispatcher:ExternalMessageDispatcher;
private var mGameTitle:String;
private var mChatApiPermission:Boolean;
private var mJabberConnection:JabberConnection;
private var mMicrotransactionApiPermission:Boolean;
private var mApiHost:String;
private var mGamePermalink:String;
private var mStatisticService:StatisticService;
private var mSharedContentApiPermission:Boolean;
private var mGameUrl:String;
private var mGameAuthToken:String;
private var mLocalConnection:MessageConnection;
public function GameAPIService(jabberConnection:JabberConnection, config:Object){
super();
mChannelId = config.channel_id;
mGameId = parseInt(config.game_id);
mGamePermalink = config.game_permalink;
mGameTitle = config.game_title;
mGameUrl = config.game_url;
mGameAuthToken = config.game_auth_token;
mSessionLookupKeyPermission = (config.permission_slk == "true");
mMicrotransactionApiPermission = (config.permission_mtx_api == "true");
mChatApiPermission = (config.permission_chat_api == "true");
mSharedContentApiPermission = (config.permission_sc_api == "true");
mApiHost = config.api_host;
mJabberConnection = jabberConnection;
mLocalConnection = new MessageConnection(false, mChannelId, false);
mStatisticService = new StatisticService(this);
mHighScoreService = new HighScoreService({api:this, stats:mStatisticService});
mMicrotransactionService = new MicrotransactionService(this);
mChatService = new ChatService(this);
mExternalMessageDispatcher = ExternalMessageDispatcher.getInstance();
mExternalMessageDispatcher.addListener(onExternalMessage);
initializeEventHandlers();
mLocalConnection.startListening();
}
public function get microtransactionApiEnabled():Boolean{
return (mMicrotransactionApiPermission);
}
private function onLocalConnect(e:MessageEvent):void{
var msg:Message = Message.fromOpcode(Opcode.OP_HELLO);
msg.addParam(Opcode.PARAM_SUCCESS, true);
sendClientMessage(msg);
sendUserInfo();
var event:GameAPIEvent = new GameAPIEvent(GameAPIEvent.API_INITIALIZED, {success:true});
dispatchEvent(event);
}
public function get gameTitle():String{
return (mGameTitle);
}
public function sendClientMessage(msg:Message):void{
if (mLocalConnection.isConnected()){
mLocalConnection.sendMessage(msg);
};
}
public function loadSharedContent(params:Object):void{
var msg:Message = Message.fromOpcode(Opcode.OP_LOAD_SHARED_CONTENT);
msg.addParam(Opcode.PARAM_DATA, params.content);
msg.addParam(Opcode.PARAM_CONTENT_TYPE, params.contentType);
msg.addParam(Opcode.PARAM_NAME, params.name);
msg.addParam(Opcode.PARAM_PERMALINK, params.permalink);
msg.addParam(Opcode.PARAM_ID, params.id);
msg.addParam(Opcode.PARAM_LABEL, params.label);
sendClientMessage(msg);
}
private function onLocalMessage(e:MessageEvent):void{
var msg:Message;
var event:GameAPIEvent;
var params:Object;
var fwd:Message;
var toUsername:String;
var e = e;
msg = e.msg;
switch (msg.getOpcode()){
case Opcode.OP_FORWARD:
fwd = Message.fromOpcode(msg.getParam(Opcode.PARAM_DATA).mOpcode);
toUsername = msg.getParam(Opcode.PARAM_USER);
fwd.setParams(msg.getParam(Opcode.PARAM_DATA).mParams);
fwd.addParam(Opcode.PARAM_FROM, username);
fwd.addParam(Opcode.PARAM_GAME_ID, gameId);
sendToPlayer(fwd, toUsername);
break;
case Opcode.OP_SAVE_SHARED_CONTENT:
if (!this.sharedContentApiEnabled){
params = {contentType:msg.getParam(Opcode.PARAM_CONTENT_TYPE)};
event = new GameAPIEvent(GameAPIEvent.SAVE_SHARED_CONTENT, params);
dispatchEvent(event);
sharedContentSaveComplete({success:false});
break;
};
Utils.sendImageToServer(msg.getParam(Opcode.PARAM_IMAGE), mApiHost, function (filename:String):void{
params = {contentType:msg.getParam(Opcode.PARAM_CONTENT_TYPE), content:msg.getParam(Opcode.PARAM_DATA), filename:filename, label:msg.getParam(Opcode.PARAM_LABEL)};
event = new GameAPIEvent(GameAPIEvent.SAVE_SHARED_CONTENT, params);
dispatchEvent(event);
});
dispatchEvent(new GameAPIEvent(GameAPIEvent.PROCESSING_SAVE_SHARED_CONTENT));
break;
case Opcode.OP_BROWSE_SHARED_CONTENT:
if (!this.sharedContentApiEnabled){
break;
};
params = {content_type:msg.getParam(Opcode.PARAM_CONTENT_TYPE), sort_order:msg.getParam(Opcode.PARAM_SORT), label:msg.getParam(Opcode.PARAM_LABEL)};
event = new GameAPIEvent(GameAPIEvent.BROWSE_SHARED_CONTENT, params);
dispatchEvent(event);
break;
};
dispatchEvent(new ClientMessageEvent(msg));
}
public function get gameUrl():String{
return (mGameUrl);
}
public function switchUser(user:User, gameAuthToken:String):void{
mJabberConnection.switchUser(user);
mGameAuthToken = gameAuthToken;
sendUserInfo();
}
public function get jabberConnection():JabberConnection{
return (mJabberConnection);
}
public function sendServerMessage(msg:Message):void{
msg.addParam(Opcode.PARAM_GAME_ID, gameId);
jabberConnection.sendKongregateMessage(msg);
}
public function get gamePermalink():String{
return (mGamePermalink);
}
public function get gameId():int{
return (mGameId);
}
public function get localConnection():MessageConnection{
return (mLocalConnection);
}
public function onServerMessage(e:MessageEvent):void{
dispatchEvent(new ServerMessageEvent(e.msg));
}
public function get chatApiService():ChatService{
return (mChatService);
}
public function get chatApiEnabled():Boolean{
return (mChatApiPermission);
}
private function sendUserInfo():void{
if (user == null){
return;
};
var msg:Message = Message.fromOpcode(Opcode.OP_USER_INFO);
msg.addParam(Opcode.PARAM_USER, user.username);
msg.addParam(Opcode.PARAM_GAME_AUTH_TOKEN, mGameAuthToken);
sendClientMessage(msg);
}
public function get sharedContentApiEnabled():Boolean{
return (mSharedContentApiPermission);
}
public function addStatistics(statistics:Array):void{
var statObject:Object;
for each (statObject in statistics) {
Log.info({addingStat:statObject});
mStatisticService.addStatistic(Statistic.fromObject(statObject));
};
mStatisticService.initialize();
}
public function sharedContentSaveComplete(params:Object):void{
var msg:Message = Message.fromOpcode(Opcode.OP_SHARED_CONTENT_SAVE_COMPLETE);
msg.addParam(Opcode.PARAM_DATA, params.content);
msg.addParam(Opcode.PARAM_SUCCESS, params.success);
msg.addParam(Opcode.PARAM_NAME, params.name);
msg.addParam(Opcode.PARAM_PERMALINK, params.permalink);
msg.addParam(Opcode.PARAM_ID, params.id);
msg.addParam(Opcode.PARAM_LABEL, params.label);
sendClientMessage(msg);
}
public function get username():String{
return (user.username);
}
public function get user():User{
return (jabberConnection.user);
}
private function onExternalMessage(msg:Message):void{
var msgToSend:Message = Message.fromOpcode(Opcode.OP_EXTERNAL_MESSAGE);
msgToSend.addParam(Opcode.PARAM_OPCODE, msg.getOpcode());
msgToSend.addParam(Opcode.PARAM_DATA, msg.getParams());
sendClientMessage(msgToSend);
}
public function get gameAuthToken():String{
return (mGameAuthToken);
}
public function onPeerMessage(e:MessageEvent):void{
sendClientMessage(e.msg);
}
public function onStatisticEvent(event:GameAPIEvent):void{
var e:GameAPIEvent = new GameAPIEvent(event.type, event.data);
dispatchEvent(e);
}
private function sendToPlayer(msg:Message, toUsername:String):void{
msg.addParam(Opcode.PARAM_FROM, username);
mJabberConnection.sendKongregateMessageToPlayer(msg, toUsername);
}
public function get clientHasSessionLookupKeyPermission():Boolean{
return (mSessionLookupKeyPermission);
}
private function initializeEventHandlers():void{
mLocalConnection.addEventListener(MessageEvent.CONNECT, onLocalConnect);
mLocalConnection.addEventListener(MessageEvent.MESSAGE, onLocalMessage);
mJabberConnection.addEventListener(MessageEvent.RECEIVED_KONG_IQ, onServerMessage);
mJabberConnection.addEventListener(PeerMessageEvent.PEER_MESSAGE, onPeerMessage);
mStatisticService.addEventListener(GameAPIEvent.STATISTIC_UPDATED, onStatisticEvent);
mStatisticService.addEventListener(GameAPIEvent.NEW_HIGH_SCORE, onStatisticEvent);
}
public function setAccomplishmentProgress(accomplishments:Array):void{
mStatisticService.setAccomplishmentProgress(accomplishments);
mStatisticService.initialize();
}
public function destroy():void{
removeEventHandlers();
mLocalConnection.close();
mMicrotransactionService.destroy();
}
public function get channelId():String{
return (mChannelId);
}
private function removeEventHandlers():void{
mLocalConnection.removeEventListener(MessageEvent.CONNECT, onLocalConnect);
mLocalConnection.removeEventListener(MessageEvent.MESSAGE, onLocalMessage);
mJabberConnection.removeEventListener(MessageEvent.RECEIVED_KONG_IQ, onServerMessage);
mJabberConnection.removeEventListener(PeerMessageEvent.PEER_MESSAGE, onPeerMessage);
mStatisticService.removeEventListener(GameAPIEvent.STATISTIC_UPDATED, onStatisticEvent);
mStatisticService.removeEventListener(GameAPIEvent.NEW_HIGH_SCORE, onStatisticEvent);
}
}
}//package com.kongregate.as3.service
Section 64
//HighScoreService (com.kongregate.as3.service.HighScoreService)
package com.kongregate.as3.service {
import com.kongregate.as3.common.events.*;
import com.kongregate.as3.common.comm.*;
import com.kongregate.as3.common.util.*;
import com.kongregate.as3.common.stats.*;
public class HighScoreService {
private var mStatisticService:StatisticService;
private var mGameAPIService:GameAPIService;
public function HighScoreService(config:Object){
super();
mGameAPIService = config.api;
mStatisticService = config.stats;
mGameAPIService.addEventListener(ClientMessageEvent.CLIENT_MESSAGE, onClientMessage);
}
private function getHighScoreList(statName:String):void{
var statistic:Statistic;
var statName = statName;
statistic = mStatisticService.findStatisticByName(statName);
if (!statistic){
Log.error((("Attempted to find statistic " + statName) + ", but statistic was not found."));
return;
};
var finished:Function = function (result:Object):void{
Log.info((((("High score list received for " + statName) + "(") + statistic.id) + ")"));
var success:Boolean = ((result.success) && (result.parsed_response));
var response:Message = Message.fromOpcode(Opcode.OP_SCORE_LIST);
response.addParam(Opcode.PARAM_SUCCESS, success);
response.addParam(Opcode.PARAM_STAT_NAME, statName);
response.addParam(Opcode.PARAM_SCORE_LIST, result.parsed_response);
mGameAPIService.sendClientMessage(response);
};
Log.info((((("Requesting high score list for statistic " + statName) + "(") + statistic.id) + ")"));
Utils.httpGet("/high_scores.json", {statistic_id:statistic.id}, finished, 0);
}
private function onClientMessage(e:ClientMessageEvent):void{
var msg:Message = e.msg;
switch (msg.getOpcode()){
case Opcode.OP_SCORE_LIST:
getHighScoreList(msg.getParam(Opcode.PARAM_STAT_NAME));
break;
};
}
}
}//package com.kongregate.as3.service
Section 65
//MicrotransactionService (com.kongregate.as3.service.MicrotransactionService)
package com.kongregate.as3.service {
import com.kongregate.as3.common.events.*;
import com.kongregate.as3.common.comm.*;
import com.kongregate.as3.common.util.*;
import com.kongregate.as3.common.items.*;
import com.adobe.crypto.*;
import flash.external.*;
public class MicrotransactionService {
private var mGameApiService:GameAPIService;
public function MicrotransactionService(gameApi:GameAPIService){
super();
mGameApiService = gameApi;
initializeEventListeners();
}
private function hasTag(item:Object, tag:String):Boolean{
var i:int;
while (i < item.tags.length) {
if (item.tags[i] == tag){
return (true);
};
i++;
};
return (false);
}
public function destroy():void{
removeEventListeners();
}
private function generateUserItemSignature(items:Array, username:String):String{
var itemInstance:Object;
var f:int;
var field:String;
var salt:String = "PC45.14,Hloi";
var sig:String = (salt + username.toLowerCase());
var fields:Array = ["identifier", "id", "data", "remaining_uses"];
var i:int;
while (i < items.length) {
itemInstance = items[i];
f = 0;
while (f < fields.length) {
field = fields[f];
sig = (sig + (itemInstance[field]) ? itemInstance[field] : "null");
f++;
};
i++;
};
return (MD5.hash(sig));
}
private function handleUseItemInstanceRequest(msg:Message):void{
var itemInstanceId:Number;
var msg = msg;
var username:String = mGameApiService.username;
itemInstanceId = msg.getParam(Opcode.PARAM_ID);
var finished:Function = function (result:Object):void{
Log.info(("Item instance use result for item instance id:" + itemInstanceId));
var parsedResponse:Object = result.parsed_response;
var success:Boolean = ((((result.success) && (parsedResponse))) && (parsedResponse.success));
var response:Message = Message.fromOpcode(Opcode.OP_USE_ITEM_INSTANCE);
response.addParam(Opcode.PARAM_SUCCESS, success);
response.addParam(Opcode.PARAM_REQUEST_ID, msg.getParam(Opcode.PARAM_REQUEST_ID));
response.addParam(Opcode.PARAM_ID, itemInstanceId);
mGameApiService.sendClientMessage(response);
};
Log.info(((("Requesting item instance use for " + username) + ", item ID: ") + itemInstanceId));
var params:Object = {api_key:mGameApiService.gameId, username:username, game_auth_token:mGameApiService.gameAuthToken, id:itemInstanceId};
Utils.httpPost("/api/use_item.json", params, finished, 0);
}
private function removeEventListeners():void{
mGameApiService.removeEventListener(ClientMessageEvent.CLIENT_MESSAGE, onClientMessage);
}
private function handleItemInstancesRequest(msg:Message):void{
var username:String;
var msg = msg;
username = msg.getParam(Opcode.PARAM_USER);
var finished:Function = function (result:Object):void{
var sig:String;
Log.info(("Item instance list received for " + username));
var success:Boolean = ((((result.success) && (result.parsed_response))) && (result.parsed_response.success));
if (success){
sig = generateUserItemSignature(result.parsed_response.items, username);
success = (sig.toLowerCase() == result.parsed_response.signature.toLowerCase());
};
var response:Message = Message.fromOpcode(Opcode.OP_ITEM_INSTANCES);
response.addParam(Opcode.PARAM_SUCCESS, success);
response.addParam(Opcode.PARAM_USER, username);
response.addParam(Opcode.PARAM_REQUEST_ID, msg.getParam(Opcode.PARAM_REQUEST_ID));
if (success){
response.addParam(Opcode.PARAM_DATA, result.parsed_response.items);
};
mGameApiService.sendClientMessage(response);
};
var params:Object = {api_key:mGameApiService.gameId, username:username};
Log.info(("Requesting item instance list from server for user " + username));
Utils.httpGet("/api/user_items.json", params, finished, 0);
}
private function handleItemCheckoutRequest(msg:Message):void{
var msg = msg;
var items:Array = msg.getParam(Opcode.PARAM_ITEMS);
var cartJSON:String = ItemUtils.buildCartJSON(items);
var url:String = ((mGameApiService.gameUrl + "/checkouts/new?cart=") + escape(cartJSON));
ExternalInterface.call("holodeck.recordAnalyticsEvent", "Lightbox", "Kred");
ExternalInterface.call("displayLightbox", url);
//unresolved jump
var _slot1 = e;
Log.error(("Error displaying lightbox: " + _slot1.toString()));
}
private function getTags(msg:Message):Array{
var tags:Array = msg.getParam(Opcode.PARAM_ITEM_TAGS);
if ((((tags == null)) || ((tags.length == 0)))){
return (null);
};
var cleanTags:Array = [];
var i:int;
while (i < tags.length) {
if (((((tags[i]) && ((tags[i] is String)))) && ((tags[i].length > 0)))){
cleanTags.push(tags[i]);
};
i++;
};
return (((cleanTags.length > 0)) ? cleanTags : null);
}
private function getItemsWithTags(items:Array, tags:Array):Array{
var taggedWithAll:Boolean;
var t:int;
if ((((tags == null)) || ((tags.length == 0)))){
return (items);
};
var taggedItems:Array = new Array();
var i:int;
while (i < items.length) {
taggedWithAll = true;
t = 0;
while (t < tags.length) {
if (!hasTag(items[i], tags[t])){
taggedWithAll = false;
break;
};
t++;
};
if (taggedWithAll){
taggedItems.push(items[i]);
};
i++;
};
return (taggedItems);
}
private function initializeEventListeners():void{
mGameApiService.addEventListener(ClientMessageEvent.CLIENT_MESSAGE, onClientMessage);
}
private function handleItemListRequest(msg:Message):void{
var tags:Array;
var msg = msg;
tags = getTags(msg);
var params:Object = {api_key:mGameApiService.gameId};
var finished:Function = function (result:Object):void{
var items:Array;
var response:Message = Message.fromOpcode(Opcode.OP_ITEM_LIST);
var success:Boolean = ((((result.success) && (result.parsed_response))) && (result.parsed_response.success));
response.addParam(Opcode.PARAM_SUCCESS, success);
response.addParam(Opcode.PARAM_REQUEST_ID, msg.getParam(Opcode.PARAM_REQUEST_ID));
if (success){
items = getItemsWithTags(result.parsed_response.items, tags);
response.addParam(Opcode.PARAM_DATA, items);
};
mGameApiService.sendClientMessage(response);
};
Log.info("Requesting item list from server");
Utils.httpGet("/api/items.json", params, finished, 0);
}
private function onClientMessage(e:ClientMessageEvent):void{
if (!mGameApiService.microtransactionApiEnabled){
return;
};
var msg:Message = e.msg;
var opcode:String = msg.getOpcode();
switch (opcode){
case Opcode.OP_ITEM_LIST:
handleItemListRequest(msg);
break;
case Opcode.OP_ITEM_INSTANCES:
handleItemInstancesRequest(msg);
break;
case Opcode.OP_ITEM_CHECKOUT:
handleItemCheckoutRequest(msg);
break;
case Opcode.OP_USE_ITEM_INSTANCE:
handleUseItemInstanceRequest(msg);
break;
};
}
}
}//package com.kongregate.as3.service
Section 66
//StatisticService (com.kongregate.as3.service.StatisticService)
package com.kongregate.as3.service {
import com.kongregate.as3.chat.*;
import com.kongregate.as3.common.events.*;
import flash.events.*;
import com.kongregate.as3.common.comm.*;
import com.kongregate.as3.common.util.*;
import flash.utils.*;
import com.kongregate.as3.common.stats.*;
public class StatisticService extends EventDispatcher {
private var mLowPriorityFlusher:Timer;
private var mMediumPriorityFlusher:Timer;
private var mStatisticsByName:Object;
private var mTasksById:Object;
private var mOnHoldAccomplishmentProgress:Array;
private var mGameAPIService:GameAPIService;
private var mStatisticsById:Object;
private var mInitialized:Boolean;
private var mStatistics:Object;
private var mHighPriorityFlusher:Timer;
public static const LOW_PRIORITY_FLUSHER_INTERVAL:int = 60000;
public static const MEDIUM_PRIORITY_FLUSHER_INTERVAL:int = 10000;
public static const HIGH_PRIORITY_MAX_STATS:int = 5;
public static const HIGH_PRIORITY_FLUSHER_INTERVAL:int = 10000;
public static const MEDIUM_PRIORITY_MAX_STATS:int = 10;
public static const LOW_PRIORITY_MAX_STATS:int = 10;
public function StatisticService(gameAPI:GameAPIService){
mLowPriorityFlusher = new Timer(LOW_PRIORITY_FLUSHER_INTERVAL);
mMediumPriorityFlusher = new Timer(MEDIUM_PRIORITY_FLUSHER_INTERVAL);
mHighPriorityFlusher = new Timer(HIGH_PRIORITY_FLUSHER_INTERVAL);
super();
mGameAPIService = gameAPI;
mInitialized = false;
mOnHoldAccomplishmentProgress = [];
mStatistics = {low:[], medium:[], high:[]};
mStatisticsByName = {};
mStatisticsById = {};
mTasksById = {};
mLowPriorityFlusher.addEventListener(TimerEvent.TIMER, flushLowPriorityStats);
mMediumPriorityFlusher.addEventListener(TimerEvent.TIMER, flushMediumPriorityStats);
mHighPriorityFlusher.addEventListener(TimerEvent.TIMER, flushHighPriorityStats);
if (mGameAPIService != null){
mGameAPIService.addEventListener(ClientMessageEvent.CLIENT_MESSAGE, onClientMessage);
};
}
private function parseTaskStatsProgressed(stats:Object):void{
var key:String;
var id:int;
var value:Number;
var statUpdated:GameAPIEvent;
if (null == stats){
return;
};
for (key in stats) {
id = int(key);
value = stats[key];
statUpdated = new GameAPIEvent(GameAPIEvent.STATISTIC_UPDATED, {id:id, value:value});
dispatchEvent(statUpdated);
};
}
private function maxStatsForPriority(priority:String):int{
switch (priority){
case Statistic.LOW:
return (LOW_PRIORITY_MAX_STATS);
case Statistic.MEDIUM:
return (MEDIUM_PRIORITY_MAX_STATS);
case Statistic.HIGH:
return (HIGH_PRIORITY_MAX_STATS);
};
return (0);
}
private function flushMediumPriorityStats(e:TimerEvent):void{
flushPriorityStats(Statistic.MEDIUM);
}
public function cullHighPriorityStats():void{
var statistic:Statistic;
var j:int;
var task:TaskProgress;
var i:int;
while (i < highPriorityStats.length) {
statistic = highPriorityStats[i];
j = 0;
while (j < statistic.taskProgresses.length) {
task = statistic.taskProgresses[j];
if (task.isCompleted()){
statistic.taskProgresses.splice(j, 1);
j--;
};
j++;
};
if (0 == statistic.taskProgresses.length){
Log.debug(((("Removing statistic '" + statistic.name) + "' from high priority stats - new priority - ") + statistic.priority));
highPriorityStats.splice(i, 1);
switch (statistic.priority){
case Statistic.LOW:
lowPriorityStats.push(statistic);
break;
case Statistic.MEDIUM:
mediumPriorityStats.push(statistic);
break;
};
};
i++;
};
}
private function parseCurrentHighScores(highScores:Object):void{
var id:int;
var newHighScore:Number;
if ((((null == highScores)) || (!((highScores is Array))))){
return;
};
var i:int;
while (i < highScores.length) {
id = highScores[i];
newHighScore = mStatisticsById[id].accumulatedValue;
dispatchEvent(new GameAPIEvent(GameAPIEvent.NEW_HIGH_SCORE, {id:id, value:newHighScore}));
i++;
};
}
private function flushPriorityStats(priority:String):void{
var statsForPriority:Array = mStatistics[priority];
statsForPriority.sortOn("sentAt", Array.NUMERIC);
var statsToSend:Array = [];
var i:int;
while (i < statsForPriority.length) {
if (statsForPriority[i].readyToSend()){
statsToSend.push(statsForPriority[i]);
};
if (statsToSend.length >= maxStatsForPriority(priority)){
break;
};
i++;
};
if (0 == statsToSend.length){
return;
};
var logObject:Object = {};
logObject[("flush" + priority)] = statsToSend;
Log.debug(logObject);
flushStats(statsToSend);
}
public function initialize():void{
if (((((((mInitialized) || (!(user)))) || (user.isGuest()))) || (!(hasStatistics())))){
return;
};
Log.debug("Initializing statistic service!");
Log.debug(((((("Stats count. Low:" + lowPriorityStats.length) + ", Medium:") + mediumPriorityStats.length) + ", High: ") + highPriorityStats.length));
Log.debug({lowStats:lowPriorityStats});
Log.debug({mediumStats:mediumPriorityStats});
Log.debug({highStats:highPriorityStats});
mHighPriorityFlusher.start();
mMediumPriorityFlusher.start();
mLowPriorityFlusher.start();
mGameAPIService.addEventListener(ServerMessageEvent.SERVER_MESSAGE, onServerMessage);
mInitialized = true;
if (mOnHoldAccomplishmentProgress.length > 0){
setAccomplishmentProgress(mOnHoldAccomplishmentProgress);
};
flushPriorityStats(Statistic.HIGH);
}
public function setTaskProgress(task:Object):void{
if (mTasksById[task.id]){
mTasksById[task.id].setCurrentProgress(task["current_progress"]);
Log.debug(((((("Setting task progress for '" + mTasksById[task.id].name) + "' to ") + mTasksById[task.id].currentProgress) + " from ") + task["current_progress"]));
} else {
Log.debug(("Skipping task not for this game with id: " + task.id));
};
}
public function setAPI(api:GameAPIService):void{
mGameAPIService = api;
}
public function get user():User{
return (mGameAPIService.user);
}
public function submitStat(name:String, value:Number):void{
value = Math.floor(value);
var statistic:Statistic = findStatisticByName(name);
if (statistic == null){
return;
};
if (((statistic.attemptUpdate(value)) && (user.isGuest()))){
dispatchEvent(new GameAPIEvent(GameAPIEvent.STATISTIC_UPDATED, {id:statistic.id, value:statistic.accumulatedValue}));
};
if (Statistic.HIGH == statistic.priority){
statistic.attemptTaskProgressUpdate(value);
};
if (((!(user.isGuest())) && (statistic.sendImmediately()))){
Log.debug({instaFlush:statistic});
flushStats([statistic]);
cullHighPriorityStats();
};
}
public function hasStatistics():Boolean{
return ((((((lowPriorityStats.length > 0)) || ((mediumPriorityStats.length > 0)))) || ((highPriorityStats.length > 0))));
}
private function flushLowPriorityStats(e:TimerEvent):void{
flushPriorityStats(Statistic.LOW);
}
private function onServerMessage(e:ServerMessageEvent):void{
var stats:Object;
var msg:Message = e.msg;
if (Opcode.OP_STATS_SUBMIT == msg.getOpcode()){
stats = msg.getParam(Opcode.PARAM_STATS);
parseServerStats(stats);
parseTaskStatsProgressed(msg.getParam(Opcode.PARAM_STATS_PROGRESSED));
parseTasksCompleted(msg.getParam(Opcode.PARAM_TASKS_COMPLETED));
parseCurrentHighScores(msg.getParam(Opcode.PARAM_STATS_CURRENT_HIGH_SCORE));
};
}
public function get highPriorityStats():Array{
return (mStatistics.high);
}
private function parseServerStats(stats:Object):void{
var key:String;
var id:int;
var statistic:Statistic;
var newSavedValue:Number;
if (null == stats){
return;
};
for (key in stats) {
id = int(key);
statistic = mStatisticsById[id];
newSavedValue = stats[key];
if (Statistic.TYPE_ADD == statistic.type){
statistic.accumulatedValue = (statistic.accumulatedValue + newSavedValue);
} else {
if (statistic.betterThanSavedValue(newSavedValue)){
statistic.savedValue = newSavedValue;
};
};
};
}
public function addStatistics(statistics:Array):void{
var statistic:Statistic;
for each (statistic in statistics) {
addStatistic(statistic);
};
}
private function onClientMessage(e:ClientMessageEvent):void{
var msg:Message;
var _local5:Array;
var stat:Object;
msg = e.msg;
switch (msg.getOpcode()){
case Opcode.OP_STATS_SUBMIT:
initialize();
_local5 = msg.getParam(Opcode.PARAM_STATS);
for each (stat in _local5) {
submitStat(stat.name, stat.value);
};
break;
};
}
public function get mediumPriorityStats():Array{
return (mStatistics.medium);
}
public function get lowPriorityStats():Array{
return (mStatistics.low);
}
public function addStatistic(statistic:Statistic):void{
var task:Object;
var i:int;
switch (statistic.priority){
case Statistic.LOW:
lowPriorityStats.push(statistic);
break;
case Statistic.MEDIUM:
mediumPriorityStats.push(statistic);
break;
case Statistic.HIGH:
highPriorityStats.push(statistic);
break;
};
mStatisticsByName[statistic.name] = statistic;
mStatisticsById[statistic.id] = statistic;
while (i < statistic.taskProgresses.length) {
task = statistic.taskProgresses[i];
mTasksById[task.id] = task;
i++;
};
}
private function flushHighPriorityStats(e:TimerEvent):void{
flushPriorityStats(Statistic.HIGH);
}
public function setAccomplishmentProgress(accomplishments:Array):void{
var tasks:Array;
var i:int;
var j:int;
if (!mInitialized){
mOnHoldAccomplishmentProgress = accomplishments;
return;
};
while (i < accomplishments.length) {
if ((accomplishments[i].accomplishment_tasks is Array)){
tasks = accomplishments[i].accomplishment_tasks;
j = 0;
while (j < tasks.length) {
setTaskProgress(tasks[j]);
j++;
};
};
i++;
};
cullHighPriorityStats();
}
public function findStatisticByName(name:String):Statistic{
return (mStatisticsByName[name]);
}
private function flushStats(stats:Array):void{
var stat:Statistic;
var formattedStats:Object = {};
var countFormattedStats:int;
var i:int;
while (i < stats.length) {
stat = stats[i];
if (((!(isNaN(stat.id))) && ((stat.id > 0)))){
formattedStats[stat.id] = stat.value;
countFormattedStats++;
};
stat.markAsSent();
i++;
};
var msg:Message = Message.fromOpcode(Opcode.OP_STATS_SUBMIT);
msg.addParam(Opcode.PARAM_USER, mGameAPIService.username);
Log.debug({statList:countFormattedStats});
if (countFormattedStats > 0){
msg.addParam(Opcode.PARAM_STATS, JSON.encode(formattedStats));
};
mGameAPIService.sendServerMessage(msg);
}
private function parseTasksCompleted(tasks:Object):void{
}
}
}//package com.kongregate.as3.service
Section 67
//Konduit (com.kongregate.as3.Konduit)
package com.kongregate.as3 {
import com.kongregate.as3.chat.*;
import com.kongregate.as3.service.*;
import com.kongregate.as3.common.events.*;
import com.kongregate.as3.common.util.*;
import flash.display.*;
import com.kongregate.as3.common.comm.external.*;
import flash.net.*;
import com.adobe.serialization.json.*;
import flash.system.*;
import flash.external.*;
public class Konduit extends Sprite {
private var mGameAPIService:GameAPIService;
private var mJabberConnection:JabberConnection;
private var mSpamService:SpamService;
public static const SAVE_SHARED_CONTENT:String = "load_shared_content";
public static const ROOM_MESSAGE:String = "room_message";
public static const TROLL_USERNAME:String = "bonus";
public static const PRIVATE_MESSAGE:String = "private_message";
public static const INIT:String = "init";
public static const SET_ACCOMPLISHMENT_PROGRESS:String = "set_accomplishment_progress";
private static const JABBER_EVENTS:Array = [JabberEvent.CONNECTION_ATTEMPT, JabberEvent.CONNECT, JabberEvent.DISCONNECT, JabberEvent.LOGIN, JabberEvent.JOIN_ROOM, JabberEvent.LEAVE_ROOM, JabberEvent.USER_JOIN, JabberEvent.ROOM_MESSAGE, JabberEvent.USER_CHANGED, JabberEvent.USER_DEPARTURE, JabberEvent.PRIVATE_MESSAGE, JabberEvent.MESSAGE_ERROR, JabberEvent.SILENCED, JabberEvent.PARTICIPATE, JabberEvent.GUEST_COUNT];
public static const ADD_STATISTICS:String = "add_statistics";
public static const GUEST_COUNT:String = "guest_count";
public static const SHOW_CUSTOM_TAB:String = "custom_tab_show";
public static const SPAM_ROOM_JOINS:String = "SPAM_ROOM_JOINS";
private static const CHAT_API_EVENTS:Array = [ChatAPIEvent.SHOW_TAB, ChatAPIEvent.CLOSE_TAB, ChatAPIEvent.CLEAR_CHAT, ChatAPIEvent.DISPLAY_MESSAGE];
public static const EVENT_JAVASCRIPT_DISPATCH:String = "javascript_dispatch";
public static const LOGIN:String = "login";
public static const CONNECT:String = "connect";
public static const CONNECTION_ATTEMPT:String = "connection_attempt";
public static const CUSTOM_TAB_MESSAGE:String = "custom_tab_message";
public static const JOIN_ROOM:String = "join_room";
public static const EVENT_JAVASCRIPT:String = "javascript_event";
public static const BROWSE_SHARED_CONTENT:String = "browse_shared_content";
public static const SET_PRESENCE:String = "set_presence";
public static const CLEAR_CUSTOM_TAB_MESSAGES:String = "custom_tab_clear_messages";
private static const GAME_API_EVENTS:Array = [GameAPIEvent.API_INITIALIZED, GameAPIEvent.STATISTIC_UPDATED, GameAPIEvent.NEW_HIGH_SCORE, GameAPIEvent.PROCESSING_SAVE_SHARED_CONTENT, GameAPIEvent.SAVE_SHARED_CONTENT, GameAPIEvent.BROWSE_SHARED_CONTENT];
public static const CLOSE_CUSTOM_TAB:String = "custom_tab_close";
public static const API_INITIALIZED:String = "api_initialized";
public static const LOAD_SHARED_CONTENT:String = "load_shared_content";
public static const SHARED_CONTENT_SAVE_COMPLETE:String = "shared_content_save_complete";
public static const SWITCH_USER:String = "switch_user";
public function Konduit(config:Object=null):void{
super();
Log.setName("Konduit");
Log.info("Konduit initialized");
Configuration.initialize(this, config);
dispatchJavascriptEvent(new KongregateEvent(INIT));
if (getConfigValue("connect")){
initialize();
};
}
public function get gameAPI():GameAPIService{
return (mGameAPIService);
}
private function setObfuscatedCookie(key:String, value:String):void{
setCookie(key, Base64.encode(value));
}
private function getObfuscatedCookie(key:String):String{
var result:Object = getCookie(key);
if (result){
return (Base64.decode(result.toString()));
};
return (null);
}
public function onJavascriptEvent(e:Object):void{
var event:KongregateEvent;
var signedUserVariables:Array;
var e = e;
if (Log.isDebug()){
Log.debug(("Event received from JS: " + e.type));
Log.debug({eventReceived:e});
};
switch (e.type){
case CONNECT:
mJabberConnection.connect();
break;
case ROOM_MESSAGE:
mJabberConnection.sendRoomMessage(e.data.room.type, e.data.message);
break;
case PRIVATE_MESSAGE:
mJabberConnection.sendPrivateMessage(e.data.username, e.data.message);
break;
case JOIN_ROOM:
mJabberConnection.joinRoom(e.data.room.type, e.data.room.xmpp_name, e.data.room.name);
mSpamService.setRoomInfo(e.data.room.type, e.data.room.xmpp_name, e.data.room.name);
break;
case SWITCH_USER:
signedUserVariables = [e.data.variables.user_vars_sig, e.data.variables.user_vars];
mGameAPIService.switchUser(new User(e.data.username, e.data.slk, signedUserVariables), e.data.game_auth_token);
break;
case ADD_STATISTICS:
mGameAPIService.addStatistics(e.data);
break;
case SET_ACCOMPLISHMENT_PROGRESS:
mGameAPIService.setAccomplishmentProgress(e.data);
break;
case SHOW_CUSTOM_TAB:
mGameAPIService.chatApiService.onCustomTabShown(e.data);
break;
case CUSTOM_TAB_MESSAGE:
mGameAPIService.chatApiService.onUserMessage(e.data);
break;
case SPAM_ROOM_JOINS:
mSpamService.spamRoomJoins(e.data);
break;
case "spam_toggle":
mSpamService.spamToggles(e.data);
break;
case LOAD_SHARED_CONTENT:
mGameAPIService.loadSharedContent(e.data);
break;
case SHARED_CONTENT_SAVE_COMPLETE:
mGameAPIService.sharedContentSaveComplete(e.data);
break;
default:
Log.info(((("Processing external message: " + e.type) + ", data: ") + e.data));
ExternalMessageDispatcher.getInstance().handleExternalMessage(e);
break;
};
event = new KongregateEvent(EVENT_JAVASCRIPT, e);
dispatchEvent(event);
//unresolved jump
var _slot1 = error;
Log.error(((("Error while processing javascript event [" + JSON.encode(e)) + "]: ") + _slot1.toString()));
}
private function alertLog():Array{
return (Log.getErrorReport());
}
public function initialize():void{
initializeExternalInterface();
initializeJabber();
initializeGameAPIService();
mJabberConnection.gameApi = mGameAPIService;
}
private function dispatchJavascriptEvent(e:KongregateEvent):void{
var e = e;
if (Log.isDebug()){
Log.spam(("Broadcasting Event to JS: " + e.type));
Log.spam({kongEvent:e.toObject()});
};
ExternalInterface.call(getJavascriptListenerName(), e.toObject());
//unresolved jump
var _slot1 = e;
Log.error(((("Error calling external interface function (" + getJavascriptListenerName()) + "): ") + _slot1.toString()));
}
private function initializeJabber():void{
var ip:String = getConfigValue("chat_ip");
var host:String = getConfigValue("chat_host");
var port:int = parseInt(getConfigValue("chat_port"));
var boshHost:String = getConfigValue("chat_bosh_host");
var boshPort:int = parseInt(getConfigValue("chat_bosh_port"));
var enableBosh:Boolean = (((getConfigValue("enable_bosh") == true)) || ((getConfigValue("enable_bosh") == "true")));
var enableCompression:Boolean = (((getConfigValue("enable_compression") == true)) || ((getConfigValue("enable_compression") == "true")));
mJabberConnection = new JabberConnection({ip:ip, host:host, port:port, enable_bosh:enableBosh, bosh_host:boshHost, bosh_port:boshPort, enable_compression:enableCompression});
mSpamService = new SpamService({ip:ip, host:host, port:port});
var i:int;
while (i < JABBER_EVENTS.length) {
mJabberConnection.addEventListener(JABBER_EVENTS[i], onKongregateEvent);
i++;
};
mJabberConnection.addEventListener(JabberEvent.DISCONNECT, onJabberDisconnect);
var signedUserVariables:Array = [getConfigValue("user_vars_sig"), getConfigValue("user_vars")];
var trollUsername:String = getObfuscatedCookie(TROLL_USERNAME);
if (trollUsername){
signedUserVariables.push({trollUsername:trollUsername});
};
var user:User = new User(getConfigValue("chat_username"), getConfigValue("chat_password"), signedUserVariables);
if (user.validateUserVariables(false)){
mJabberConnection.user = user;
mJabberConnection.connect();
} else {
Log.error("Unable to validate user variables!");
Log.error(("User vars: " + getConfigValue("user_vars")));
Log.error(("User vars sig: " + getConfigValue("user_vars_sig")));
};
}
public function shutdown():void{
var i:int;
if (mJabberConnection != null){
i = 0;
while (i < JABBER_EVENTS.length) {
mJabberConnection.removeEventListener(JABBER_EVENTS[i], onKongregateEvent);
i++;
};
mJabberConnection.destroy();
};
if (mGameAPIService != null){
i = 0;
while (i < GAME_API_EVENTS.length) {
mGameAPIService.removeEventListener(GAME_API_EVENTS[i], onKongregateEvent);
i++;
};
i = 0;
while (i < CHAT_API_EVENTS.length) {
mGameAPIService.chatApiService.removeEventListener(CHAT_API_EVENTS[i], onKongregateEvent);
i++;
};
mGameAPIService.destroy();
};
}
public function getConfigValue(name:String){
return (Configuration.getConfigValue(name));
}
public function get connection():JabberConnection{
return (mJabberConnection);
}
private function onJabberDisconnect(e:KongregateEvent):void{
if (e.data.banned){
setObfuscatedCookie(TROLL_USERNAME, mJabberConnection.user.username);
};
}
private function onKongregateEvent(e:KongregateEvent):void{
dispatchJavascriptEvent(e);
var event:KongregateEvent = new KongregateEvent(EVENT_JAVASCRIPT_DISPATCH, e.toObject());
dispatchEvent(event);
}
private function getCookie(settingName:String):Object{
var so:SharedObject;
var settingName = settingName;
so = SharedObject.getLocal("chatData");
return (so.data[settingName]);
//unresolved jump
var _slot1 = e;
Log.error(("Error getting cookie: " + _slot1.toString()));
return (null);
}
private function getJavascriptListenerName():String{
return (getConfigValue("javascript_listener"));
}
private function onJavascriptJSONEvent(json):void{
var event:Object;
var json = json;
if ((json is String)){
event = JSON.decode(json);
onJavascriptEvent(event);
//unresolved jump
var _slot1 = e;
Log.error(("Error while parsing JSON event from JS: " + _slot1.toString()));
} else {
Log.error(("Non string object passed into konduit: " + json));
};
}
private function setCookie(settingName:String, settingValue:Object):void{
var so:SharedObject;
var settingName = settingName;
var settingValue = settingValue;
so = SharedObject.getLocal("chatData");
so.data[settingName] = settingValue;
so.flush();
//unresolved jump
var _slot1 = e;
Log.error(("Error setting cookie: " + _slot1.toString()));
}
private function deleteCookie(settingName:String):void{
var so:SharedObject = SharedObject.getLocal("chatData");
delete so.data[settingName];
so.flush();
}
public function getConfig():Object{
return (Configuration.getConfig());
}
private function initializeGameAPIService():void{
if (mGameAPIService){
return;
};
mGameAPIService = new GameAPIService(mJabberConnection, getConfig());
var i:int;
while (i < GAME_API_EVENTS.length) {
mGameAPIService.addEventListener(GAME_API_EVENTS[i], onKongregateEvent);
i++;
};
i = 0;
while (i < CHAT_API_EVENTS.length) {
mGameAPIService.chatApiService.addEventListener(CHAT_API_EVENTS[i], onKongregateEvent);
i++;
};
}
private function initializeExternalInterface():void{
Security.allowDomain("*");
ExternalInterface.addCallback("dispatchJSONEvent", onJavascriptJSONEvent);
ExternalInterface.addCallback("alertLog", alertLog);
//unresolved jump
var _slot1 = e;
Log.error(("Unable to add external dispatchEvent function: " + _slot1.toString()));
}
}
}//package com.kongregate.as3
Section 68
//MD5 (com.meychi.ascrypt3.MD5)
package com.meychi.ascrypt3 {
public class MD5 {
public function MD5(){
super();
}
private static function md5_hh(a:Number, b:Number, c:Number, d:Number, x:Number, s:Number, t:Number):Number{
return (md5_cmn(((b ^ c) ^ d), a, b, x, s, t));
}
private static function md5_cmn(q:Number, a:Number, b:Number, x:Number, s:Number, t:Number):Number{
return (safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b));
}
private static function str2binl(str:String):Array{
var bin:Array = new Array();
var mask:Number = ((1 << 8) - 1);
var i:Number = 0;
while (i < (str.length * 8)) {
bin[(i >> 5)] = (bin[(i >> 5)] | ((str.charCodeAt((i / 8)) & mask) << (i % 32)));
i = (i + 8);
};
return (bin);
}
private static function md5_ff(a:Number, b:Number, c:Number, d:Number, x:Number, s:Number, t:Number):Number{
return (md5_cmn(((b & c) | (~(b) & d)), a, b, x, s, t));
}
public static function calculate(src:String):String{
return (hex_md5(src));
}
private static function binl2hex(binarray:Array):String{
var str:String = new String("");
var tab:String = new String("0123456789abcdef");
var i:Number = 0;
while (i < (binarray.length * 4)) {
str = (str + (tab.charAt(((binarray[(i >> 2)] >> (((i % 4) * 8) + 4)) & 15)) + tab.charAt(((binarray[(i >> 2)] >> ((i % 4) * 8)) & 15))));
i++;
};
return (str);
}
private static function safe_add(x:Number, y:Number):Number{
var lsw:Number = ((x & 0xFFFF) + (y & 0xFFFF));
var msw:Number = (((x >> 16) + (y >> 16)) + (lsw >> 16));
return (((msw << 16) | (lsw & 0xFFFF)));
}
private static function md5_gg(a:Number, b:Number, c:Number, d:Number, x:Number, s:Number, t:Number):Number{
return (md5_cmn(((b & d) | (c & ~(d))), a, b, x, s, t));
}
private static function md5_ii(a:Number, b:Number, c:Number, d:Number, x:Number, s:Number, t:Number):Number{
return (md5_cmn((c ^ (b | ~(d))), a, b, x, s, t));
}
private static function hex_md5(src:String):String{
return (binl2hex(core_md5(str2binl(src), (src.length * 8))));
}
private static function bit_rol(num:Number, cnt:Number):Number{
return (((num << cnt) | (num >>> (32 - cnt))));
}
private static function core_md5(x:Array, len:Number):Array{
var olda:Number;
var oldb:Number;
var oldc:Number;
var oldd:Number;
x[(len >> 5)] = (x[(len >> 5)] | (128 << (len % 32)));
x[((((len + 64) >>> 9) << 4) + 14)] = len;
var a:Number = 1732584193;
var b:Number = -271733879;
var c:Number = -1732584194;
var d:Number = 271733878;
var i:Number = 0;
while (i < x.length) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5_ff(a, b, c, d, x[(i + 0)], 7, -680876936);
d = md5_ff(d, a, b, c, x[(i + 1)], 12, -389564586);
c = md5_ff(c, d, a, b, x[(i + 2)], 17, 606105819);
b = md5_ff(b, c, d, a, x[(i + 3)], 22, -1044525330);
a = md5_ff(a, b, c, d, x[(i + 4)], 7, -176418897);
d = md5_ff(d, a, b, c, x[(i + 5)], 12, 1200080426);
c = md5_ff(c, d, a, b, x[(i + 6)], 17, -1473231341);
b = md5_ff(b, c, d, a, x[(i + 7)], 22, -45705983);
a = md5_ff(a, b, c, d, x[(i + 8)], 7, 1770035416);
d = md5_ff(d, a, b, c, x[(i + 9)], 12, -1958414417);
c = md5_ff(c, d, a, b, x[(i + 10)], 17, -42063);
b = md5_ff(b, c, d, a, x[(i + 11)], 22, -1990404162);
a = md5_ff(a, b, c, d, x[(i + 12)], 7, 1804603682);
d = md5_ff(d, a, b, c, x[(i + 13)], 12, -40341101);
c = md5_ff(c, d, a, b, x[(i + 14)], 17, -1502002290);
b = md5_ff(b, c, d, a, x[(i + 15)], 22, 1236535329);
a = md5_gg(a, b, c, d, x[(i + 1)], 5, -165796510);
d = md5_gg(d, a, b, c, x[(i + 6)], 9, -1069501632);
c = md5_gg(c, d, a, b, x[(i + 11)], 14, 643717713);
b = md5_gg(b, c, d, a, x[(i + 0)], 20, -373897302);
a = md5_gg(a, b, c, d, x[(i + 5)], 5, -701558691);
d = md5_gg(d, a, b, c, x[(i + 10)], 9, 38016083);
c = md5_gg(c, d, a, b, x[(i + 15)], 14, -660478335);
b = md5_gg(b, c, d, a, x[(i + 4)], 20, -405537848);
a = md5_gg(a, b, c, d, x[(i + 9)], 5, 568446438);
d = md5_gg(d, a, b, c, x[(i + 14)], 9, -1019803690);
c = md5_gg(c, d, a, b, x[(i + 3)], 14, -187363961);
b = md5_gg(b, c, d, a, x[(i + 8)], 20, 1163531501);
a = md5_gg(a, b, c, d, x[(i + 13)], 5, -1444681467);
d = md5_gg(d, a, b, c, x[(i + 2)], 9, -51403784);
c = md5_gg(c, d, a, b, x[(i + 7)], 14, 1735328473);
b = md5_gg(b, c, d, a, x[(i + 12)], 20, -1926607734);
a = md5_hh(a, b, c, d, x[(i + 5)], 4, -378558);
d = md5_hh(d, a, b, c, x[(i + 8)], 11, -2022574463);
c = md5_hh(c, d, a, b, x[(i + 11)], 16, 1839030562);
b = md5_hh(b, c, d, a, x[(i + 14)], 23, -35309556);
a = md5_hh(a, b, c, d, x[(i + 1)], 4, -1530992060);
d = md5_hh(d, a, b, c, x[(i + 4)], 11, 1272893353);
c = md5_hh(c, d, a, b, x[(i + 7)], 16, -155497632);
b = md5_hh(b, c, d, a, x[(i + 10)], 23, -1094730640);
a = md5_hh(a, b, c, d, x[(i + 13)], 4, 681279174);
d = md5_hh(d, a, b, c, x[(i + 0)], 11, -358537222);
c = md5_hh(c, d, a, b, x[(i + 3)], 16, -722521979);
b = md5_hh(b, c, d, a, x[(i + 6)], 23, 76029189);
a = md5_hh(a, b, c, d, x[(i + 9)], 4, -640364487);
d = md5_hh(d, a, b, c, x[(i + 12)], 11, -421815835);
c = md5_hh(c, d, a, b, x[(i + 15)], 16, 530742520);
b = md5_hh(b, c, d, a, x[(i + 2)], 23, -995338651);
a = md5_ii(a, b, c, d, x[(i + 0)], 6, -198630844);
d = md5_ii(d, a, b, c, x[(i + 7)], 10, 1126891415);
c = md5_ii(c, d, a, b, x[(i + 14)], 15, -1416354905);
b = md5_ii(b, c, d, a, x[(i + 5)], 21, -57434055);
a = md5_ii(a, b, c, d, x[(i + 12)], 6, 1700485571);
d = md5_ii(d, a, b, c, x[(i + 3)], 10, -1894986606);
c = md5_ii(c, d, a, b, x[(i + 10)], 15, -1051523);
b = md5_ii(b, c, d, a, x[(i + 1)], 21, -2054922799);
a = md5_ii(a, b, c, d, x[(i + 8)], 6, 1873313359);
d = md5_ii(d, a, b, c, x[(i + 15)], 10, -30611744);
c = md5_ii(c, d, a, b, x[(i + 6)], 15, -1560198380);
b = md5_ii(b, c, d, a, x[(i + 13)], 21, 1309151649);
a = md5_ii(a, b, c, d, x[(i + 4)], 6, -145523070);
d = md5_ii(d, a, b, c, x[(i + 11)], 10, -1120210379);
c = md5_ii(c, d, a, b, x[(i + 2)], 15, 718787259);
b = md5_ii(b, c, d, a, x[(i + 9)], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
i = (i + 16);
};
return (new Array(a, b, c, d));
}
}
}//package com.meychi.ascrypt3
Section 69
//Rijndael (com.meychi.ascrypt3.Rijndael)
package com.meychi.ascrypt3 {
public class Rijndael {
public var keySize:Number;// = 128
private var Nb:Number;
private var SBoxInverse:Array;
private var Nk:Number;
private var shiftOffsets:Array;
private var Nr:Number;
public var blockSize:Number;// = 128
private var roundsArray:Array;
private var Rcon:Array;
private var SBox:Array;
public function Rijndael(... _args){
Rcon = new Array(1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145);
SBox = new Array(99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 0xFF, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22);
SBoxInverse = new Array(82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 0xFF, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125);
super();
if ((((_args.length >= 0)) && (!(isNaN(_args[0]))))){
this.keySize = _args[0];
};
if ((((_args.length >= 1)) && (!(isNaN(_args[1]))))){
this.blockSize = _args[1];
};
this.roundsArray = [0, 0, 0, 0, [0, 0, 0, 0, 10, 0, 12, 0, 14], 0, [0, 0, 0, 0, 12, 0, 12, 0, 14], 0, [0, 0, 0, 0, 14, 0, 14, 0, 14]];
this.shiftOffsets = [0, 0, 0, 0, [0, 1, 2, 3], 0, [0, 1, 2, 3], 0, [0, 1, 3, 4]];
this.Nb = (blockSize / 32);
this.Nk = (keySize / 32);
this.Nr = this.roundsArray[this.Nk][this.Nb];
}
private function encryption(block:Array, expandedKey:Array):Array{
block = this.packBytes(block);
this.addRoundKey(block, expandedKey);
var i:Number = 1;
while (i < Nr) {
this.Round(block, expandedKey.slice((this.Nb * i), (this.Nb * (i + 1))));
i++;
};
this.FinalRound(block, expandedKey.slice((this.Nb * this.Nr)));
return (this.unpackBytes(block));
}
private function xtime(poly:Number):Number{
poly = (poly << 1);
return (((poly & 0x0100)) ? (poly ^ 283) : poly);
}
private function charsToHex(chars:Array):String{
var result:String = new String("");
var hexes:Array = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
var i:Number = 0;
while (i < chars.length) {
result = (result + (hexes[(chars[i] >> 4)] + hexes[(chars[i] & 15)]));
i++;
};
return (result);
}
private function InverseFinalRound(state:Array, roundKey:Array):void{
this.addRoundKey(state, roundKey);
this.shiftRow(state, "decrypt");
this.byteSub(state, "decrypt");
}
private function mult_GF256(x:Number, y:Number):Number{
var result:Number = 0;
var bit:Number = 1;
while (bit < 0x0100) {
if ((x & bit)){
result = (result ^ y);
};
bit = (bit * 2);
y = xtime(y);
};
return (result);
}
public function decrypt(src:String, key:String, mode:String):String{
var i:Number;
var pt:Array = new Array();
var aBlock:Array = new Array();
var chars:Array = hexToChars(src);
var bpb:Number = (this.blockSize / 8);
var expandedKey:Array = this.keyExpansion(strToChars(key));
var block:Number = ((chars.length / bpb) - 1);
while (block > 0) {
aBlock = decryption(chars.slice((block * bpb), ((block + 1) * bpb)), expandedKey);
if (mode == "CBC"){
i = 0;
while (i < bpb) {
pt[(((block - 1) * bpb) + i)] = (aBlock[i] ^ chars[(((block - 1) * bpb) + i)]);
i++;
};
} else {
pt = aBlock.concat(pt);
};
block--;
};
if (mode == "ECB"){
pt = this.decryption(chars.slice(0, bpb), expandedKey).concat(pt);
};
return (charsToStr(pt));
}
private function hexToChars(hex:String):Array{
var codes:Array = new Array();
var i:Number = ((hex.substr(0, 2))=="0x") ? 2 : 0;
while (i < hex.length) {
codes.push(parseInt(hex.substr(i, 2), 16));
i = (i + 2);
};
return (codes);
}
private function formatPlaintext(plaintext:Array):Array{
var bpb:Number = (blockSize / 8);
var i:Number = (bpb - (plaintext.length % bpb));
while ((((i > 0)) && ((i < bpb)))) {
plaintext[plaintext.length] = 0;
i--;
};
return (plaintext);
}
private function shiftRow(state:Array, dir:String):void{
var i:Number = 1;
while (i < 4) {
if (dir == "encrypt"){
state[i] = this.cyclicShiftLeft(state[i], this.shiftOffsets[Nb][i]);
} else {
state[i] = this.cyclicShiftLeft(state[i], (this.Nb - this.shiftOffsets[Nb][i]));
};
i++;
};
}
private function FinalRound(state:Array, roundKey:Array):void{
this.byteSub(state, "encrypt");
this.shiftRow(state, "encrypt");
this.addRoundKey(state, roundKey);
}
private function strToChars(str:String):Array{
var codes:Array = new Array();
var i:Number = 0;
while (i < str.length) {
codes.push(str.charCodeAt(i));
i++;
};
return (codes);
}
private function mixColumn(state:Array, dir:String):void{
var i:Number;
var j:Number;
var b:Array = new Array();
j = 0;
while (j < this.Nb) {
i = 0;
while (i < 4) {
if (dir == "encrypt"){
b[i] = (((this.mult_GF256(state[i][j], 2) ^ this.mult_GF256(state[((i + 1) % 4)][j], 3)) ^ state[((i + 2) % 4)][j]) ^ state[((i + 3) % 4)][j]);
} else {
b[i] = (((this.mult_GF256(state[i][j], 14) ^ this.mult_GF256(state[((i + 1) % 4)][j], 11)) ^ this.mult_GF256(state[((i + 2) % 4)][j], 13)) ^ this.mult_GF256(state[((i + 3) % 4)][j], 9));
};
i++;
};
i = 0;
while (i < 4) {
state[i][j] = b[i];
i++;
};
j++;
};
}
private function decryption(block:Array, expandedKey:Array):Array{
block = this.packBytes(block);
this.InverseFinalRound(block, expandedKey.slice((this.Nb * this.Nr)));
var i:Number = (Nr - 1);
while (i > 0) {
this.InverseRound(block, expandedKey.slice((this.Nb * i), (this.Nb * (i + 1))));
i--;
};
this.addRoundKey(block, expandedKey);
return (this.unpackBytes(block));
}
private function byteSub(state:Array, dir:String):void{
var j:Number;
var S:Array = new Array();
if (dir == "encrypt"){
S = this.SBox;
} else {
S = this.SBoxInverse;
};
var i:Number = 0;
while (i < 4) {
j = 0;
while (j < this.Nb) {
state[i][j] = S[state[i][j]];
j++;
};
i++;
};
}
private function packBytes(octets:Array):Array{
var state:Array = new Array();
state[0] = new Array();
state[1] = new Array();
state[2] = new Array();
state[3] = new Array();
var j:Number = 0;
while (j < octets.length) {
state[0][(j / 4)] = octets[j];
state[1][(j / 4)] = octets[(j + 1)];
state[2][(j / 4)] = octets[(j + 2)];
state[3][(j / 4)] = octets[(j + 3)];
j = (j + 4);
};
return (state);
}
public function encrypt(src:String, key:String, mode:String):String{
var i:Number;
var ct:Array = new Array();
var aBlock:Array = new Array();
var bpb:Number = (this.blockSize / 8);
if (mode == "CBC"){
ct = this.getRandomBytes(bpb);
};
var chars:Array = this.formatPlaintext(strToChars(src));
var expandedKey:Array = this.keyExpansion(strToChars(key));
var block:Number = 0;
while (block < (chars.length / bpb)) {
aBlock = chars.slice((block * bpb), ((block + 1) * bpb));
if (mode == "CBC"){
i = 0;
while (i < bpb) {
aBlock[i] = (aBlock[i] ^ ct[((block * bpb) + i)]);
i++;
};
};
ct = ct.concat(this.encryption(aBlock, expandedKey));
block++;
};
return (charsToHex(ct));
}
private function keyExpansion(key:Array):Array{
var j:Number;
var temp:Number = 0;
this.Nk = (this.keySize / 32);
this.Nb = (this.blockSize / 32);
var expandedKey:Array = new Array();
this.Nr = this.roundsArray[this.Nk][this.Nb];
j = 0;
while (j < this.Nk) {
expandedKey[j] = (((key[(4 * j)] | (key[((4 * j) + 1)] << 8)) | (key[((4 * j) + 2)] << 16)) | (key[((4 * j) + 3)] << 24));
j++;
};
j = this.Nk;
while (j < (this.Nb * (this.Nr + 1))) {
temp = expandedKey[(j - 1)];
if ((j % this.Nk) == 0){
temp = ((((this.SBox[((temp >> 8) & 0xFF)] | (this.SBox[((temp >> 16) & 0xFF)] << 8)) | (this.SBox[((temp >> 24) & 0xFF)] << 16)) | (this.SBox[(temp & 0xFF)] << 24)) ^ this.Rcon[(Math.floor((j / this.Nk)) - 1)]);
} else {
if ((((this.Nk > 6)) && (((j % this.Nk) == 4)))){
temp = ((((this.SBox[((temp >> 24) & 0xFF)] << 24) | (this.SBox[((temp >> 16) & 0xFF)] << 16)) | (this.SBox[((temp >> 8) & 0xFF)] << 8)) | this.SBox[(temp & 0xFF)]);
};
};
expandedKey[j] = (expandedKey[(j - this.Nk)] ^ temp);
j++;
};
return (expandedKey);
}
private function InverseRound(state:Array, roundKey:Array):void{
this.addRoundKey(state, roundKey);
this.mixColumn(state, "decrypt");
this.shiftRow(state, "decrypt");
this.byteSub(state, "decrypt");
}
private function cyclicShiftLeft(src:Array, pos:Number):Array{
var temp:Array = src.slice(0, pos);
src = src.slice(pos).concat(temp);
return (src);
}
private function unpackBytes(packed:Array):Array{
var result:Array = new Array();
var j:Number = 0;
while (j < packed[0].length) {
result[result.length] = packed[0][j];
result[result.length] = packed[1][j];
result[result.length] = packed[2][j];
result[result.length] = packed[3][j];
j++;
};
return (result);
}
private function addRoundKey(state:Array, roundKey:Array):void{
var j:Number = 0;
while (j < this.Nb) {
state[0][j] = (state[0][j] ^ (roundKey[j] & 0xFF));
state[1][j] = (state[1][j] ^ ((roundKey[j] >> 8) & 0xFF));
state[2][j] = (state[2][j] ^ ((roundKey[j] >> 16) & 0xFF));
state[3][j] = (state[3][j] ^ ((roundKey[j] >> 24) & 0xFF));
j++;
};
}
private function Round(state:Array, roundKey:Array):void{
this.byteSub(state, "encrypt");
this.shiftRow(state, "encrypt");
this.mixColumn(state, "encrypt");
this.addRoundKey(state, roundKey);
}
private function getRandomBytes(howMany:Number):Array{
var bytes:Array = new Array();
var i:Number = 0;
while (i < howMany) {
bytes[i] = Math.round((Math.random() * 0xFF));
i++;
};
return (bytes);
}
private function charsToStr(chars:Array):String{
var result:String = new String("");
var i:Number = 0;
while (i < chars.length) {
result = (result + String.fromCharCode(chars[i]));
i++;
};
return (result);
}
}
}//package com.meychi.ascrypt3
Section 70
//Adler32 (com.wirelust.as3zlib.Adler32)
package com.wirelust.as3zlib {
import flash.utils.*;
public final class Adler32 {
private static var BASE:int = 65521;
private static var NMAX:int = 5552;
public function Adler32(){
super();
}
public function adler32(adler:Number, buf:ByteArray, index:int, len:int):Number{
var k:int;
if (buf == null){
return (1);
};
var s1:Number = (adler & 0xFFFF);
var s2:Number = ((adler >> 16) & 0xFFFF);
while (len > 0) {
k = ((len < NMAX)) ? len : NMAX;
len = (len - k);
while (k >= 16) {
var _temp1 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp1] & 0xFF));
s2 = (s2 + s1);
var _temp2 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp2] & 0xFF));
s2 = (s2 + s1);
var _temp3 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp3] & 0xFF));
s2 = (s2 + s1);
var _temp4 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp4] & 0xFF));
s2 = (s2 + s1);
var _temp5 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp5] & 0xFF));
s2 = (s2 + s1);
var _temp6 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp6] & 0xFF));
s2 = (s2 + s1);
var _temp7 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp7] & 0xFF));
s2 = (s2 + s1);
var _temp8 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp8] & 0xFF));
s2 = (s2 + s1);
var _temp9 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp9] & 0xFF));
s2 = (s2 + s1);
var _temp10 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp10] & 0xFF));
s2 = (s2 + s1);
var _temp11 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp11] & 0xFF));
s2 = (s2 + s1);
var _temp12 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp12] & 0xFF));
s2 = (s2 + s1);
var _temp13 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp13] & 0xFF));
s2 = (s2 + s1);
var _temp14 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp14] & 0xFF));
s2 = (s2 + s1);
var _temp15 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp15] & 0xFF));
s2 = (s2 + s1);
var _temp16 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp16] & 0xFF));
s2 = (s2 + s1);
k = (k - 16);
};
if (k != 0){
do {
var _temp17 = index;
index = (index + 1);
s1 = (s1 + (buf[_temp17] & 0xFF));
s2 = (s2 + s1);
--k;
} while (k != 0);
};
s1 = (s1 % BASE);
s2 = (s2 % BASE);
};
return (((s2 << 16) | s1));
}
}
}//package com.wirelust.as3zlib
Section 71
//Deflate (com.wirelust.as3zlib.Deflate)
package com.wirelust.as3zlib {
import flash.utils.*;
import com.wirelust.util.*;
public class Deflate {
var bi_valid:int;
public var hash_shift:int;
public var last_flush:int;
public var max_chain_length:int;
var l_buf:int;
var d_buf:int;
public var block_start:int;
public var prev:Array;
var matches:int;
var heap_len:int;
var lit_bufsize:int;
public var ins_h:int;
public var strm:ZStream;
private var z_errmsg:Array;
public var nice_match:int;
var bl_desc:Tree;
public var match_start:int;
var last_lit:int;
public var prev_length:int;
var bl_tree:Array;
public var strategy:int;
var bi_buf:Number;
public var hash_mask:int;
public var lookahead:int;
public var level:int;
var opt_len:int;
var l_desc:Tree;
var d_desc:Tree;
public var noheader:int;
var heap_max:int;
public var hash_bits:int;
public var hash_size:int;
public var pending:int;
public var match_length:int;
public var pending_out:int;
var last_eob_len:int;
public var data_type:uint;
public var w_mask:int;
public var prev_match:int;
var dyn_dtree:Array;
public var good_match:int;
var dyn_ltree:Array;
var depth:Array;
public var pending_buf:ByteArray;
public var w_bits:int;
public var match_available:int;
public var w_size:int;
public var strstart:int;
var static_len:int;
var bl_count:Array;
public var head:Array;
public var method:uint;
var heap:Array;
public var window:ByteArray;
public var status:int;
public var pending_buf_size:int;
public var window_size:int;
public var max_lazy_match:int;
private static const DYN_TREES:int = 2;
private static const Z_ASCII:int = 1;
private static const PRESET_DICT:int = 32;
private static const Z_FINISH:int = 4;
private static const Z_NEED_DICT:int = 2;
private static const Z_DEFAULT_STRATEGY:int = 0;
private static const MAX_BITS:int = 15;
private static const Z_DATA_ERROR:int = -3;
private static const REPZ_3_10:int = 17;
private static const Z_STREAM_ERROR:int = -2;
private static const Z_NO_FLUSH:int = 0;
private static const Z_FULL_FLUSH:int = 3;
private static const Z_MEM_ERROR:int = -4;
private static const Z_SYNC_FLUSH:int = 2;
private static const D_CODES:int = 30;
private static const Z_UNKNOWN:int = 2;
private static const FinishStarted:int = 2;
private static const L_CODES:int = 286;
private static const Z_BUF_ERROR:int = -5;
private static const MIN_MATCH:int = 3;
private static const Z_FILTERED:int = 1;
private static const Z_PARTIAL_FLUSH:int = 1;
private static const STATIC_TREES:int = 1;
private static const REP_3_6:int = 16;
private static const LENGTH_CODES:int = 29;
private static const Buf_size:int = 16;
private static const HEAP_SIZE:int = 573;
private static const Z_VERSION_ERROR:int = -6;
private static const Z_STREAM_END:int = 1;
private static const INIT_STATE:int = 42;
private static const Z_BINARY:int = 0;
private static const MIN_LOOKAHEAD:int = 262;
private static const Z_ERRNO:int = -1;
private static const LITERALS:int = 0x0100;
private static const BUSY_STATE:int = 113;
private static const REPZ_11_138:int = 18;
private static const FINISH_STATE:int = 666;
private static const STORED_BLOCK:int = 0;
private static const FinishDone:int = 3;
private static const BL_CODES:int = 19;
private static const Z_OK:int = 0;
private static const Z_HUFFMAN_ONLY:int = 2;
private static const MAX_MATCH:int = 258;
private static const END_BLOCK:int = 0x0100;
private static var SLOW:int = 2;
private static var MAX_MEM_LEVEL:int = 9;
private static var MAX_WBITS:int = 15;
private static var NeedMore:int = 0;
private static var FAST:int = 1;
private static var DEF_MEM_LEVEL:int = 8;
private static var BlockDone:int = 1;
private static var config_table:Array = new Array(new DeflateConfig(0, 0, 0, 0, STORED), new DeflateConfig(4, 4, 8, 4, FAST), new DeflateConfig(4, 5, 16, 8, FAST), new DeflateConfig(4, 6, 32, 32, FAST), new DeflateConfig(4, 4, 16, 16, SLOW), new DeflateConfig(8, 16, 32, 32, SLOW), new DeflateConfig(8, 16, 128, 128, SLOW), new DeflateConfig(8, 32, 128, 0x0100, SLOW), new DeflateConfig(32, 128, 258, 0x0400, SLOW), new DeflateConfig(32, 258, 258, 0x1000, SLOW));
private static var STORED:int = 0;
private static var Z_DEFAULT_COMPRESSION:int = -1;
private static var Z_DEFLATED:int = 8;
public function Deflate():void{
z_errmsg = new Array("need dictionary", "stream end", "", "file error", "stream error", "data error", "insufficient memory", "buffer error", "incompatible version", "");
l_desc = new Tree();
d_desc = new Tree();
bl_desc = new Tree();
bl_count = new Array();
heap = new Array();
depth = new Array();
super();
dyn_ltree = new Array();
dyn_dtree = new Array();
bl_tree = new Array();
}
public function bi_flush():void{
if (bi_valid == 16){
put_short(bi_buf);
bi_buf = 0;
bi_valid = 0;
} else {
if (bi_valid >= 8){
this.put_byte_withInt(bi_buf);
bi_buf = (bi_buf >>> 8);
bi_valid = (bi_valid - 8);
};
};
}
public function send_tree(tree:Array, max_code:int):void{
var n:int;
var curlen:int;
var prevlen = -1;
var nextlen:int = tree[((0 * 2) + 1)];
var count:int;
var max_count = 7;
var min_count = 4;
if (nextlen == 0){
max_count = 138;
min_count = 3;
};
n = 0;
for (;n <= max_code;n++) {
curlen = nextlen;
nextlen = tree[(((n + 1) * 2) + 1)];
++count;
if ((((count < max_count)) && ((curlen == nextlen)))){
continue;
} else {
if (count < min_count){
do {
send_code(curlen, bl_tree);
--count;
} while (count != 0);
} else {
if (curlen != 0){
if (curlen != prevlen){
send_code(curlen, bl_tree);
count--;
};
send_code(REP_3_6, bl_tree);
send_bits((count - 3), 2);
} else {
if (count <= 10){
send_code(REPZ_3_10, bl_tree);
send_bits((count - 3), 3);
} else {
send_code(REPZ_11_138, bl_tree);
send_bits((count - 11), 7);
};
};
};
};
count = 0;
prevlen = curlen;
if (nextlen == 0){
max_count = 138;
min_count = 3;
} else {
if (curlen == nextlen){
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
};
};
};
}
function lm_init():void{
window_size = (2 * w_size);
head[(hash_size - 1)] = 0;
var i:int;
while (i < (hash_size - 1)) {
head[i] = 0;
i++;
};
max_lazy_match = Deflate.config_table[level].max_lazy;
good_match = Deflate.config_table[level].good_length;
nice_match = Deflate.config_table[level].nice_length;
max_chain_length = Deflate.config_table[level].max_chain;
strstart = 0;
block_start = 0;
lookahead = 0;
match_length = (prev_length = (MIN_MATCH - 1));
match_available = 0;
ins_h = 0;
}
function set_data_type():void{
var n:int;
var ascii_freq:int;
var bin_freq:int;
while (n < 7) {
bin_freq = (bin_freq + dyn_ltree[(n * 2)]);
n++;
};
while (n < 128) {
ascii_freq = (ascii_freq + dyn_ltree[(n * 2)]);
n++;
};
while (n < LITERALS) {
bin_freq = (bin_freq + dyn_ltree[(n * 2)]);
n++;
};
data_type = ((bin_freq > (ascii_freq >>> 2))) ? Z_BINARY : Z_ASCII;
}
public function deflate(strm:ZStream, flush:int):int{
var old_flush:int;
var header:int;
var level_flags:int;
var bstate:int;
var i:int;
if ((((flush > Z_FINISH)) || ((flush < 0)))){
return (Z_STREAM_ERROR);
};
if ((((((strm.next_out == null)) || ((((strm.next_in == null)) && (!((strm.avail_in == 0))))))) || ((((status == FINISH_STATE)) && (!((flush == Z_FINISH))))))){
strm.msg = z_errmsg[(Z_NEED_DICT - Z_STREAM_ERROR)];
return (Z_STREAM_ERROR);
};
if (strm.avail_out == 0){
strm.msg = z_errmsg[(Z_NEED_DICT - Z_BUF_ERROR)];
return (Z_BUF_ERROR);
};
this.strm = strm;
old_flush = last_flush;
last_flush = flush;
if (status == INIT_STATE){
header = ((Z_DEFLATED + ((w_bits - 8) << 4)) << 8);
level_flags = (((level - 1) & 0xFF) >> 1);
if (level_flags > 3){
level_flags = 3;
};
header = (header | (level_flags << 6));
if (strstart != 0){
header = (header | PRESET_DICT);
};
header = (header + (31 - (header % 31)));
status = BUSY_STATE;
putShortMSB(header);
if (strstart != 0){
putShortMSB(int((strm.adler >>> 16)));
putShortMSB(int((strm.adler & 0xFFFF)));
};
strm.adler = strm._adler.adler32(0, null, 0, 0);
};
if (pending != 0){
strm.flush_pending();
if (strm.avail_out == 0){
last_flush = -1;
return (Z_OK);
};
} else {
if ((((((strm.avail_in == 0)) && ((flush <= old_flush)))) && (!((flush == Z_FINISH))))){
strm.msg = z_errmsg[(Z_NEED_DICT - Z_BUF_ERROR)];
return (Z_BUF_ERROR);
};
};
if ((((status == FINISH_STATE)) && (!((strm.avail_in == 0))))){
strm.msg = z_errmsg[(Z_NEED_DICT - Z_BUF_ERROR)];
return (Z_BUF_ERROR);
};
if (((((!((strm.avail_in == 0))) || (!((lookahead == 0))))) || (((!((flush == Z_NO_FLUSH))) && (!((status == FINISH_STATE))))))){
bstate = -1;
switch (config_table[level].func){
case STORED:
bstate = deflate_stored(flush);
break;
case FAST:
bstate = deflate_fast(flush);
break;
case SLOW:
bstate = deflate_slow(flush);
break;
};
if ((((bstate == FinishStarted)) || ((bstate == FinishDone)))){
status = FINISH_STATE;
};
if ((((bstate == NeedMore)) || ((bstate == FinishStarted)))){
if (strm.avail_out == 0){
last_flush = -1;
};
return (Z_OK);
};
if (bstate == BlockDone){
if (flush == Z_PARTIAL_FLUSH){
_tr_align();
} else {
_tr_stored_block(0, 0, false);
if (flush == Z_FULL_FLUSH){
i = 0;
while (i < hash_size) {
head[i] = 0;
i++;
};
};
};
strm.flush_pending();
if (strm.avail_out == 0){
last_flush = -1;
return (Z_OK);
};
};
};
if (flush != Z_FINISH){
return (Z_OK);
};
if (noheader != 0){
return (Z_STREAM_END);
};
putShortMSB(int((strm.adler >>> 16)));
putShortMSB(int((strm.adler & 0xFFFF)));
strm.flush_pending();
noheader = -1;
return (((pending)!=0) ? Z_OK : Z_STREAM_END);
}
function fill_window():void{
var n:int;
var m:int;
var p:int;
var more:int;
do {
more = ((window_size - lookahead) - strstart);
if ((((((more == 0)) && ((strstart == 0)))) && ((lookahead == 0)))){
more = w_size;
} else {
if (more == -1){
more--;
} else {
if (strstart >= ((w_size + w_size) - MIN_LOOKAHEAD)){
System.byteArrayCopy(window, w_size, window, 0, w_size);
match_start = (match_start - w_size);
strstart = (strstart - w_size);
block_start = (block_start - w_size);
n = hash_size;
p = n;
do {
--p;
m = (head[p] & 0xFFFF);
head[p] = ((m >= w_size)) ? Cast.toShort((m - w_size)) : 0;
--n;
} while (n != 0);
n = w_size;
p = n;
do {
--p;
m = (prev[p] & 0xFFFF);
prev[p] = ((m >= w_size)) ? Cast.toShort((m - w_size)) : 0;
--n;
} while (n != 0);
more = (more + w_size);
};
};
};
if (strm.avail_in == 0){
return;
};
n = strm.read_buf(window, (strstart + lookahead), more);
lookahead = (lookahead + n);
if (lookahead >= MIN_MATCH){
ins_h = (window[strstart] & 0xFF);
ins_h = (((ins_h << hash_shift) ^ (window[(strstart + 1)] & 0xFF)) & hash_mask);
};
} while ((((lookahead < MIN_LOOKAHEAD)) && (!((strm.avail_in == 0)))));
}
function deflateSetDictionary(strm:ZStream, dictionary:ByteArray, dictLength:int):int{
var length:int = dictLength;
var index:int;
if ((((dictionary == null)) || (!((status == INIT_STATE))))){
return (Z_STREAM_ERROR);
};
strm.adler = strm._adler.adler32(strm.adler, dictionary, 0, dictLength);
if (length < MIN_MATCH){
return (Z_OK);
};
if (length > (w_size - MIN_LOOKAHEAD)){
length = (w_size - MIN_LOOKAHEAD);
index = (dictLength - length);
};
System.byteArrayCopy(dictionary, index, window, 0, length);
strstart = length;
block_start = length;
ins_h = (window[0] & 0xFF);
ins_h = (((ins_h << hash_shift) ^ (window[1] & 0xFF)) & hash_mask);
var n:int;
while (n <= (length - MIN_MATCH)) {
ins_h = (((ins_h << hash_shift) ^ (window[(n + (MIN_MATCH - 1))] & 0xFF)) & hash_mask);
prev[(n & w_mask)] = head[ins_h];
head[ins_h] = Cast.toShort(n);
n++;
};
return (Z_OK);
}
function scan_tree(tree:Array, max_code:int):void{
var n:int;
var curlen:int;
var prevlen = -1;
var nextlen:int = tree[((0 * 2) + 1)];
var count:int;
var max_count = 7;
var min_count = 4;
if (nextlen == 0){
max_count = 138;
min_count = 3;
};
tree[(((max_code + 1) * 2) + 1)] = 0xFFFF;
n = 0;
for (;n <= max_code;n++) {
curlen = nextlen;
nextlen = tree[(((n + 1) * 2) + 1)];
++count;
if ((((count < max_count)) && ((curlen == nextlen)))){
continue;
} else {
if (count < min_count){
bl_tree[(curlen * 2)] = (bl_tree[(curlen * 2)] + count);
} else {
if (curlen != 0){
if (curlen != prevlen){
var _local10 = bl_tree;
var _local11 = (curlen * 2);
var _local12 = (_local10[_local11] + 1);
_local10[_local11] = _local12;
};
_local10 = bl_tree;
_local11 = (REP_3_6 * 2);
_local12 = (_local10[_local11] + 1);
_local10[_local11] = _local12;
} else {
if (count <= 10){
_local10 = bl_tree;
_local11 = (REPZ_3_10 * 2);
_local12 = (_local10[_local11] + 1);
_local10[_local11] = _local12;
} else {
_local10 = bl_tree;
_local11 = (REPZ_11_138 * 2);
_local12 = (_local10[_local11] + 1);
_local10[_local11] = _local12;
};
};
};
};
count = 0;
prevlen = curlen;
if (nextlen == 0){
max_count = 138;
min_count = 3;
} else {
if (curlen == nextlen){
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
};
};
};
}
function tr_init():void{
l_desc.dyn_tree = dyn_ltree;
l_desc.stat_desc = StaticTree.static_l_desc;
d_desc.dyn_tree = dyn_dtree;
d_desc.stat_desc = StaticTree.static_d_desc;
bl_desc.dyn_tree = bl_tree;
bl_desc.stat_desc = StaticTree.static_bl_desc;
bi_buf = 0;
bi_valid = 0;
last_eob_len = 8;
init_block();
}
final public function put_byte(p:ByteArray, start:int, len:int):void{
System.byteArrayCopy(p, start, pending_buf, pending, len);
pending = (pending + len);
}
function flush_block_only(eof:Boolean):void{
_tr_flush_block(((block_start >= 0)) ? block_start : -1, (strstart - block_start), eof);
block_start = strstart;
strm.flush_pending();
}
function copy_block(buf:int, len:int, header:Boolean):void{
var index:int;
bi_windup();
last_eob_len = 8;
if (header){
put_short(len);
put_short((~(len) & 0xFFFF));
};
put_byte(window, buf, len);
}
final public function send_code(c:int, tree:Array):void{
var c2:int = (c * 2);
send_bits((tree[c2] & 0xFFFF), (tree[(c2 + 1)] & 0xFFFF));
}
public function deflate_stored(flush:int):int{
var max_start:int;
var max_block_size:int;
if (max_block_size > (pending_buf_size - 5)){
max_block_size = (pending_buf_size - 5);
};
while (true) {
if (lookahead <= 1){
fill_window();
if ((((lookahead == 0)) && ((flush == Z_NO_FLUSH)))){
return (NeedMore);
};
if (lookahead == 0){
break;
};
};
strstart = (strstart + lookahead);
lookahead = 0;
max_start = (block_start + max_block_size);
if ((((strstart == 0)) || ((strstart >= max_start)))){
lookahead = int((strstart - max_start));
strstart = int(max_start);
flush_block_only(false);
if (strm.avail_out == 0){
return (NeedMore);
};
};
if ((strstart - block_start) >= (w_size - MIN_LOOKAHEAD)){
flush_block_only(false);
if (strm.avail_out == 0){
return (NeedMore);
};
};
};
flush_block_only((flush == Z_FINISH));
if (strm.avail_out == 0){
return (((flush)==Z_FINISH) ? FinishStarted : NeedMore);
};
return (((flush == Z_FINISH)) ? FinishDone : BlockDone);
}
public function put_byte_withInt(c:int):void{
pending_buf.writeByte(c);
pending++;
}
public function put_short(w:int):void{
this.put_byte_withInt(w);
this.put_byte_withInt((w >>> 8));
}
public function send_bits(value:int, length:int):void{
var val:int;
var len:int = length;
if (bi_valid > (int(Buf_size) - len)){
val = value;
bi_buf = (bi_buf | ((val << bi_valid) & 0xFFFF));
put_short(bi_buf);
bi_buf = (val >>> (Buf_size - bi_valid));
bi_buf = Cast.toShort((val >>> (Buf_size - bi_valid)));
bi_valid = (bi_valid + (len - Buf_size));
} else {
bi_buf = (bi_buf | ((value << bi_valid) & 0xFFFF));
bi_valid = (bi_valid + len);
};
}
public function _tr_align():void{
send_bits((STATIC_TREES << 1), 3);
send_code(END_BLOCK, StaticTree.static_ltree);
bi_flush();
if ((((1 + last_eob_len) + 10) - bi_valid) < 9){
send_bits((STATIC_TREES << 1), 3);
send_code(END_BLOCK, StaticTree.static_ltree);
bi_flush();
};
last_eob_len = 7;
}
public function compress_block(ltree:Array, dtree:Array):void{
var dist:int;
var lc:int;
var code:int;
var extra:int;
var lx:int;
if (last_lit != 0){
do {
dist = (((pending_buf[(d_buf + (lx * 2))] << 8) & 0xFF00) | (pending_buf[((d_buf + (lx * 2)) + 1)] & 0xFF));
lc = (pending_buf[(l_buf + lx)] & 0xFF);
lx++;
if (dist == 0){
send_code(lc, ltree);
} else {
code = Tree._length_code[lc];
send_code(((code + LITERALS) + 1), ltree);
extra = Tree.extra_lbits[code];
if (extra != 0){
lc = (lc - Tree.base_length[code]);
send_bits(lc, extra);
};
dist--;
code = Tree.d_code(dist);
send_code(code, dtree);
extra = Tree.extra_dbits[code];
if (extra != 0){
dist = (dist - Tree.base_dist[code]);
send_bits(dist, extra);
};
};
} while (lx < last_lit);
};
send_code(END_BLOCK, ltree);
last_eob_len = ltree[((END_BLOCK * 2) + 1)];
}
function _tr_flush_block(buf:int, stored_len:int, eof:Boolean):void{
var opt_lenb:int;
var static_lenb:int;
var max_blindex:int;
if (level > 0){
if (data_type == Z_UNKNOWN){
set_data_type();
};
l_desc.build_tree(this);
d_desc.build_tree(this);
max_blindex = build_bl_tree();
opt_lenb = (((opt_len + 3) + 7) >>> 3);
static_lenb = (((static_len + 3) + 7) >>> 3);
if (static_lenb <= opt_lenb){
opt_lenb = static_lenb;
};
} else {
static_lenb = (stored_len + 5);
opt_lenb = static_lenb;
};
if (((((stored_len + 4) <= opt_lenb)) && (!((buf == -1))))){
_tr_stored_block(buf, stored_len, eof);
} else {
if (static_lenb == opt_lenb){
send_bits(((STATIC_TREES << 1) + (eof) ? 1 : 0), 3);
compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
} else {
send_bits(((DYN_TREES << 1) + (eof) ? 1 : 0), 3);
send_all_trees((l_desc.max_code + 1), (d_desc.max_code + 1), (max_blindex + 1));
compress_block(dyn_ltree, dyn_dtree);
};
};
init_block();
if (eof){
bi_windup();
};
}
public function send_all_trees(lcodes:int, dcodes:int, blcodes:int):void{
var rank:int;
send_bits((lcodes - 0x0101), 5);
send_bits((dcodes - 1), 5);
send_bits((blcodes - 4), 4);
rank = 0;
while (rank < blcodes) {
send_bits(bl_tree[((Tree.bl_order[rank] * 2) + 1)], 3);
rank++;
};
send_tree(dyn_ltree, (lcodes - 1));
send_tree(dyn_dtree, (dcodes - 1));
}
public function deflate_slow(flush:int):int{
var bflush:Boolean;
var max_insert:int;
var hash_head:int;
while (true) {
if (lookahead < MIN_LOOKAHEAD){
fill_window();
if ((((lookahead < MIN_LOOKAHEAD)) && ((flush == Z_NO_FLUSH)))){
return (NeedMore);
};
if (lookahead == 0){
break;
};
};
if (lookahead >= MIN_MATCH){
ins_h = (((ins_h << hash_shift) ^ (window[(strstart + (MIN_MATCH - 1))] & 0xFF)) & hash_mask);
hash_head = (head[ins_h] & 0xFFFF);
prev[(strstart & w_mask)] = head[ins_h];
head[ins_h] = Cast.toShort(strstart);
};
prev_length = match_length;
prev_match = match_start;
match_length = (MIN_MATCH - 1);
if (((((!((hash_head == 0))) && ((prev_length < max_lazy_match)))) && ((((strstart - hash_head) & 0xFFFF) <= (w_size - MIN_LOOKAHEAD))))){
if (strategy != Z_HUFFMAN_ONLY){
match_length = longest_match(hash_head);
};
if ((((match_length <= 5)) && ((((strategy == Z_FILTERED)) || ((((match_length == MIN_MATCH)) && (((strstart - match_start) > 0x1000)))))))){
match_length = (MIN_MATCH - 1);
};
};
if ((((prev_length >= MIN_MATCH)) && ((match_length <= prev_length)))){
max_insert = ((strstart + lookahead) - MIN_MATCH);
bflush = _tr_tally(((strstart - 1) - prev_match), (prev_length - MIN_MATCH));
lookahead = (lookahead - (prev_length - 1));
prev_length = (prev_length - 2);
do {
if (++strstart <= max_insert){
ins_h = (((ins_h << hash_shift) ^ (window[(strstart + (MIN_MATCH - 1))] & 0xFF)) & hash_mask);
hash_head = (head[ins_h] & 0xFFFF);
prev[(strstart & w_mask)] = head[ins_h];
head[ins_h] = Cast.toShort(strstart);
};
} while (--prev_length != 0);
match_available = 0;
match_length = (MIN_MATCH - 1);
strstart++;
if (bflush){
flush_block_only(false);
if (strm.avail_out == 0){
return (NeedMore);
};
};
} else {
if (match_available != 0){
bflush = _tr_tally(0, (window[(strstart - 1)] & 0xFF));
if (bflush){
flush_block_only(false);
};
strstart++;
lookahead--;
if (strm.avail_out == 0){
return (NeedMore);
};
} else {
match_available = 1;
strstart++;
lookahead--;
};
};
};
if (match_available != 0){
bflush = _tr_tally(0, (window[(strstart - 1)] & 0xFF));
match_available = 0;
};
flush_block_only((flush == Z_FINISH));
if (strm.avail_out == 0){
if (flush == Z_FINISH){
return (FinishStarted);
};
return (NeedMore);
};
return (((flush == Z_FINISH)) ? FinishDone : BlockDone);
}
public function bi_windup():void{
if (bi_valid > 8){
put_short(bi_buf);
} else {
if (bi_valid > 0){
this.put_byte_withInt(bi_buf);
};
};
bi_buf = 0;
bi_valid = 0;
}
function pqdownheap(tree:Array, k:int):void{
var v:int = heap[k];
var j = (k << 1);
while (j <= heap_len) {
if ((((j < heap_len)) && (smaller(tree, heap[(j + 1)], heap[j], depth)))){
j++;
};
if (smaller(tree, v, heap[j], depth)){
break;
};
heap[k] = heap[j];
k = j;
j = (j << 1);
};
heap[k] = v;
}
public function build_bl_tree():int{
var max_blindex:int;
scan_tree(dyn_ltree, l_desc.max_code);
scan_tree(dyn_dtree, d_desc.max_code);
bl_desc.build_tree(this);
max_blindex = (BL_CODES - 1);
while (max_blindex >= 3) {
if (bl_tree[((Tree.bl_order[max_blindex] * 2) + 1)] != 0){
break;
};
max_blindex--;
};
opt_len = (opt_len + ((((3 * (max_blindex + 1)) + 5) + 5) + 4));
return (max_blindex);
}
function init_block():void{
var i:int;
i = 0;
while (i < L_CODES) {
dyn_ltree[(i * 2)] = 0;
i++;
};
i = 0;
while (i < D_CODES) {
dyn_dtree[(i * 2)] = 0;
i++;
};
i = 0;
while (i < BL_CODES) {
bl_tree[(i * 2)] = 0;
i++;
};
dyn_ltree[(END_BLOCK * 2)] = 1;
opt_len = (static_len = 0);
last_lit = (matches = 0);
}
function deflateEnd():int{
if (((((!((status == INIT_STATE))) && (!((status == BUSY_STATE))))) && (!((status == FINISH_STATE))))){
return (Z_STREAM_ERROR);
};
pending_buf = null;
head = null;
prev = null;
window = null;
return (((status == BUSY_STATE)) ? Z_DATA_ERROR : Z_OK);
}
final public function putShortMSB(b:int):void{
this.put_byte_withInt((b >> 8));
this.put_byte_withInt((b & 0xFF));
}
function deflateParams(strm:ZStream, _level:int, _strategy:int):int{
var err:int = Z_OK;
if (_level == Z_DEFAULT_COMPRESSION){
_level = 6;
};
if ((((((((_level < 0)) || ((_level > 9)))) || ((_strategy < 0)))) || ((_strategy > Z_HUFFMAN_ONLY)))){
return (Z_STREAM_ERROR);
};
if (((!((config_table[level].func == config_table[_level].func))) && (!((strm.total_in == 0))))){
err = strm.deflate(Z_PARTIAL_FLUSH);
};
if (level != _level){
level = _level;
max_lazy_match = config_table[level].max_lazy;
good_match = config_table[level].good_length;
nice_match = config_table[level].nice_length;
max_chain_length = config_table[level].max_chain;
};
strategy = _strategy;
return (err);
}
public function deflateInit2(strm:ZStream, level:int, method:int, windowBits:int, memLevel:int, strategy:int):int{
var noheader:int;
strm.msg = null;
if (level == Z_DEFAULT_COMPRESSION){
level = 6;
};
if (windowBits < 0){
noheader = 1;
windowBits = -(windowBits);
};
if ((((((((((((((((((memLevel < 1)) || ((memLevel > MAX_MEM_LEVEL)))) || (!((method == Z_DEFLATED))))) || ((windowBits < 9)))) || ((windowBits > 15)))) || ((level < 0)))) || ((level > 9)))) || ((strategy < 0)))) || ((strategy > Z_HUFFMAN_ONLY)))){
return (Z_STREAM_ERROR);
};
strm.dstate = Deflate(this);
this.noheader = noheader;
w_bits = windowBits;
w_size = (1 << w_bits);
w_mask = (w_size - 1);
hash_bits = (memLevel + 7);
hash_size = (1 << hash_bits);
hash_mask = (hash_size - 1);
hash_shift = (((hash_bits + MIN_MATCH) - 1) / MIN_MATCH);
window = new ByteArray();
prev = new Array();
head = new Array();
lit_bufsize = (1 << (memLevel + 6));
pending_buf = new ByteArray();
pending_buf_size = (lit_bufsize * 4);
d_buf = (lit_bufsize / 2);
l_buf = ((1 + 2) * lit_bufsize);
this.level = level;
this.strategy = strategy;
this.method = method;
return (deflateReset(strm));
}
public function _tr_tally(dist:int, lc:int):Boolean{
var out_length:int;
var in_length:int;
var dcode:int;
pending_buf[(d_buf + (last_lit * 2))] = Cast.toByte((dist >>> 8));
pending_buf[((d_buf + (last_lit * 2)) + 1)] = Cast.toByte(dist);
pending_buf[(l_buf + last_lit)] = lc;
last_lit++;
if (dist == 0){
var _local6 = dyn_ltree;
var _local7 = (lc * 2);
var _local8 = (_local6[_local7] + 1);
_local6[_local7] = _local8;
} else {
matches++;
dist--;
_local6 = dyn_ltree;
_local7 = (((Tree._length_code[lc] + LITERALS) + 1) * 2);
_local8 = (_local6[_local7] + 1);
_local6[_local7] = _local8;
_local6 = dyn_dtree;
_local7 = (Tree.d_code(dist) * 2);
_local8 = (_local6[_local7] + 1);
_local6[_local7] = _local8;
};
if (((((last_lit & 1) == 0)) && ((level > 2)))){
out_length = (last_lit * 8);
in_length = (strstart - block_start);
dcode = 0;
while (dcode < D_CODES) {
out_length = (out_length + (int(dyn_dtree[(dcode * 2)]) * (5 + Tree.extra_dbits[dcode])));
dcode++;
};
out_length = (out_length >>> 3);
if ((((matches < (last_lit / 2))) && ((out_length < (in_length / 2))))){
return (true);
};
};
return ((last_lit == (lit_bufsize - 1)));
}
public function deflateInit(strm:ZStream, level:int):int{
return (deflateInitWithBits(strm, level, MAX_WBITS));
}
function longest_match(cur_match:int):int{
var match:int;
var len:int;
var chain_length:int = max_chain_length;
var scan:int = strstart;
var best_len:int = prev_length;
var limit:int = ((strstart > (w_size - MIN_LOOKAHEAD))) ? (strstart - (w_size - MIN_LOOKAHEAD)) : 0;
var nice_match:int = this.nice_match;
var wmask:int = w_mask;
var strend:int = (strstart + MAX_MATCH);
var scan_end1:uint = window[((scan + best_len) - 1)];
var scan_end:uint = window[(scan + best_len)];
if (prev_length >= good_match){
chain_length = (chain_length >> 2);
};
if (nice_match > lookahead){
nice_match = lookahead;
};
do {
match = cur_match;
if (((((((!((window[(match + best_len)] == scan_end))) || (!((window[((match + best_len) - 1)] == scan_end1))))) || (!((window[match] == window[scan]))))) || (!((window[_temp2] == window[(scan + 1)]))))){
} else {
scan = (scan + 2);
match++;
do {
++scan;
++match;
} while ((((((((((((((((((window[scan] == window[match])) && ((window[_temp4] == window[_temp5])))) && ((window[_temp7] == window[_temp8])))) && ((window[_temp10] == window[_temp11])))) && ((window[_temp13] == window[_temp14])))) && ((window[_temp16] == window[_temp17])))) && ((window[_temp19] == window[_temp20])))) && ((window[_temp22] == window[_temp23])))) && ((scan < strend))));
len = (MAX_MATCH - int((strend - scan)));
scan = (strend - MAX_MATCH);
if (len > best_len){
match_start = cur_match;
best_len = len;
if (len >= nice_match){
break;
};
scan_end1 = window[((scan + best_len) - 1)];
scan_end = window[(scan + best_len)];
};
};
cur_match = (prev[(cur_match & wmask)] & 0xFFFF);
} while ((((cur_match > limit)) && (!((_temp24 == 0)))));
if (best_len <= lookahead){
return (best_len);
};
return (lookahead);
}
public function _tr_stored_block(buf:int, stored_len:int, eof:Boolean):void{
send_bits(((STORED_BLOCK << 1) + (eof) ? 1 : 0), 3);
copy_block(buf, stored_len, true);
}
public function deflateInitWithBits(strm:ZStream, level:int, bits:int):int{
return (deflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY));
}
function deflateReset(strm:ZStream):int{
strm.total_in = (strm.total_out = 0);
strm.msg = null;
strm.data_type = Z_UNKNOWN;
pending = 0;
pending_out = 0;
pending_buf = new ByteArray();
if (noheader < 0){
noheader = 0;
};
status = ((noheader)!=0) ? BUSY_STATE : INIT_STATE;
strm.adler = strm._adler.adler32(0, null, 0, 0);
last_flush = Z_NO_FLUSH;
tr_init();
lm_init();
return (Z_OK);
}
public function deflate_fast(flush:int):int{
var bflush:Boolean;
var hash_head:int;
while (true) {
if (lookahead < MIN_LOOKAHEAD){
fill_window();
if ((((lookahead < MIN_LOOKAHEAD)) && ((flush == Z_NO_FLUSH)))){
return (NeedMore);
};
if (lookahead == 0){
break;
};
};
if (lookahead >= MIN_MATCH){
ins_h = (((ins_h << hash_shift) ^ (window[(strstart + (MIN_MATCH - 1))] & 0xFF)) & hash_mask);
hash_head = head[ins_h];
prev[(strstart & w_mask)] = head[ins_h];
head[ins_h] = Cast.toShort(strstart);
};
if (((!((hash_head == 0))) && (((strstart - hash_head) <= (w_size - MIN_LOOKAHEAD))))){
if (strategy != Z_HUFFMAN_ONLY){
match_length = longest_match(hash_head);
};
};
if (match_length >= MIN_MATCH){
bflush = _tr_tally((strstart - match_start), (match_length - MIN_MATCH));
lookahead = (lookahead - match_length);
if ((((match_length <= max_lazy_match)) && ((lookahead >= MIN_MATCH)))){
match_length--;
do {
strstart++;
ins_h = (((ins_h << hash_shift) ^ (window[(strstart + (MIN_MATCH - 1))] & 0xFF)) & hash_mask);
hash_head = (head[ins_h] & 0xFFFF);
prev[(strstart & w_mask)] = head[ins_h];
head[ins_h] = Cast.toShort(strstart);
} while (--match_length != 0);
strstart++;
} else {
strstart = (strstart + match_length);
match_length = 0;
ins_h = window[strstart];
ins_h = (((ins_h << hash_shift) ^ (window[(strstart + 1)] & 0xFF)) & hash_mask);
};
} else {
bflush = _tr_tally(0, (window[strstart] & 0xFF));
lookahead--;
strstart++;
};
if (bflush){
flush_block_only(false);
if (strm.avail_out == 0){
return (NeedMore);
};
};
};
flush_block_only((flush == Z_FINISH));
if (strm.avail_out == 0){
if (flush == Z_FINISH){
return (FinishStarted);
};
return (NeedMore);
};
return (((flush == Z_FINISH)) ? FinishDone : BlockDone);
}
static function smaller(tree:Array, n:int, m:int, depth:Array):Boolean{
var tn2:Number = tree[(n * 2)];
var tm2:Number = tree[(m * 2)];
return ((((tn2 < tm2)) || ((((tn2 == tm2)) && ((depth[n] <= depth[m]))))));
}
}
}//package com.wirelust.as3zlib
Section 72
//DeflateConfig (com.wirelust.as3zlib.DeflateConfig)
package com.wirelust.as3zlib {
public class DeflateConfig {
public var func:int;
public var max_lazy:int;
public var good_length:int;
public var max_chain:int;
public var nice_length:int;
public function DeflateConfig(good_length:int, max_lazy:int, nice_length:int, max_chain:int, func:int){
super();
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
}
}
}//package com.wirelust.as3zlib
Section 73
//InfBlocks (com.wirelust.as3zlib.InfBlocks)
package com.wirelust.as3zlib {
import flash.utils.*;
import com.wirelust.util.*;
public final class InfBlocks {
public var left:int;
public var check:Number;
public var bb:Array;
public var checkfn:Object;
public var index:int;
public var table:int;
public var last:int;
public var end:int;
public var read:int;
public var write:int;
public var blens:Array;
public var mode:int;
public var codes:InfCodes;
public var tb:Array;
public var window:ByteArray;
public var bitb:int;
public var hufts:Array;
public var bitk:int;
public var inftree:InfTree;
private static const Z_STREAM_END:int = 1;
private static const LENS:int = 1;
private static const DRY:int = 7;
private static const CODES:int = 6;
private static const Z_BUF_ERROR:int = -5;
private static const Z_DATA_ERROR:int = -3;
private static const Z_NEED_DICT:int = 2;
private static const BTREE:int = 4;
private static const Z_OK:int = 0;
private static const STORED:int = 2;
private static const inflate_mask:Array = new Array(0, 1, 3, 7, 15, 31, 63, 127, 0xFF, 511, 1023, 2047, 4095, 8191, 16383, 32767, 0xFFFF);
private static const BAD:int = 9;
private static const MANY:int = 1440;
private static const Z_ERRNO:int = -1;
private static const DTREE:int = 5;
public static const border:Array = new Array(16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15);
private static const Z_STREAM_ERROR:int = -2;
private static const DONE:int = 8;
private static const Z_MEM_ERROR:int = -4;
private static const TYPE:int = 0;
private static const Z_VERSION_ERROR:int = -6;
private static const TABLE:int = 3;
public function InfBlocks(z:ZStream, checkfn:Object, w:int){
bb = new Array();
tb = new Array();
codes = new InfCodes();
inftree = new InfTree();
super();
hufts = new Array();
window = new ByteArray();
end = w;
this.checkfn = checkfn;
mode = TYPE;
reset(z, null);
}
public function sync_point():int{
return (((mode == LENS)) ? 1 : 0);
}
public function set_dictionary(d:ByteArray, start:int, n:int):void{
System.byteArrayCopy(d, start, window, 0, n);
read = (write = n);
}
public function reset(z:ZStream, c:Array):void{
if (c != null){
c[0] = check;
};
if ((((mode == BTREE)) || ((mode == DTREE)))){
};
if (mode == CODES){
codes.free(z);
};
mode = TYPE;
bitk = 0;
bitb = 0;
read = (write = 0);
if (checkfn != null){
z.adler = (check = z._adler.adler32(0, null, 0, 0));
};
}
public function proc(z:ZStream, r:int):int{
var t:int;
var b:int;
var k:int;
var p:int;
var n:int;
var q:int;
var m:int;
var bl:Array;
var bd:Array;
var tl:Array;
var td:Array;
var h:Array;
var i:int;
var j:int;
var c:int;
var nextByte:int;
p = z.next_in_index;
n = z.avail_in;
b = bitb;
k = bitk;
q = write;
m = int(((q < read)) ? ((read - q) - 1) : (end - q));
while (true) {
switch (mode){
case TYPE:
while (k < 3) {
if (n != 0){
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
n--;
var _temp1 = p;
p = (p + 1);
z.next_in.position = _temp1;
nextByte = Cast.toByte(z.next_in.readByte());
b = (b | ((nextByte & 0xFF) << k));
k = (k + 8);
};
t = int((b & 7));
last = (t & 1);
switch ((t >>> 1)){
case 0:
b = (b >>> 3);
k = (k - 3);
t = (k & 7);
b = (b >>> t);
k = (k - t);
mode = LENS;
break;
case 1:
bl = new Array(1);
bd = new Array(1);
tl = new Array();
tl[0] = new Array();
td = new Array();
td[0] = new Array();
InfTree.inflate_trees_fixed(bl, bd, tl, td, z);
codes.init(bl[0], bd[0], tl[0], 0, td[0], 0, z);
b = (b >>> 3);
k = (k - 3);
mode = CODES;
break;
case 2:
b = (b >>> 3);
k = (k - 3);
mode = TABLE;
break;
case 3:
b = (b >>> 3);
k = (k - 3);
mode = BAD;
z.msg = "invalid block type";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
break;
case LENS:
while (k < 32) {
if (n != 0){
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
n--;
var _temp2 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp2] & 0xFF) << k));
k = (k + 8);
};
if (((~(b) >>> 16) & 0xFFFF) != (b & 0xFFFF)){
mode = BAD;
z.msg = "invalid stored block lengths";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
left = (b & 0xFFFF);
k = 0;
b = k;
mode = ((left)!=0) ? STORED : ((last)!=0) ? DRY : TYPE;
break;
case STORED:
if (n == 0){
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
if (m == 0){
if ((((q == end)) && (!((read == 0))))){
q = 0;
m = int(((q < read)) ? ((read - q) - 1) : (end - q));
};
if (m == 0){
write = q;
r = inflate_flush(z, r);
q = write;
m = int(((q < read)) ? ((read - q) - 1) : (end - q));
if ((((q == end)) && (!((read == 0))))){
q = 0;
m = int(((q < read)) ? ((read - q) - 1) : (end - q));
};
if (m == 0){
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
};
};
r = Z_OK;
t = left;
if (t > n){
t = n;
};
if (t > m){
t = m;
};
System.byteArrayCopy(z.next_in, p, window, q, t);
p = (p + t);
n = (n - t);
q = (q + t);
m = (m - t);
if ((left = (left - t)) != 0){
break;
};
mode = ((last)!=0) ? DRY : TYPE;
break;
case TABLE:
while (k < 14) {
if (n != 0){
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
n--;
var _temp3 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp3] & 0xFF) << k));
k = (k + 8);
};
t = (b & 16383);
table = t;
if (((((t & 31) > 29)) || ((((t >> 5) & 31) > 29)))){
mode = BAD;
z.msg = "too many length or distance symbols";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
t = ((258 + (t & 31)) + ((t >> 5) & 31));
if ((((blens == null)) || ((blens.length < t)))){
blens = new Array();
} else {
i = 0;
while (i < t) {
blens[i] = 0;
i++;
};
};
b = (b >>> 14);
k = (k - 14);
index = 0;
mode = BTREE;
case BTREE:
while (index < (4 + (table >>> 10))) {
while (k < 3) {
if (n != 0){
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
n--;
var _temp4 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp4] & 0xFF) << k));
k = (k + 8);
};
blens[border[index++]] = (b & 7);
b = (b >>> 3);
k = (k - 3);
};
while (index < 19) {
blens[border[index++]] = 0;
};
bb[0] = 7;
t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z);
if (t != Z_OK){
r = t;
if (r == Z_DATA_ERROR){
blens = null;
mode = BAD;
};
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
index = 0;
mode = DTREE;
case DTREE:
while (true) {
t = table;
if (!(index < ((258 + (t & 31)) + ((t >> 5) & 31)))){
break;
};
t = bb[0];
while (k < t) {
if (n != 0){
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
n--;
var _temp5 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp5] & 0xFF) << k));
k = (k + 8);
};
if (tb[0] == -1){
};
t = hufts[(((tb[0] + (b & inflate_mask[t])) * 3) + 1)];
c = hufts[(((tb[0] + (b & inflate_mask[t])) * 3) + 2)];
if (c < 16){
b = (b >>> t);
k = (k - t);
var _local19 = index++;
blens[_local19] = c;
} else {
i = ((c == 18)) ? 7 : (c - 14);
j = ((c == 18)) ? 11 : 3;
while (k < (t + i)) {
if (n != 0){
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
n--;
var _temp6 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp6] & 0xFF) << k));
k = (k + 8);
};
b = (b >>> t);
k = (k - t);
j = (j + (b & inflate_mask[i]));
b = (b >>> i);
k = (k - i);
i = index;
t = table;
if (((((i + j) > ((258 + (t & 31)) + ((t >> 5) & 31)))) || ((((c == 16)) && ((i < 1)))))){
blens = null;
mode = BAD;
z.msg = "invalid bit length repeat";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
c = ((c == 16)) ? blens[(i - 1)] : 0;
do {
var _temp7 = i;
i = (i + 1);
_local19 = _temp7;
blens[_local19] = c;
--j;
} while (j != 0);
index = i;
};
};
tb[0] = -1;
bl = new Array();
bd = new Array();
tl = new Array();
td = new Array();
bl[0] = 9;
bd[0] = 6;
t = table;
t = inftree.inflate_trees_dynamic((0x0101 + (t & 31)), (1 + ((t >> 5) & 31)), blens, bl, bd, tl, td, hufts, z);
if (t != Z_OK){
if (t == Z_DATA_ERROR){
blens = null;
mode = BAD;
};
r = t;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
codes.init(bl[0], bd[0], hufts, tl[0], hufts, td[0], z);
mode = CODES;
case CODES:
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
r = codes.proc(this, z, r);
if (r != Z_STREAM_END){
return (inflate_flush(z, r));
};
r = Z_OK;
codes.free(z);
p = z.next_in_index;
n = z.avail_in;
b = bitb;
k = bitk;
q = write;
m = int(((q < read)) ? ((read - q) - 1) : (end - q));
if (last == 0){
mode = TYPE;
break;
};
mode = DRY;
case DRY:
write = q;
r = inflate_flush(z, r);
q = write;
m = int(((q < read)) ? ((read - q) - 1) : (end - q));
if (read != write){
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
mode = DONE;
case DONE:
r = Z_STREAM_END;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
case BAD:
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
default:
r = Z_STREAM_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
};
};
r = Z_STREAM_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
write = q;
return (inflate_flush(z, r));
}
public function inflate_flush(z:ZStream, r:int):int{
var n:int;
var p:int;
var q:int;
p = z.next_out_index;
q = read;
n = int((((q <= write)) ? write : end - q));
if (n > z.avail_out){
n = z.avail_out;
};
if (((!((n == 0))) && ((r == Z_BUF_ERROR)))){
r = Z_OK;
};
z.avail_out = (z.avail_out - n);
z.total_out = (z.total_out + n);
if (checkfn != null){
z.adler = (check = z._adler.adler32(check, window, q, n));
};
System.byteArrayCopy(window, q, z.next_out, p, n);
p = (p + n);
q = (q + n);
if (q == end){
q = 0;
if (write == end){
write = 0;
};
n = (write - q);
if (n > z.avail_out){
n = z.avail_out;
};
if (((!((n == 0))) && ((r == Z_BUF_ERROR)))){
r = Z_OK;
};
z.avail_out = (z.avail_out - n);
z.total_out = (z.total_out + n);
if (checkfn != null){
z.adler = (check = z._adler.adler32(check, window, q, n));
};
System.byteArrayCopy(window, q, z.next_out, p, n);
p = (p + n);
q = (q + n);
};
z.next_out_index = p;
read = q;
return (r);
}
public function free(z:ZStream):void{
reset(z, null);
window = null;
hufts = null;
}
}
}//package com.wirelust.as3zlib
Section 74
//InfCodes (com.wirelust.as3zlib.InfCodes)
package com.wirelust.as3zlib {
import com.wirelust.as3zlib.*;
final class InfCodes {
public var dtree:Array;
public var ltree:Array;
public var len:int;
public var need:int;
public var lit:int;
public var dtree_index:int;
public var ltree_index:int;
public var tree:Array;
public var mode:int;
public var dist:int;
public var tree_index:int;// = 0
public var lbits:uint;
public var dbits:uint;
public var getBits:int;
private static const Z_STREAM_END:int = 1;
private static const COPY:int = 5;
private static const START:int = 0;
private static const BADCODE:int = 9;
private static const Z_BUF_ERROR:int = -5;
private static const Z_DATA_ERROR:int = -3;
private static const Z_NEED_DICT:int = 2;
private static const DISTEXT:int = 4;
private static const Z_OK:int = 0;
private static const inflate_mask:Array = new Array(0, 1, 3, 7, 15, 31, 63, 127, 0xFF, 511, 1023, 2047, 4095, 8191, 16383, 32767, 0xFFFF);
private static const WASH:int = 7;
private static const DIST:int = 3;
private static const Z_ERRNO:int = -1;
private static const LENEXT:int = 2;
private static const Z_STREAM_ERROR:int = -2;
private static const LEN:int = 1;
private static const LIT:int = 6;
private static const Z_MEM_ERROR:int = -4;
private static const END:int = 8;
private static const Z_VERSION_ERROR:int = -6;
function InfCodes(){
super();
}
public function init(bl:int, bd:int, tl:Array, tl_index:int, td:Array, td_index:int, z:ZStream):void{
mode = START;
lbits = bl;
dbits = bd;
ltree = tl;
ltree_index = tl_index;
dtree = td;
dtree_index = td_index;
tree = null;
}
function proc(s:InfBlocks, z:ZStream, r:int):int{
var j:int;
var t:Array;
var tindex:int;
var e:int;
var p:int;
var n:int;
var q:int;
var m:int;
var f:int;
var b:int;
var k:int;
p = 0;
p = z.next_in_index;
n = z.avail_in;
b = s.bitb;
k = s.bitk;
q = s.write;
m = ((q < s.read)) ? ((s.read - q) - 1) : (s.end - q);
while (true) {
switch (mode){
case START:
if ((((m >= 258)) && ((n >= 10)))){
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, s, z);
p = z.next_in_index;
n = z.avail_in;
b = s.bitb;
k = s.bitk;
q = s.write;
m = ((q < s.read)) ? ((s.read - q) - 1) : (s.end - q);
if (r != Z_OK){
mode = ((r == Z_STREAM_END)) ? WASH : BADCODE;
break;
};
};
need = lbits;
tree = ltree;
tree_index = ltree_index;
mode = LEN;
case LEN:
j = need;
while (k < j) {
if (n != 0){
r = Z_OK;
} else {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
};
n--;
var _temp1 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp1] & 0xFF) << k));
k = (k + 8);
};
tindex = ((tree_index + (b & inflate_mask[j])) * 3);
b = (b >>> tree[(tindex + 1)]);
k = (k - tree[(tindex + 1)]);
e = tree[tindex];
if (e == 0){
lit = tree[(tindex + 2)];
mode = LIT;
break;
};
if ((e & 16) != 0){
getBits = (e & 15);
len = tree[(tindex + 2)];
mode = LENEXT;
break;
};
if ((e & 64) == 0){
need = e;
tree_index = ((tindex / 3) + tree[(tindex + 2)]);
break;
};
if ((e & 32) != 0){
mode = WASH;
break;
};
mode = BADCODE;
z.msg = "invalid literal/length code";
r = Z_DATA_ERROR;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
case LENEXT:
j = getBits;
while (k < j) {
if (n != 0){
r = Z_OK;
} else {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
};
n--;
var _temp2 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp2] & 0xFF) << k));
k = (k + 8);
};
len = (len + (b & inflate_mask[j]));
b = (b >> j);
k = (k - j);
need = dbits;
tree = dtree;
tree_index = dtree_index;
mode = DIST;
case DIST:
j = need;
while (k < j) {
if (n != 0){
r = Z_OK;
} else {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
};
n--;
var _temp3 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp3] & 0xFF) << k));
k = (k + 8);
};
tindex = ((tree_index + (b & inflate_mask[j])) * 3);
b = (b >> tree[(tindex + 1)]);
k = (k - tree[(tindex + 1)]);
e = tree[tindex];
if ((e & 16) != 0){
getBits = (e & 15);
dist = tree[(tindex + 2)];
mode = DISTEXT;
break;
};
if ((e & 64) == 0){
need = e;
tree_index = ((tindex / 3) + tree[(tindex + 2)]);
break;
};
mode = BADCODE;
z.msg = "invalid distance code";
r = Z_DATA_ERROR;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
case DISTEXT:
j = getBits;
while (k < j) {
if (n != 0){
r = Z_OK;
} else {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
};
n--;
var _temp4 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp4] & 0xFF) << k));
k = (k + 8);
};
dist = (dist + (b & inflate_mask[j]));
b = (b >> j);
k = (k - j);
mode = COPY;
case COPY:
f = (q - dist);
while (f < 0) {
f = (f + s.end);
};
while (len != 0) {
if (m == 0){
if ((((q == s.end)) && (!((s.read == 0))))){
q = 0;
m = ((q < s.read)) ? ((s.read - q) - 1) : (s.end - q);
};
if (m == 0){
s.write = q;
r = s.inflate_flush(z, r);
q = s.write;
m = ((q < s.read)) ? ((s.read - q) - 1) : (s.end - q);
if ((((q == s.end)) && (!((s.read == 0))))){
q = 0;
m = ((q < s.read)) ? ((s.read - q) - 1) : (s.end - q);
};
if (m == 0){
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
};
};
};
var _temp5 = q;
q = (q + 1);
var _local15 = _temp5;
var _temp6 = f;
f = (f + 1);
s.window[_local15] = s.window[_temp6];
m--;
if (f == s.end){
f = 0;
};
len--;
};
mode = START;
break;
case LIT:
if (m == 0){
if ((((q == s.end)) && (!((s.read == 0))))){
q = 0;
m = ((q < s.read)) ? ((s.read - q) - 1) : (s.end - q);
};
if (m == 0){
s.write = q;
r = s.inflate_flush(z, r);
q = s.write;
m = ((q < s.read)) ? ((s.read - q) - 1) : (s.end - q);
if ((((q == s.end)) && (!((s.read == 0))))){
q = 0;
m = ((q < s.read)) ? ((s.read - q) - 1) : (s.end - q);
};
if (m == 0){
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
};
};
};
r = Z_OK;
var _temp7 = q;
q = (q + 1);
_local15 = _temp7;
s.window[_local15] = lit;
m--;
mode = START;
break;
case WASH:
if (k > 7){
k = (k - 8);
n++;
p--;
};
s.write = q;
r = s.inflate_flush(z, r);
q = s.write;
m = ((q < s.read)) ? ((s.read - q) - 1) : (s.end - q);
if (s.read != s.write){
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
};
mode = END;
case END:
r = Z_STREAM_END;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
case BADCODE:
r = Z_DATA_ERROR;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
default:
r = Z_STREAM_ERROR;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
};
};
r = Z_STREAM_ERROR;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (s.inflate_flush(z, r));
}
public function inflate_fast(bl:int, bd:int, tl:Array, tl_index:int, td:Array, td_index:int, s:InfBlocks, z:ZStream):int{
var t:int;
var tp:Array;
var tp_index:int;
var e:int;
var b:int;
var k:int;
var p:int;
var n:int;
var q:int;
var m:int;
var ml:int;
var md:int;
var c:int;
var d:int;
var r:int;
var tp_index_t_3:int;
var needContinue:*;
p = z.next_in_index;
n = z.avail_in;
b = s.bitb;
k = s.bitk;
q = s.write;
m = ((q < s.read)) ? ((s.read - q) - 1) : (s.end - q);
ml = inflate_mask[bl];
md = inflate_mask[bd];
do {
needContinue = false;
while (k < 20) {
n--;
var _temp1 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp1] & 0xFF) << k));
k = (k + 8);
};
t = (b & ml);
tp = tl;
tp_index = tl_index;
tp_index_t_3 = ((tp_index + t) * 3);
e = tp[tp_index_t_3];
if (e == 0){
b = (b >> tp[(tp_index_t_3 + 1)]);
k = (k - tp[(tp_index_t_3 + 1)]);
var _temp2 = q;
q = (q + 1);
var _local26 = _temp2;
s.window[_local26] = tp[(tp_index_t_3 + 2)];
m--;
needContinue = true;
};
if (!needContinue){
do {
b = (b >> tp[(tp_index_t_3 + 1)]);
k = (k - tp[(tp_index_t_3 + 1)]);
if ((e & 16) != 0){
e = (e & 15);
c = (tp[(tp_index_t_3 + 2)] + (int(b) & inflate_mask[e]));
b = (b >> e);
k = (k - e);
while (k < 15) {
n--;
var _temp3 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp3] & 0xFF) << k));
k = (k + 8);
};
t = (b & md);
tp = td;
tp_index = td_index;
tp_index_t_3 = ((tp_index + t) * 3);
e = tp[tp_index_t_3];
do {
b = (b >> tp[(tp_index_t_3 + 1)]);
k = (k - tp[(tp_index_t_3 + 1)]);
if ((e & 16) != 0){
e = (e & 15);
while (k < e) {
n--;
var _temp4 = p;
p = (p + 1);
b = (b | ((z.next_in[_temp4] & 0xFF) << k));
k = (k + 8);
};
d = (tp[(tp_index_t_3 + 2)] + (b & inflate_mask[e]));
b = (b >> e);
k = (k - e);
m = (m - c);
if (q >= d){
r = (q - d);
if (((((q - r) > 0)) && ((2 > (q - r))))){
var _temp5 = q;
q = (q + 1);
_local26 = _temp5;
var _temp6 = r;
r = (r + 1);
s.window[_local26] = s.window[_temp6];
var _temp7 = q;
q = (q + 1);
var _local27 = _temp7;
var _temp8 = r;
r = (r + 1);
s.window[_local27] = s.window[_temp8];
c = (c - 2);
} else {
System.byteArrayCopy(s.window, r, s.window, q, 2);
q = (q + 2);
r = (r + 2);
c = (c - 2);
};
} else {
r = (q - d);
do {
r = (r + s.end);
} while (r < 0);
e = (s.end - r);
if (c > e){
c = (c - e);
if (((((q - r) > 0)) && ((e > (q - r))))){
do {
var _temp9 = q;
q = (q + 1);
_local26 = _temp9;
var _temp10 = r;
r = (r + 1);
s.window[_local26] = s.window[_temp10];
--e;
} while (e != 0);
} else {
System.byteArrayCopy(s.window, r, s.window, q, e);
q = (q + e);
r = (r + e);
e = 0;
};
r = 0;
};
};
if (((((q - r) > 0)) && ((c > (q - r))))){
do {
var _temp11 = q;
q = (q + 1);
_local26 = _temp11;
var _temp12 = r;
r = (r + 1);
s.window[_local26] = s.window[_temp12];
--c;
} while (c != 0);
} else {
System.byteArrayCopy(s.window, r, s.window, q, c);
q = (q + c);
r = (r + c);
c = 0;
};
break;
} else {
if ((e & 64) == 0){
t = (t + tp[(tp_index_t_3 + 2)]);
t = (t + (b & inflate_mask[e]));
tp_index_t_3 = ((tp_index + t) * 3);
e = tp[tp_index_t_3];
} else {
z.msg = "invalid distance code";
c = (z.avail_in - n);
c = (((k >> 3) < c)) ? (k >> 3) : c;
n = (n + c);
p = (p - c);
k = (k - (c << 3));
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (Z_DATA_ERROR);
};
};
} while (true);
break;
};
if ((e & 64) == 0){
t = (t + tp[(tp_index_t_3 + 2)]);
t = (t + (b & inflate_mask[e]));
tp_index_t_3 = ((tp_index + t) * 3);
e = tp[tp_index_t_3];
if (e == 0){
b = (b >> tp[(tp_index_t_3 + 1)]);
k = (k - tp[(tp_index_t_3 + 1)]);
var _temp13 = q;
q = (q + 1);
_local26 = _temp13;
s.window[_local26] = tp[(tp_index_t_3 + 2)];
m--;
break;
};
} else {
if ((e & 32) != 0){
c = (z.avail_in - n);
c = (((k >> 3) < c)) ? (k >> 3) : c;
n = (n + c);
p = (p - c);
k = (k - (c << 3));
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (Z_STREAM_END);
} else {
z.msg = "invalid literal/length code";
c = (z.avail_in - n);
c = (((k >> 3) < c)) ? (k >> 3) : c;
n = (n + c);
p = (p - c);
k = (k - (c << 3));
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (Z_DATA_ERROR);
};
};
} while (true);
};
} while ((((m >= 258)) && ((n >= 10))));
c = (z.avail_in - n);
c = (((k >> 3) < c)) ? (k >> 3) : c;
n = (n + c);
p = (p - c);
k = (k - (c << 3));
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
s.write = q;
return (Z_OK);
}
public function free(z:ZStream):void{
}
}
}//package com.wirelust.as3zlib
Section 75
//Inflate (com.wirelust.as3zlib.Inflate)
package com.wirelust.as3zlib {
import flash.utils.*;
public final class Inflate {
public var method:int;
public var mode:int;
public var wbits:int;
public var was:Array;
public var nowrap:int;
public var blocks:InfBlocks;
public var marker:int;
public var need:Number;
private static const Z_STREAM_END:int = 1;
public static const BLOCKS:int = 7;
public static const DONE:int = 12;
private static const PRESET_DICT:int = 32;
public static const Z_FINISH:int = 4;
private static const Z_NEED_DICT:int = 2;
private static const Z_DATA_ERROR:int = -3;
private static const Z_ERRNO:int = -1;
private static const MAX_WBITS:int = 15;
public static const Z_NO_FLUSH:int = 0;
private static const Z_STREAM_ERROR:int = -2;
private static const Z_MEM_ERROR:int = -4;
public static const DICT0:int = 6;
public static const DICT1:int = 5;
public static const DICT2:int = 4;
public static const DICT3:int = 3;
public static const DICT4:int = 2;
public static const Z_FULL_FLUSH:int = 3;
public static const Z_SYNC_FLUSH:int = 2;
public static const CHECK2:int = 10;
public static const CHECK3:int = 9;
public static const CHECK4:int = 8;
public static const CHECK1:int = 11;
private static const Z_BUF_ERROR:int = -5;
private static const Z_DEFLATED:int = 8;
public static const METHOD:int = 0;
public static const BAD:int = 13;
public static const Z_PARTIAL_FLUSH:int = 1;
public static const FLAG:int = 1;
private static const Z_OK:int = 0;
private static const Z_VERSION_ERROR:int = -6;
private static var mark:Array = new Array(0, 0, 0xFF, 0xFF);
public function Inflate(){
was = new Array();
super();
}
public function inflate(z:ZStream, f:int):int{
var r:int;
var b:int;
var _local5:int;
if ((((((z == null)) || ((z.istate == null)))) || ((z.next_in == null)))){
return (Z_STREAM_ERROR);
};
f = ((f == Z_FINISH)) ? Z_BUF_ERROR : Z_OK;
r = Z_BUF_ERROR;
while (true) {
switch (z.istate.mode){
case METHOD:
if (z.avail_in == 0){
return (r);
};
r = f;
z.avail_in--;
z.total_in++;
if (((z.istate.method = z.next_in[z.next_in_index++]) & 15) != Z_DEFLATED){
z.istate.mode = BAD;
z.msg = "unknown compression method";
z.istate.marker = 5;
break;
};
if (((z.istate.method >> 4) + 8) > z.istate.wbits){
z.istate.mode = BAD;
z.msg = "invalid window size";
z.istate.marker = 5;
break;
};
z.istate.mode = FLAG;
case FLAG:
if (z.avail_in == 0){
return (r);
};
r = f;
z.avail_in--;
z.total_in++;
b = (z.next_in[z.next_in_index++] & 0xFF);
_local5 = (((z.istate.method << 8) + b) % 31);
if (_local5 != 0){
z.istate.mode = BAD;
z.msg = "incorrect header check";
z.istate.marker = 5;
break;
};
if ((b & PRESET_DICT) == 0){
z.istate.mode = BLOCKS;
break;
};
z.istate.mode = DICT4;
case DICT4:
if (z.avail_in == 0){
return (r);
};
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = (((z.next_in[z.next_in_index++] & 0xFF) << 24) & 4278190080);
z.istate.mode = DICT3;
case DICT3:
if (z.avail_in == 0){
return (r);
};
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = (z.istate.need + (((z.next_in[z.next_in_index++] & 0xFF) << 16) & 0xFF0000));
z.istate.mode = DICT2;
case DICT2:
if (z.avail_in == 0){
return (r);
};
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = (z.istate.need + (((z.next_in[z.next_in_index++] & 0xFF) << 8) & 0xFF00));
z.istate.mode = DICT1;
case DICT1:
if (z.avail_in == 0){
return (r);
};
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = (z.istate.need + (z.next_in[z.next_in_index++] & 0xFF));
z.adler = z.istate.need;
z.istate.mode = DICT0;
return (Z_NEED_DICT);
case DICT0:
z.istate.mode = BAD;
z.msg = "need dictionary";
z.istate.marker = 0;
return (Z_STREAM_ERROR);
case BLOCKS:
r = z.istate.blocks.proc(z, r);
if (r == Z_DATA_ERROR){
z.istate.mode = BAD;
z.istate.marker = 0;
break;
};
if (r == Z_OK){
r = f;
};
if (r != Z_STREAM_END){
return (r);
};
r = f;
z.istate.blocks.reset(z, z.istate.was);
if (z.istate.nowrap != 0){
z.istate.mode = DONE;
break;
};
z.istate.mode = CHECK4;
case CHECK4:
if (z.avail_in == 0){
return (r);
};
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = (((z.next_in[z.next_in_index++] & 0xFF) << 24) & 4278190080);
z.istate.mode = CHECK3;
case CHECK3:
if (z.avail_in == 0){
return (r);
};
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = (z.istate.need + (((z.next_in[z.next_in_index++] & 0xFF) << 16) & 0xFF0000));
z.istate.mode = CHECK2;
case CHECK2:
if (z.avail_in == 0){
return (r);
};
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = (z.istate.need + (((z.next_in[z.next_in_index++] & 0xFF) << 8) & 0xFF00));
z.istate.mode = CHECK1;
case CHECK1:
if (z.avail_in == 0){
return (r);
};
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = (z.istate.need + (z.next_in[z.next_in_index++] & 0xFF));
if (int(z.istate.was[0]) != int(z.istate.need)){
z.istate.mode = BAD;
z.msg = "incorrect data check";
z.istate.marker = 5;
break;
};
z.istate.mode = DONE;
case DONE:
return (Z_STREAM_END);
case BAD:
return (Z_DATA_ERROR);
default:
return (Z_STREAM_ERROR);
};
};
return (Z_STREAM_ERROR);
}
public function inflateReset(z:ZStream):int{
if ((((z == null)) || ((z.istate == null)))){
return (Z_STREAM_ERROR);
};
z.total_in = (z.total_out = 0);
z.msg = null;
z.istate.mode = ((z.istate.nowrap)!=0) ? BLOCKS : METHOD;
z.istate.blocks.reset(z, null);
return (Z_OK);
}
public function inflateSyncPoint(z:ZStream):int{
if ((((((z == null)) || ((z.istate == null)))) || ((z.istate.blocks == null)))){
return (Z_STREAM_ERROR);
};
return (z.istate.blocks.sync_point());
}
public function inflateSync(z:ZStream):int{
var n:int;
var p:int;
var m:int;
var r:Number;
var w:Number;
if ((((z == null)) || ((z.istate == null)))){
return (Z_STREAM_ERROR);
};
if (z.istate.mode != BAD){
z.istate.mode = BAD;
z.istate.marker = 0;
};
n = z.avail_in;
if (n == 0){
return (Z_BUF_ERROR);
};
p = z.next_in_index;
m = z.istate.marker;
while (((!((n == 0))) && ((m < 4)))) {
if (z.next_in[p] == mark[m]){
m++;
} else {
if (z.next_in[p] != 0){
m = 0;
} else {
m = (4 - m);
};
};
p++;
n--;
};
z.total_in = (z.total_in + (p - z.next_in_index));
z.next_in_index = p;
z.avail_in = n;
z.istate.marker = m;
if (m != 4){
return (Z_DATA_ERROR);
};
r = z.total_in;
w = z.total_out;
inflateReset(z);
z.total_in = r;
z.total_out = w;
z.istate.mode = BLOCKS;
return (Z_OK);
}
public function inflateSetDictionary(z:ZStream, dictionary:ByteArray, dictLength:int):int{
var index:int;
var length:int = dictLength;
if ((((((z == null)) || ((z.istate == null)))) || (!((z.istate.mode == DICT0))))){
return (Z_STREAM_ERROR);
};
if (z._adler.adler32(1, dictionary, 0, dictLength) != z.adler){
return (Z_DATA_ERROR);
};
z.adler = z._adler.adler32(0, null, 0, 0);
if (length >= (1 << z.istate.wbits)){
length = ((1 << z.istate.wbits) - 1);
index = (dictLength - length);
};
z.istate.blocks.set_dictionary(dictionary, index, length);
z.istate.mode = BLOCKS;
return (Z_OK);
}
public function inflateInit(z:ZStream, w:int):int{
z.msg = null;
blocks = null;
nowrap = 0;
if (w < 0){
w = -(w);
nowrap = 1;
};
if ((((w < 8)) || ((w > 15)))){
inflateEnd(z);
return (Z_STREAM_ERROR);
};
wbits = w;
z.istate.blocks = new InfBlocks(z, ((z.istate.nowrap)!=0) ? null : this, (1 << w));
inflateReset(z);
return (Z_OK);
}
public function inflateEnd(z:ZStream):int{
if (blocks != null){
blocks.free(z);
};
blocks = null;
return (Z_OK);
}
}
}//package com.wirelust.as3zlib
Section 76
//InfTree (com.wirelust.as3zlib.InfTree)
package com.wirelust.as3zlib {
import com.wirelust.as3zlib.*;
final class InfTree {
public var c:Array;// = null
public var hn:Array;// = null
public var r:Array;// = null
public var u:Array;// = null
public var v:Array;// = null
public var x:Array;// = null
private static const Z_STREAM_END:int = 1;
public static const cpdext:Array = new Array(0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13);
public static const cpdist:Array = new Array(1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 0x0101, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577);
private static const Z_BUF_ERROR:int = -5;
private static const Z_DATA_ERROR:int = -3;
private static const Z_NEED_DICT:int = 2;
public static const fixed_td:Array = new Array(80, 5, 1, 87, 5, 0x0101, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33, 92, 5, 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537, 85, 5, 97, 93, 5, 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5, 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577);
private static const MANY:int = 1440;
private static const Z_ERRNO:int = -1;
public static const fixed_tl:Array = new Array(96, 7, 0x0100, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 0x0100, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 0x0100, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 0x0100, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 0xFF);
public static const BMAX:int = 15;
private static const Z_OK:int = 0;
public static const cplens:Array = new Array(3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0);
private static const fixed_bd:int = 5;
private static const Z_STREAM_ERROR:int = -2;
public static const cplext:Array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112);
private static const fixed_bl:int = 9;
private static const Z_MEM_ERROR:int = -4;
private static const Z_VERSION_ERROR:int = -6;
function InfTree(){
super();
}
public function inflate_trees_bits(c:Array, bb:Array, tb:Array, hp:Array, z:ZStream):int{
var result:int;
initWorkArea(19);
hn[0] = 0;
result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);
if (result == Z_DATA_ERROR){
z.msg = "oversubscribed dynamic bit lengths tree";
} else {
if ((((result == Z_BUF_ERROR)) || ((bb[0] == 0)))){
z.msg = "incomplete dynamic bit lengths tree";
result = Z_DATA_ERROR;
};
};
return (result);
}
private function initWorkArea(vsize:int):void{
var i:int;
if (hn == null){
hn = new Array();
v = new Array();
c = new Array();
r = new Array();
u = new Array();
x = new Array();
};
if (v.length < vsize){
v = new Array();
};
i = 0;
while (i < vsize) {
v[i] = 0;
i++;
};
i = 0;
while (i < (BMAX + 1)) {
c[i] = 0;
i++;
};
i = 0;
while (i < 3) {
r[i] = 0;
i++;
};
System.arrayCopy(c, 0, u, 0, BMAX);
System.arrayCopy(c, 0, x, 0, (BMAX + 1));
}
private function huft_build(b:Array, bindex:int, n:int, s:int, d:Array, e:Array, t:Array, m:Array, hp:Array, hn:Array, v:Array):int{
var a:int;
var f:int;
var g:int;
var h:int;
var i:int;
var j:int;
var k:int;
var l:int;
var mask:int;
var p:int;
var q:int;
var w:int;
var xp:int;
var y:int;
var z:int;
p = 0;
i = n;
do {
var _local27 = c;
var _local28 = b[(bindex + p)];
var _local29 = (_local27[_local28] + 1);
_local27[_local28] = _local29;
p++;
i--;
} while (i != 0);
if (c[0] == n){
t[0] = -1;
m[0] = 0;
return (Z_OK);
};
l = m[0];
j = 1;
while (j <= BMAX) {
if (c[j] != 0){
break;
};
j++;
};
k = j;
if (l < j){
l = j;
};
i = BMAX;
while (i != 0) {
if (c[i] != 0){
break;
};
i--;
};
g = i;
if (l > i){
l = i;
};
m[0] = l;
y = (1 << j);
while (j < i) {
y = (y - c[j]);
if (y < 0){
return (Z_DATA_ERROR);
};
j++;
y = (y << 1);
};
y = (y - c[i]);
if (y < 0){
return (Z_DATA_ERROR);
};
c[i] = (c[i] + y);
j = 0;
x[1] = j;
p = 1;
xp = 2;
while (--i != 0) {
j = (j + c[p]);
x[xp] = j;
xp++;
p++;
};
i = 0;
p = 0;
do {
j = b[(bindex + p)];
if (j != 0){
_local28 = x;
_local29 = j;
var _local30 = (_local28[_local29] + 1);
_local28[_local29] = _local30;
_local27 = _local28[_local29];
v[_local27] = i;
};
p++;
++i;
} while (i < n);
n = x[g];
i = 0;
x[0] = i;
p = 0;
h = -1;
w = -(l);
u[0] = 0;
q = 0;
z = 0;
while (k <= g) {
a = c[k];
while (a-- != 0) {
while (k > (w + l)) {
h++;
w = (w + l);
z = (g - w);
z = ((z)>l) ? l : z;
j = (k - w);
f = (1 << j);
if (f > (a + 1)){
f = (f - (a + 1));
xp = k;
if (j < z){
while (++j < z) {
f = (f << 1);
++xp;
if (f <= c[xp]){
break;
};
f = (f - c[xp]);
};
};
};
z = (1 << j);
if ((hn[0] + z) > MANY){
return (Z_DATA_ERROR);
};
q = hn[0];
u[h] = q;
hn[0] = (hn[0] + z);
if (h != 0){
x[h] = i;
r[0] = j;
r[1] = l;
j = (i >>> (w - l));
r[2] = int(((q - u[(h - 1)]) - j));
System.arrayCopy(r, 0, hp, ((u[(h - 1)] + j) * 3), 3);
} else {
t[0] = q;
};
};
r[1] = (k - w);
if (p >= n){
r[0] = (128 + 64);
} else {
if (v[p] < s){
r[0] = ((v[p] < 0x0100)) ? 0 : (32 + 64);
var _temp1 = p;
p = (p + 1);
r[2] = v[_temp1];
} else {
r[0] = ((e[(v[p] - s)] + 16) + 64);
var _temp2 = p;
p = (p + 1);
r[2] = d[(v[_temp2] - s)];
};
};
f = (1 << (k - w));
j = (i >>> w);
while (j < z) {
System.arrayCopy(r, 0, hp, ((q + j) * 3), 3);
j = (j + f);
};
j = (1 << (k - 1));
while ((i & j) != 0) {
i = (i ^ j);
j = (j >>> 1);
};
i = (i ^ j);
mask = ((1 << w) - 1);
while ((i & mask) != x[h]) {
h--;
w = (w - l);
mask = ((1 << w) - 1);
};
};
k++;
};
return ((((!((y == 0))) && (!((g == 1))))) ? Z_BUF_ERROR : Z_OK);
}
public function inflate_trees_dynamic(nl:int, nd:int, c:Array, bl:Array, bd:Array, tl:Array, td:Array, hp:Array, z:ZStream):int{
var result:int;
initWorkArea(288);
hn[0] = 0;
result = huft_build(c, 0, nl, 0x0101, cplens, cplext, tl, bl, hp, hn, v);
if (((!((result == Z_OK))) || ((bl[0] == 0)))){
if (result == Z_DATA_ERROR){
z.msg = "oversubscribed literal/length tree";
} else {
if (result != Z_MEM_ERROR){
z.msg = "incomplete literal/length tree";
result = Z_DATA_ERROR;
};
};
return (result);
};
initWorkArea(288);
result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v);
if (((!((result == Z_OK))) || ((((bd[0] == 0)) && ((nl > 0x0101)))))){
if (result == Z_DATA_ERROR){
z.msg = "oversubscribed distance tree";
} else {
if (result == Z_BUF_ERROR){
z.msg = "incomplete distance tree";
result = Z_DATA_ERROR;
} else {
if (result != Z_MEM_ERROR){
z.msg = "empty distance tree with lengths";
result = Z_DATA_ERROR;
};
};
};
return (result);
};
return (Z_OK);
}
public static function inflate_trees_fixed(bl:Array, bd:Array, tl:Array, td:Array, z:ZStream):int{
bl[0] = fixed_bl;
bd[0] = fixed_bd;
tl[0] = fixed_tl;
td[0] = fixed_td;
return (Z_OK);
}
}
}//package com.wirelust.as3zlib
Section 77
//JZlib (com.wirelust.as3zlib.JZlib)
package com.wirelust.as3zlib {
public final class JZlib {
public var version:String;// = "1.0.2"
public static var Z_MEM_ERROR:int = -4;
public static var Z_STREAM_END:int = 1;
public static var Z_DEFAULT_COMPRESSION:int = -1;
public static var Z_SYNC_FLUSH:int = 2;
public static var Z_VERSION_ERROR:int = -6;
public static var Z_NO_COMPRESSION:int = 0;
public static var Z_ERRNO:int = -1;
public static var Z_BEST_SPEED:int = 1;
public static var Z_DEFAULT_STRATEGY:int = 0;
public static var Z_BUF_ERROR:int = -5;
public static var Z_FINISH:int = 4;
public static var Z_FILTERED:int = 1;
public static var Z_PARTIAL_FLUSH:int = 1;
public static var Z_HUFFMAN_ONLY:int = 2;
public static var Z_DATA_ERROR:int = -3;
public static var Z_OK:int = 0;
public static var Z_NO_FLUSH:int = 0;
public static var Z_STREAM_ERROR:int = -2;
public static var Z_BEST_COMPRESSION:int = 9;
public static var Z_FULL_FLUSH:int = 3;
public static var Z_NEED_DICT:int = 2;
public function JZlib(){
super();
}
public static function get version():String{
return (version);
}
}
}//package com.wirelust.as3zlib
Section 78
//StaticTree (com.wirelust.as3zlib.StaticTree)
package com.wirelust.as3zlib {
import com.wirelust.as3zlib.*;
final class StaticTree {
var extra_base:int;
var max_length:int;
var elems:int;
var extra_bits:Array;
var static_tree:Array;
public static const MAX_BL_BITS:int = 7;
private static const MAX_BITS:int = 15;
private static const LITERALS:int = 0x0100;
private static const D_CODES:int = 30;
private static const LENGTH_CODES:int = 29;
private static const BL_CODES:int = 19;
private static const L_CODES:int = 286;
public static const static_dtree:Array = new Array(0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5);
public static const static_ltree:Array = new Array(12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 0xFF, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8);
static var static_l_desc:StaticTree = new StaticTree(static_ltree, Tree.extra_lbits, (LITERALS + 1), L_CODES, MAX_BITS);
;
static var static_bl_desc:StaticTree = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
;
static var static_d_desc:StaticTree = new StaticTree(static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
;
function StaticTree(static_tree:Array, extra_bits:Array, extra_base:int, elems:int, max_length:int){
super();
this.static_tree = static_tree;
this.extra_bits = extra_bits;
this.extra_base = extra_base;
this.elems = elems;
this.max_length = max_length;
}
}
}//package com.wirelust.as3zlib
Section 79
//System (com.wirelust.as3zlib.System)
package com.wirelust.as3zlib {
import flash.utils.*;
import flash.external.*;
public class System {
public function System(){
super();
}
public static function byteArrayCopy(src:ByteArray, srcPos:int, dest:ByteArray, destPos:int, length:int):void{
var i:int;
while (i < length) {
dest[(destPos + i)] = src[(srcPos + i)];
i++;
};
}
public static function arrayCopy(src:Array, srcPos:int, dest:Array, destPos:int, length:int):void{
var i:int;
while (i < length) {
dest[(destPos + i)] = src[(srcPos + i)];
i++;
};
}
public static function println(msg:String):void{
trace(msg);
ExternalInterface.call("console.log", msg);
}
}
}//package com.wirelust.as3zlib
Section 80
//Tree (com.wirelust.as3zlib.Tree)
package com.wirelust.as3zlib {
import com.wirelust.util.*;
public final class Tree {
public var dyn_tree:Array;
public var max_code:int;
public var stat_desc:StaticTree;
public static const extra_lbits:Array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0);
public static const REPZ_3_10:int = 17;
private static const D_CODES:int = 30;
public static const Buf_size:int = 16;
private static const BL_CODES:int = 19;
private static const L_CODES:int = 286;
public static const base_length:Array = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0);
public static const bl_order:Array = new Array(16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15);
public static const base_dist:Array = new Array(0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 0x0100, 384, 0x0200, 0x0300, 0x0400, 0x0600, 0x0800, 0x0C00, 0x1000, 0x1800, 0x2000, 0x3000, 0x4000, 0x6000);
public static const DIST_CODE_LEN:int = 0x0200;
public static const extra_blbits:Array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7);
public static const MAX_BL_BITS:int = 7;
private static const MAX_BITS:int = 15;
private static const LITERALS:int = 0x0100;
public static const _dist_code:Array = new Array(0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29);
public static const END_BLOCK:int = 0x0100;
private static const LENGTH_CODES:int = 29;
public static const _length_code:Array = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28);
public static const REP_3_6:int = 16;
private static const HEAP_SIZE:int = 573;
public static const REPZ_11_138:int = 18;
public static const extra_dbits:Array = new Array(0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13);
public function Tree(){
super();
}
public function build_tree(s:Deflate):void{
var n:int;
var m:int;
var node:int;
var tree:Array = dyn_tree;
var stree:Array = stat_desc.static_tree;
var elems:int = stat_desc.elems;
var max_code = -1;
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
n = 0;
while (n < elems) {
if (tree[(n * 2)] != 0){
var _local9 = ++s.heap_len;
max_code = n;
s.heap[_local9] = max_code;
s.depth[n] = 0;
} else {
tree[((n * 2) + 1)] = 0;
};
n++;
};
while (s.heap_len < 2) {
_local9 = ++s.heap_len;
node = (s.heap[_local9] = ((max_code < 2)) ? ++max_code;
max_code : 0);
tree[(node * 2)] = 1;
s.depth[node] = 0;
s.opt_len--;
if (stree != null){
s.static_len = (s.static_len - stree[((node * 2) + 1)]);
};
};
this.max_code = max_code;
n = (s.heap_len / 2);
while (n >= 1) {
s.pqdownheap(tree, n);
n--;
};
node = elems;
do {
n = s.heap[1];
s.heap[1] = s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m = s.heap[1];
_local9 = --s.heap_max;
s.heap[_local9] = n;
var _local10 = --s.heap_max;
s.heap[_local10] = m;
tree[(node * 2)] = (tree[(n * 2)] + tree[(m * 2)]);
s.depth[node] = (Math.max(s.depth[n], s.depth[m]) + 1);
tree[((n * 2) + 1)] = (tree[((m * 2) + 1)] = node);
var _temp1 = node;
node = (node + 1);
s.heap[1] = _temp1;
s.pqdownheap(tree, 1);
} while (s.heap_len >= 2);
_local9 = --s.heap_max;
s.heap[_local9] = s.heap[1];
gen_bitlen(s);
gen_codes(tree, max_code, s.bl_count);
}
public function gen_bitlen(s:Deflate):void{
var h:int;
var n:int;
var m:int;
var bits:int;
var xbits:int;
var f:Number;
var tree:Array = dyn_tree;
var stree:Array = stat_desc.static_tree;
var extra:Array = stat_desc.extra_bits;
var base:int = stat_desc.extra_base;
var max_length:int = stat_desc.max_length;
var overflow:int;
bits = 0;
while (bits <= MAX_BITS) {
s.bl_count[bits] = 0;
bits++;
};
tree[((s.heap[s.heap_max] * 2) + 1)] = 0;
h = (s.heap_max + 1);
while (h < HEAP_SIZE) {
n = s.heap[h];
bits = (tree[((tree[((n * 2) + 1)] * 2) + 1)] + 1);
if (bits > max_length){
bits = max_length;
overflow++;
};
tree[((n * 2) + 1)] = Cast.toShort(bits);
if (n > max_code){
} else {
var _local14 = s.bl_count;
var _local15 = bits;
var _local16 = (_local14[_local15] + 1);
_local14[_local15] = _local16;
xbits = 0;
if (n >= base){
xbits = extra[(n - base)];
};
f = tree[(n * 2)];
s.opt_len = (s.opt_len + (f * (bits + xbits)));
if (stree != null){
s.static_len = (s.static_len + (f * (stree[((n * 2) + 1)] + xbits)));
};
};
h++;
};
if (overflow == 0){
return;
};
do {
bits = (max_length - 1);
while (s.bl_count[bits] == 0) {
bits--;
};
_local14 = s.bl_count;
_local15 = bits;
_local16 = (_local14[_local15] - 1);
_local14[_local15] = _local16;
s.bl_count[(bits + 1)] = (s.bl_count[(bits + 1)] + 2);
_local14 = s.bl_count;
_local15 = max_length;
_local16 = (_local14[_local15] - 1);
_local14[_local15] = _local16;
overflow = (overflow - 2);
} while (overflow > 0);
bits = max_length;
while (bits != 0) {
n = s.bl_count[bits];
while (n != 0) {
--h;
m = s.heap[h];
if (m > max_code){
} else {
if (tree[((m * 2) + 1)] != bits){
s.opt_len = (s.opt_len + ((bits - tree[((m * 2) + 1)]) * tree[(m * 2)]));
tree[((m * 2) + 1)] = Cast.toShort(bits);
};
n--;
};
};
bits--;
};
}
public static function bi_reverse(code:int, len:int):int{
var res:int;
do {
res = (res | (code & 1));
code = (code >>> 1);
res = (res << 1);
--len;
} while (len > 0);
return ((res >>> 1));
}
public static function d_code(dist:int):int{
return (((dist < 0x0100)) ? _dist_code[dist] : _dist_code[(0x0100 + (dist >>> 7))]);
}
public static function gen_codes(tree:Array, max_code:int, bl_count:Array):void{
var bits:int;
var n:int;
var len:int;
var next_code:Array = new Array();
var code:Number = 0;
bits = 1;
while (bits <= MAX_BITS) {
code = ((code + bl_count[(bits - 1)]) << 1);
next_code[bits] = code;
bits++;
};
n = 0;
while (n <= max_code) {
len = tree[((n * 2) + 1)];
if (len == 0){
} else {
var _local9 = next_code;
var _local10 = len;
var _local11 = (_local9[_local10] + 1);
_local9[_local10] = _local11;
tree[(n * 2)] = bi_reverse(_local9[_local10], len);
};
n++;
};
}
}
}//package com.wirelust.as3zlib
Section 81
//ZStream (com.wirelust.as3zlib.ZStream)
package com.wirelust.as3zlib {
import flash.utils.*;
public final class ZStream {
public var total_in:Number;
public var msg:String;
public var next_out:ByteArray;
public var next_in_index:int;
public var istate:Inflate;
public var total_out:Number;
public var next_out_index:int;
public var adler:Number;
public var _adler:Adler32;
public var dstate:Deflate;
public var data_type:int;
public var next_in:ByteArray;
public var avail_in:int;
public var avail_out:int;
private static var Z_MEM_ERROR:int = -4;
private static var Z_STREAM_END:int = 1;
private static var DEF_WBITS:int = MAX_WBITS;
private static var Z_SYNC_FLUSH:int = 2;
private static var Z_VERSION_ERROR:int = -6;
private static var Z_BUF_ERROR:int = -5;
private static var Z_FINISH:int = 4;
private static var MAX_MEM_LEVEL:int = 9;
private static var Z_PARTIAL_FLUSH:int = 1;
private static var MAX_WBITS:int = 15;
private static var Z_DATA_ERROR:int = -3;
private static var Z_ERRNO:int = -1;
private static var Z_NO_FLUSH:int = 0;
private static var Z_STREAM_ERROR:int = -2;
private static var Z_OK:int = 0;
private static var Z_FULL_FLUSH:int = 3;
private static var Z_NEED_DICT:int = 2;
public function ZStream(){
_adler = new Adler32();
super();
}
public function read_buf(buf:ByteArray, start:int, size:int):int{
var len:int = avail_in;
if (len > size){
len = size;
};
if (len == 0){
return (0);
};
avail_in = (avail_in - len);
if (dstate.noheader == 0){
adler = _adler.adler32(adler, next_in, next_in_index, len);
};
System.byteArrayCopy(next_in, next_in_index, buf, start, len);
next_in_index = (next_in_index + len);
total_in = (total_in + len);
return (len);
}
public function inflate(f:int):int{
if (istate == null){
return (Z_STREAM_ERROR);
};
return (istate.inflate(this, f));
}
public function inflateSync():int{
if (istate == null){
return (Z_STREAM_ERROR);
};
return (istate.inflateSync(this));
}
public function inflateEnd():int{
if (istate == null){
return (Z_STREAM_ERROR);
};
var ret:int = istate.inflateEnd(this);
istate = null;
return (ret);
}
public function inflateSetDictionary(dictionary:ByteArray, dictLength:int):int{
if (istate == null){
return (Z_STREAM_ERROR);
};
return (istate.inflateSetDictionary(this, dictionary, dictLength));
}
public function deflateInit(level:int):int{
return (this.deflateInitWithIntInt(level, MAX_WBITS));
}
public function flush_pending():void{
var len:int = dstate.pending;
if (len > avail_out){
len = avail_out;
};
if (len == 0){
return;
};
if ((((((((dstate.pending_buf.length <= dstate.pending_out)) || ((next_out.length <= next_out_index)))) || ((dstate.pending_buf.length < (dstate.pending_out + len))))) || ((next_out.length < (next_out_index + len))))){
};
System.byteArrayCopy(dstate.pending_buf, dstate.pending_out, next_out, next_out_index, len);
next_out_index = (next_out_index + len);
dstate.pending_out = (dstate.pending_out + len);
total_out = (total_out + len);
avail_out = (avail_out - len);
dstate.pending = (dstate.pending - len);
if (dstate.pending == 0){
dstate.pending_out = 0;
dstate.pending_buf = new ByteArray();
};
}
public function deflateInitWithIntIntBoolean(level:int, bits:int, nowrap:Boolean):int{
dstate = new Deflate();
return (dstate.deflateInitWithBits(this, level, (nowrap) ? -(bits) : bits));
}
public function inflateInitWithWbits(w:int):int{
return (this.inflateInitWithWbitsNoWrap(w, false));
}
public function deflateInitWithIntInt(level:int, bits:int):int{
return (deflateInitWithIntIntBoolean(level, bits, false));
}
public function deflateInitWithBoolean(level:int, nowrap:Boolean):int{
return (this.deflateInitWithIntIntBoolean(level, MAX_WBITS, nowrap));
}
public function inflateInitWithNoWrap(nowrap:Boolean):int{
return (inflateInitWithWbitsNoWrap(DEF_WBITS, nowrap));
}
public function deflateParams(level:int, strategy:int):int{
if (dstate == null){
return (Z_STREAM_ERROR);
};
return (dstate.deflateParams(this, level, strategy));
}
public function inflateInitWithWbitsNoWrap(w:int, nowrap:Boolean):int{
istate = new Inflate();
return (istate.inflateInit(this, (nowrap) ? -(w) : w));
}
public function deflateEnd():int{
if (dstate == null){
return (Z_STREAM_ERROR);
};
var ret:int = dstate.deflateEnd();
dstate = null;
return (ret);
}
public function deflate(flush:int):int{
if (dstate == null){
return (Z_STREAM_ERROR);
};
return (dstate.deflate(this, flush));
}
public function free():void{
next_in = null;
next_out = null;
msg = null;
_adler = null;
}
public function deflateSetDictionary(dictionary:ByteArray, dictLength:int):int{
if (dstate == null){
return (Z_STREAM_ERROR);
};
return (dstate.deflateSetDictionary(this, dictionary, dictLength));
}
public function inflateInit():int{
return (inflateInitWithWbits(DEF_WBITS));
}
}
}//package com.wirelust.as3zlib
Section 82
//Cast (com.wirelust.util.Cast)
package com.wirelust.util {
public class Cast {
public function Cast(){
super();
}
public static function toShort(valueIn:int):int{
var unsignedValue:Number = (valueIn & 32767);
var signedValue:Number = unsignedValue;
if ((valueIn >> 15) == 1){
signedValue = (unsignedValue - 0x8000);
};
return (signedValue);
}
public static function toByte(valueIn:int):int{
var unsignedValue:Number = (valueIn & 127);
var signedValue:Number = unsignedValue;
var signedBit:Number = ((valueIn & 0xFF) >> 7);
if (signedBit == 1){
signedValue = (unsignedValue - 128);
};
return (signedValue);
}
}
}//package com.wirelust.util
Section 83
//BindabilityInfo (mx.binding.BindabilityInfo)
package mx.binding {
import mx.events.*;
import mx.core.*;
public class BindabilityInfo {
private var classChangeEvents:Object;
private var typeDescription:XML;
private var childChangeEvents:Object;
public static const METHOD:String = "method";
public static const ACCESSOR:String = "accessor";
public static const CHANGE_EVENT:String = "ChangeEvent";
public static const NON_COMMITTING_CHANGE_EVENT:String = "NonCommittingChangeEvent";
public static const BINDABLE:String = "Bindable";
mx_internal static const VERSION:String = "3.4.0.9271";
public static const MANAGED:String = "Managed";
public function BindabilityInfo(typeDescription:XML){
childChangeEvents = {};
super();
this.typeDescription = typeDescription;
}
private function addChangeEvents(metadata:XMLList, eventListObj:Object, isCommit:Boolean):void{
var md:XML;
var arg:XMLList;
var eventName:String;
for each (md in metadata) {
arg = md.arg;
if (arg.length() > 0){
eventName = arg[0].@value;
eventListObj[eventName] = isCommit;
} else {
trace((("warning: unconverted Bindable metadata in class '" + typeDescription.@name) + "'"));
};
};
}
private function getClassChangeEvents():Object{
if (!classChangeEvents){
classChangeEvents = {};
addBindabilityEvents(typeDescription.metadata, classChangeEvents);
if (typeDescription.metadata.(@name == MANAGED).length() > 0){
classChangeEvents[PropertyChangeEvent.PROPERTY_CHANGE] = true;
};
};
return (classChangeEvents);
}
private function addBindabilityEvents(metadata:XMLList, eventListObj:Object):void{
var metadata = metadata;
var eventListObj = eventListObj;
addChangeEvents(metadata.(@name == BINDABLE), eventListObj, true);
addChangeEvents(metadata.(@name == CHANGE_EVENT), eventListObj, true);
addChangeEvents(metadata.(@name == NON_COMMITTING_CHANGE_EVENT), eventListObj, false);
}
private function copyProps(from:Object, to:Object):Object{
var propName:String;
for (propName in from) {
to[propName] = from[propName];
};
return (to);
}
public function getChangeEvents(childName:String):Object{
var childDesc:XMLList;
var numChildren:int;
var childName = childName;
var changeEvents:Object = childChangeEvents[childName];
if (!changeEvents){
changeEvents = copyProps(getClassChangeEvents(), {});
childDesc = (typeDescription.accessor.(@name == childName) + typeDescription.method.(@name == childName));
numChildren = childDesc.length();
if (numChildren == 0){
if (!typeDescription.@dynamic){
trace((((("warning: no describeType entry for '" + childName) + "' on non-dynamic type '") + typeDescription.@name) + "'"));
};
} else {
if (numChildren > 1){
trace(((((("warning: multiple describeType entries for '" + childName) + "' on type '") + typeDescription.@name) + "':\n") + childDesc));
};
addBindabilityEvents(childDesc.metadata, changeEvents);
};
childChangeEvents[childName] = changeEvents;
};
return (changeEvents);
}
}
}//package mx.binding
Section 84
//CollectionViewError (mx.collections.errors.CollectionViewError)
package mx.collections.errors {
import mx.core.*;
public class CollectionViewError extends Error {
mx_internal static const VERSION:String = "3.4.0.9271";
public function CollectionViewError(message:String){
super(message);
}
}
}//package mx.collections.errors
Section 85
//CursorError (mx.collections.errors.CursorError)
package mx.collections.errors {
import mx.core.*;
public class CursorError extends Error {
mx_internal static const VERSION:String = "3.4.0.9271";
public function CursorError(message:String){
super(message);
}
}
}//package mx.collections.errors
Section 86
//ItemPendingError (mx.collections.errors.ItemPendingError)
package mx.collections.errors {
import mx.rpc.*;
import mx.core.*;
public class ItemPendingError extends Error {
private var _responders:Array;
mx_internal static const VERSION:String = "3.4.0.9271";
public function ItemPendingError(message:String){
super(message);
}
public function get responders():Array{
return (_responders);
}
public function addResponder(responder:IResponder):void{
if (!_responders){
_responders = [];
};
_responders.push(responder);
}
}
}//package mx.collections.errors
Section 87
//SortError (mx.collections.errors.SortError)
package mx.collections.errors {
import mx.core.*;
public class SortError extends Error {
mx_internal static const VERSION:String = "3.4.0.9271";
public function SortError(message:String){
super(message);
}
}
}//package mx.collections.errors
Section 88
//ArrayCollection (mx.collections.ArrayCollection)
package mx.collections {
import flash.utils.*;
import mx.core.*;
public class ArrayCollection extends ListCollectionView implements IExternalizable {
mx_internal static const VERSION:String = "3.4.0.9271";
public function ArrayCollection(source:Array=null){
super();
this.source = source;
}
public function set source(s:Array):void{
list = new ArrayList(s);
}
public function readExternal(input:IDataInput):void{
if ((list is IExternalizable)){
IExternalizable(list).readExternal(input);
} else {
source = (input.readObject() as Array);
};
}
public function writeExternal(output:IDataOutput):void{
if ((list is IExternalizable)){
IExternalizable(list).writeExternal(output);
} else {
output.writeObject(source);
};
}
public function get source():Array{
if (((list) && ((list is ArrayList)))){
return (ArrayList(list).source);
};
return (null);
}
}
}//package mx.collections
Section 89
//ArrayList (mx.collections.ArrayList)
package mx.collections {
import flash.events.*;
import flash.utils.*;
import mx.events.*;
import mx.resources.*;
import mx.utils.*;
import mx.core.*;
public class ArrayList extends EventDispatcher implements IList, IExternalizable, IPropertyChangeNotifier {
private var _source:Array;
private var _dispatchEvents:int;// = 0
private var _uid:String;
private var resourceManager:IResourceManager;
mx_internal static const VERSION:String = "3.4.0.9271";
public function ArrayList(source:Array=null){
resourceManager = ResourceManager.getInstance();
super();
disableEvents();
this.source = source;
enableEvents();
_uid = UIDUtil.createUID();
}
public function addAll(addList:IList):void{
addAllAt(addList, length);
}
public function readExternal(input:IDataInput):void{
source = input.readObject();
}
private function internalDispatchEvent(kind:String, item:Object=null, location:int=-1):void{
var event:CollectionEvent;
var objEvent:PropertyChangeEvent;
if (_dispatchEvents == 0){
if (hasEventListener(CollectionEvent.COLLECTION_CHANGE)){
event = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
event.kind = kind;
event.items.push(item);
event.location = location;
dispatchEvent(event);
};
if (((hasEventListener(PropertyChangeEvent.PROPERTY_CHANGE)) && ((((kind == CollectionEventKind.ADD)) || ((kind == CollectionEventKind.REMOVE)))))){
objEvent = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE);
objEvent.property = location;
if (kind == CollectionEventKind.ADD){
objEvent.newValue = item;
} else {
objEvent.oldValue = item;
};
dispatchEvent(objEvent);
};
};
}
public function removeAll():void{
var len:int;
var i:int;
if (length > 0){
len = length;
i = 0;
while (i < len) {
stopTrackUpdates(source[i]);
i++;
};
source.splice(0, length);
internalDispatchEvent(CollectionEventKind.RESET);
};
}
public function getItemIndex(item:Object):int{
return (ArrayUtil.getItemIndex(item, source));
}
public function removeItemAt(index:int):Object{
var message:String;
if ((((index < 0)) || ((index >= length)))){
message = resourceManager.getString("collections", "outOfBounds", [index]);
throw (new RangeError(message));
};
var removed:Object = source.splice(index, 1)[0];
stopTrackUpdates(removed);
internalDispatchEvent(CollectionEventKind.REMOVE, removed, index);
return (removed);
}
public function addAllAt(addList:IList, index:int):void{
var length:int = addList.length;
var i:int;
while (i < length) {
this.addItemAt(addList.getItemAt(i), (i + index));
i++;
};
}
public function itemUpdated(item:Object, property:Object=null, oldValue:Object=null, newValue:Object=null):void{
var event:PropertyChangeEvent = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE);
event.kind = PropertyChangeEventKind.UPDATE;
event.source = item;
event.property = property;
event.oldValue = oldValue;
event.newValue = newValue;
itemUpdateHandler(event);
}
public function get uid():String{
return (_uid);
}
public function writeExternal(output:IDataOutput):void{
output.writeObject(_source);
}
public function addItem(item:Object):void{
addItemAt(item, length);
}
public function toArray():Array{
return (source.concat());
}
public function get source():Array{
return (_source);
}
public function getItemAt(index:int, prefetch:int=0):Object{
var message:String;
if ((((index < 0)) || ((index >= length)))){
message = resourceManager.getString("collections", "outOfBounds", [index]);
throw (new RangeError(message));
};
return (source[index]);
}
public function set uid(value:String):void{
_uid = value;
}
public function setItemAt(item:Object, index:int):Object{
var message:String;
var hasCollectionListener:Boolean;
var hasPropertyListener:Boolean;
var updateInfo:PropertyChangeEvent;
var event:CollectionEvent;
if ((((index < 0)) || ((index >= length)))){
message = resourceManager.getString("collections", "outOfBounds", [index]);
throw (new RangeError(message));
};
var oldItem:Object = source[index];
source[index] = item;
stopTrackUpdates(oldItem);
startTrackUpdates(item);
if (_dispatchEvents == 0){
hasCollectionListener = hasEventListener(CollectionEvent.COLLECTION_CHANGE);
hasPropertyListener = hasEventListener(PropertyChangeEvent.PROPERTY_CHANGE);
if (((hasCollectionListener) || (hasPropertyListener))){
updateInfo = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE);
updateInfo.kind = PropertyChangeEventKind.UPDATE;
updateInfo.oldValue = oldItem;
updateInfo.newValue = item;
updateInfo.property = index;
};
if (hasCollectionListener){
event = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
event.kind = CollectionEventKind.REPLACE;
event.location = index;
event.items.push(updateInfo);
dispatchEvent(event);
};
if (hasPropertyListener){
dispatchEvent(updateInfo);
};
};
return (oldItem);
}
public function get length():int{
if (source){
return (source.length);
};
return (0);
}
private function disableEvents():void{
_dispatchEvents--;
}
protected function itemUpdateHandler(event:PropertyChangeEvent):void{
var objEvent:PropertyChangeEvent;
var index:uint;
internalDispatchEvent(CollectionEventKind.UPDATE, event);
if ((((_dispatchEvents == 0)) && (hasEventListener(PropertyChangeEvent.PROPERTY_CHANGE)))){
objEvent = PropertyChangeEvent(event.clone());
index = getItemIndex(event.target);
objEvent.property = ((index.toString() + ".") + event.property);
dispatchEvent(objEvent);
};
}
public function addItemAt(item:Object, index:int):void{
var message:String;
if ((((index < 0)) || ((index > length)))){
message = resourceManager.getString("collections", "outOfBounds", [index]);
throw (new RangeError(message));
};
source.splice(index, 0, item);
startTrackUpdates(item);
internalDispatchEvent(CollectionEventKind.ADD, item, index);
}
public function removeItem(item:Object):Boolean{
var index:int = getItemIndex(item);
var result = (index >= 0);
if (result){
removeItemAt(index);
};
return (result);
}
protected function stopTrackUpdates(item:Object):void{
if (((item) && ((item is IEventDispatcher)))){
IEventDispatcher(item).removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, itemUpdateHandler);
};
}
protected function startTrackUpdates(item:Object):void{
if (((item) && ((item is IEventDispatcher)))){
IEventDispatcher(item).addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, itemUpdateHandler, false, 0, true);
};
}
override public function toString():String{
if (source){
return (source.toString());
};
return (getQualifiedClassName(this));
}
private function enableEvents():void{
_dispatchEvents++;
if (_dispatchEvents > 0){
_dispatchEvents = 0;
};
}
public function set source(s:Array):void{
var i:int;
var len:int;
var event:CollectionEvent;
if (((_source) && (_source.length))){
len = _source.length;
i = 0;
while (i < len) {
stopTrackUpdates(_source[i]);
i++;
};
};
_source = (s) ? s : [];
len = _source.length;
i = 0;
while (i < len) {
startTrackUpdates(_source[i]);
i++;
};
if (_dispatchEvents == 0){
event = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
event.kind = CollectionEventKind.RESET;
dispatchEvent(event);
};
}
}
}//package mx.collections
Section 90
//CursorBookmark (mx.collections.CursorBookmark)
package mx.collections {
import mx.core.*;
public class CursorBookmark {
private var _value:Object;
mx_internal static const VERSION:String = "3.4.0.9271";
private static var _first:CursorBookmark;
private static var _last:CursorBookmark;
private static var _current:CursorBookmark;
public function CursorBookmark(value:Object){
super();
_value = value;
}
public function get value():Object{
return (_value);
}
public function getViewIndex():int{
return (-1);
}
public static function get LAST():CursorBookmark{
if (!_last){
_last = new CursorBookmark("${L}");
};
return (_last);
}
public static function get FIRST():CursorBookmark{
if (!_first){
_first = new CursorBookmark("${F}");
};
return (_first);
}
public static function get CURRENT():CursorBookmark{
if (!_current){
_current = new CursorBookmark("${C}");
};
return (_current);
}
}
}//package mx.collections
Section 91
//ICollectionView (mx.collections.ICollectionView)
package mx.collections {
import flash.events.*;
public interface ICollectionView extends IEventDispatcher {
function set filterFunction(mx.collections:ICollectionView/mx.collections:ICollectionView:length/get:Function):void;
function enableAutoUpdate():void;
function get length():int;
function disableAutoUpdate():void;
function itemUpdated(_arg1:Object, _arg2:Object=null, _arg3:Object=null, _arg4:Object=null):void;
function get filterFunction():Function;
function createCursor():IViewCursor;
function refresh():Boolean;
function set sort(mx.collections:ICollectionView/mx.collections:ICollectionView:length/get:Sort):void;
function get sort():Sort;
function contains(Function:Object):Boolean;
}
}//package mx.collections
Section 92
//IList (mx.collections.IList)
package mx.collections {
import flash.events.*;
public interface IList extends IEventDispatcher {
function addItem(C:\autobuild\galaga\frameworks\projects\framework\src;mx\collections;IList.as:Object):void;
function get length():int;
function addItemAt(_arg1:Object, _arg2:int):void;
function itemUpdated(_arg1:Object, _arg2:Object=null, _arg3:Object=null, _arg4:Object=null):void;
function getItemIndex(:Object):int;
function removeItemAt(mx.collections:IList/mx.collections:IList:length/get:int):Object;
function getItemAt(_arg1:int, _arg2:int=0):Object;
function removeAll():void;
function toArray():Array;
function setItemAt(_arg1:Object, _arg2:int):Object;
}
}//package mx.collections
Section 93
//ItemResponder (mx.collections.ItemResponder)
package mx.collections {
import mx.rpc.*;
import mx.core.*;
public class ItemResponder implements IResponder {
private var _faultHandler:Function;
private var _token:Object;
private var _resultHandler:Function;
mx_internal static const VERSION:String = "3.4.0.9271";
public function ItemResponder(result:Function, fault:Function, token:Object=null){
super();
_resultHandler = result;
_faultHandler = fault;
_token = token;
}
public function result(data:Object):void{
_resultHandler(data, _token);
}
public function fault(info:Object):void{
_faultHandler(info, _token);
}
}
}//package mx.collections
Section 94
//IViewCursor (mx.collections.IViewCursor)
package mx.collections {
import flash.events.*;
public interface IViewCursor extends IEventDispatcher {
function get current():Object;
function moveNext():Boolean;
function get view():ICollectionView;
function movePrevious():Boolean;
function remove():Object;
function findLast(:Object):Boolean;
function get beforeFirst():Boolean;
function get afterLast():Boolean;
function findAny(:Object):Boolean;
function get bookmark():CursorBookmark;
function findFirst(:Object):Boolean;
function seek(_arg1:CursorBookmark, _arg2:int=0, _arg3:int=0):void;
function insert(mx.collections:IViewCursor/mx.collections:IViewCursor:beforeFirst/get:Object):void;
}
}//package mx.collections
Section 95
//ListCollectionView (mx.collections.ListCollectionView)
package mx.collections {
import flash.events.*;
import flash.utils.*;
import mx.events.*;
import mx.resources.*;
import mx.utils.*;
import mx.core.*;
import mx.collections.errors.*;
public class ListCollectionView extends Proxy implements ICollectionView, IList, IMXMLObject {
private var autoUpdateCounter:int;
private var _list:IList;
private var _filterFunction:Function;
protected var localIndex:Array;
mx_internal var dispatchResetEvent:Boolean;// = true
private var pendingUpdates:Array;
private var resourceManager:IResourceManager;
private var eventDispatcher:EventDispatcher;
private var revision:int;
private var _sort:Sort;
mx_internal static const VERSION:String = "3.4.0.9271";
public function ListCollectionView(list:IList=null){
resourceManager = ResourceManager.getInstance();
super();
eventDispatcher = new EventDispatcher(this);
this.list = list;
}
private function handlePendingUpdates():void{
var pu:Array;
var singleUpdateEvent:CollectionEvent;
var i:int;
var event:CollectionEvent;
var j:int;
if (pendingUpdates){
pu = pendingUpdates;
pendingUpdates = null;
i = 0;
while (i < pu.length) {
event = pu[i];
if (event.kind == CollectionEventKind.UPDATE){
if (!singleUpdateEvent){
singleUpdateEvent = event;
} else {
j = 0;
while (j < event.items.length) {
singleUpdateEvent.items.push(event.items[j]);
j++;
};
};
} else {
listChangeHandler(event);
};
i++;
};
if (singleUpdateEvent){
listChangeHandler(singleUpdateEvent);
};
};
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void{
eventDispatcher.removeEventListener(type, listener, useCapture);
}
private function replaceItemsInView(items:Array, location:int, dispatch:Boolean=true):void{
var len:int;
var oldItems:Array;
var newItems:Array;
var i:int;
var propertyEvent:PropertyChangeEvent;
var event:CollectionEvent;
if (localIndex){
len = items.length;
oldItems = [];
newItems = [];
i = 0;
while (i < len) {
propertyEvent = items[i];
oldItems.push(propertyEvent.oldValue);
newItems.push(propertyEvent.newValue);
i++;
};
removeItemsFromView(oldItems, location, dispatch);
addItemsToView(newItems, location, dispatch);
} else {
event = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
event.kind = CollectionEventKind.REPLACE;
event.location = location;
event.items = items;
dispatchEvent(event);
};
}
private function getFilteredItemIndex(item:Object):int{
var prevItem:Object;
var len:int;
var j:int;
var loc:int = list.getItemIndex(item);
if (loc == 0){
return (0);
};
var i:int = (loc - 1);
while (i >= 0) {
prevItem = list.getItemAt(i);
if (filterFunction(prevItem)){
len = localIndex.length;
j = 0;
while (j < len) {
if (localIndex[j] == prevItem){
return ((j + 1));
};
j++;
};
};
i--;
};
return (0);
}
public function willTrigger(type:String):Boolean{
return (eventDispatcher.willTrigger(type));
}
mx_internal function findItem(values:Object, mode:String, insertIndex:Boolean=false):int{
var message:String;
if (!sort){
message = resourceManager.getString("collections", "itemNotFound");
throw (new CollectionViewError(message));
};
if (localIndex.length == 0){
return ((insertIndex) ? 0 : -1);
};
return (sort.findItem(localIndex, values, mode, insertIndex));
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function nextName(index:int):String{
return ((index - 1).toString());
}
public function removeAll():void{
var i:int;
var len:int = length;
if (len > 0){
if (localIndex){
i = (len - 1);
while (i >= 0) {
removeItemAt(i);
i--;
};
} else {
list.removeAll();
};
};
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function hasProperty(name):Boolean{
var n:Number;
var name = name;
if ((name is QName)){
name = name.localName;
};
var index = -1;
n = parseInt(String(name));
if (!isNaN(n)){
index = int(n);
};
//unresolved jump
var _slot1 = e;
if (index == -1){
return (false);
};
return ((((index >= 0)) && ((index < length))));
}
public function addAllAt(addList:IList, index:int):void{
var length:int = addList.length;
var i:int;
while (i < length) {
this.addItemAt(addList.getItemAt(i), (i + index));
i++;
};
}
public function getItemAt(index:int, prefetch:int=0):Object{
var message:String;
if ((((index < 0)) || ((index >= length)))){
message = resourceManager.getString("collections", "outOfBounds", [index]);
throw (new RangeError(message));
};
if (localIndex){
return (localIndex[index]);
};
if (list){
return (list.getItemAt(index, prefetch));
};
return (null);
}
private function moveItemInView(item:Object, dispatch:Boolean=true, updateEventItems:Array=null):void{
var removeLocation:int;
var i:int;
var addLocation:int;
var event:CollectionEvent;
if (localIndex){
removeLocation = -1;
i = 0;
while (i < localIndex.length) {
if (localIndex[i] == item){
removeLocation = i;
break;
};
i++;
};
if (removeLocation > -1){
localIndex.splice(removeLocation, 1);
};
addLocation = addItemsToView([item], removeLocation, false);
if (dispatch){
event = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
event.items.push(item);
if (((((updateEventItems) && ((addLocation == removeLocation)))) && ((addLocation > -1)))){
updateEventItems.push(item);
return;
};
if ((((addLocation > -1)) && ((removeLocation > -1)))){
event.kind = CollectionEventKind.MOVE;
event.location = addLocation;
event.oldLocation = removeLocation;
} else {
if (addLocation > -1){
event.kind = CollectionEventKind.ADD;
event.location = addLocation;
} else {
if (removeLocation > -1){
event.kind = CollectionEventKind.REMOVE;
event.location = removeLocation;
} else {
dispatch = false;
};
};
};
if (dispatch){
dispatchEvent(event);
};
};
};
}
public function contains(item:Object):Boolean{
return (!((getItemIndex(item) == -1)));
}
public function get sort():Sort{
return (_sort);
}
private function removeItemsFromView(items:Array, sourceLocation:int, dispatch:Boolean=true):void{
var i:int;
var item:Object;
var loc:int;
var event:CollectionEvent;
var removedItems:Array = (localIndex) ? [] : items;
var removeLocation:int = sourceLocation;
if (localIndex){
i = 0;
while (i < items.length) {
item = items[i];
loc = getItemIndex(item);
if (loc > -1){
localIndex.splice(loc, 1);
removedItems.push(item);
removeLocation = loc;
};
i++;
};
};
if (((dispatch) && ((removedItems.length > 0)))){
event = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
event.kind = CollectionEventKind.REMOVE;
event.location = (((!(localIndex)) || ((removedItems.length == 1)))) ? removeLocation : -1;
event.items = removedItems;
dispatchEvent(event);
};
}
public function get list():IList{
return (_list);
}
public function addItemAt(item:Object, index:int):void{
var message:String;
if ((((((index < 0)) || (!(list)))) || ((index > length)))){
message = resourceManager.getString("collections", "outOfBounds", [index]);
throw (new RangeError(message));
};
var listIndex:int = index;
if (((localIndex) && (sort))){
listIndex = list.length;
} else {
if (((localIndex) && (!((filterFunction == null))))){
if (listIndex == localIndex.length){
listIndex = list.length;
} else {
listIndex = list.getItemIndex(localIndex[index]);
};
};
};
list.addItemAt(item, listIndex);
}
public function itemUpdated(item:Object, property:Object=null, oldValue:Object=null, newValue:Object=null):void{
list.itemUpdated(item, property, oldValue, newValue);
}
private function populateLocalIndex():void{
if (list){
localIndex = list.toArray();
} else {
localIndex = [];
};
}
private function handlePropertyChangeEvents(events:Array):void{
var updatedItems:Array;
var updateEntry:Object;
var i:int;
var temp:Array;
var ctr:int;
var updateInfo:PropertyChangeEvent;
var item:Object;
var defaultMove:Boolean;
var j:int;
var l:int;
var k:int;
var ctr1:int;
var updateEvent:CollectionEvent;
var eventItems:Array = events;
if (((sort) || (!((filterFunction == null))))){
updatedItems = [];
i = 0;
while (i < events.length) {
updateInfo = events[i];
if (updateInfo.target){
item = updateInfo.target;
defaultMove = !((updateInfo.target == updateInfo.source));
} else {
item = updateInfo.source;
defaultMove = false;
};
j = 0;
while (j < updatedItems.length) {
if (updatedItems[j].item == item){
events = updatedItems[j].events;
l = events.length;
k = 0;
while (k < l) {
if (events[k].property != updateInfo.property){
events.push(updateInfo);
break;
};
k++;
};
break;
};
j++;
};
if (j < updatedItems.length){
updateEntry = updatedItems[j];
} else {
updateEntry = {item:item, move:defaultMove, events:[updateInfo]};
updatedItems.push(updateEntry);
};
updateEntry.move = ((((((updateEntry.move) || (filterFunction))) || (!(updateInfo.property)))) || (((sort) && (sort.propertyAffectsSort(String(updateInfo.property))))));
i++;
};
eventItems = [];
i = 0;
while (i < updatedItems.length) {
updateEntry = updatedItems[i];
if (updateEntry.move){
moveItemInView(updateEntry.item, updateEntry.item, eventItems);
} else {
eventItems.push(updateEntry.item);
};
i++;
};
temp = [];
ctr = 0;
while (ctr < eventItems.length) {
ctr1 = 0;
while (ctr1 < updatedItems.length) {
if (eventItems[ctr] == updatedItems[ctr1].item){
temp = temp.concat(updatedItems[ctr1].events);
};
ctr1++;
};
ctr++;
};
eventItems = temp;
};
if (eventItems.length > 0){
updateEvent = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
updateEvent.kind = CollectionEventKind.UPDATE;
updateEvent.items = eventItems;
dispatchEvent(updateEvent);
};
}
public function set sort(s:Sort):void{
_sort = s;
dispatchEvent(new Event("sortChanged"));
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function nextValue(index:int){
return (getItemAt((index - 1)));
}
public function setItemAt(item:Object, index:int):Object{
var message:String;
var oldItem:Object;
if ((((((index < 0)) || (!(list)))) || ((index >= length)))){
message = resourceManager.getString("collections", "outOfBounds", [index]);
throw (new RangeError(message));
};
var listIndex:int = index;
if (localIndex){
if (index > localIndex.length){
listIndex = list.length;
} else {
oldItem = localIndex[index];
listIndex = list.getItemIndex(oldItem);
};
};
return (list.setItemAt(item, listIndex));
}
mx_internal function getBookmark(index:int):ListCollectionViewBookmark{
var value:Object;
var message:String;
var index = index;
if ((((index < 0)) || ((index > length)))){
message = resourceManager.getString("collections", "invalidIndex", [index]);
throw (new CollectionViewError(message));
};
value = getItemAt(index);
//unresolved jump
var _slot1 = e;
value = null;
return (new ListCollectionViewBookmark(value, this, revision, index));
}
private function addItemsToView(items:Array, sourceLocation:int, dispatch:Boolean=true):int{
var loc:int;
var i:int;
var item:Object;
var message:String;
var event:CollectionEvent;
var addedItems:Array = (localIndex) ? [] : items;
var addLocation:int = sourceLocation;
var firstOne:Boolean;
if (localIndex){
loc = sourceLocation;
i = 0;
while (i < items.length) {
item = items[i];
if ((((filterFunction == null)) || (filterFunction(item)))){
if (sort){
loc = findItem(item, Sort.ANY_INDEX_MODE, true);
if (firstOne){
addLocation = loc;
firstOne = false;
};
} else {
loc = getFilteredItemIndex(item);
if (firstOne){
addLocation = loc;
firstOne = false;
};
};
if (((((sort) && (sort.unique))) && ((sort.compareFunction(item, localIndex[loc]) == 0)))){
message = resourceManager.getString("collections", "incorrectAddition");
throw (new CollectionViewError(message));
};
var _temp1 = loc;
loc = (loc + 1);
localIndex.splice(_temp1, 0, item);
addedItems.push(item);
} else {
addLocation = -1;
};
i++;
};
};
if (((localIndex) && ((addedItems.length > 1)))){
addLocation = -1;
};
if (((dispatch) && ((addedItems.length > 0)))){
event = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
event.kind = CollectionEventKind.ADD;
event.location = addLocation;
event.items = addedItems;
dispatchEvent(event);
};
return (addLocation);
}
public function addAll(addList:IList):void{
addAllAt(addList, length);
}
public function set list(value:IList):void{
var oldHasItems:Boolean;
var newHasItems:Boolean;
if (_list != value){
if (_list){
_list.removeEventListener(CollectionEvent.COLLECTION_CHANGE, listChangeHandler);
oldHasItems = (_list.length > 0);
};
_list = value;
if (_list){
_list.addEventListener(CollectionEvent.COLLECTION_CHANGE, listChangeHandler, false, 0, true);
newHasItems = (_list.length > 0);
};
if (((oldHasItems) || (newHasItems))){
reset();
};
dispatchEvent(new Event("listChanged"));
};
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void{
eventDispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
public function dispatchEvent(event:Event):Boolean{
return (eventDispatcher.dispatchEvent(event));
}
public function getItemIndex(item:Object):int{
var i:int;
var startIndex:int;
var endIndex:int;
var len:int;
if (sort){
startIndex = sort.findItem(localIndex, item, Sort.FIRST_INDEX_MODE);
if (startIndex == -1){
return (-1);
};
endIndex = sort.findItem(localIndex, item, Sort.LAST_INDEX_MODE);
i = startIndex;
while (i <= endIndex) {
if (localIndex[i] == item){
return (i);
};
i++;
};
return (-1);
} else {
if (filterFunction != null){
len = localIndex.length;
i = 0;
while (i < len) {
if (localIndex[i] == item){
return (i);
};
i++;
};
return (-1);
};
};
return (list.getItemIndex(item));
}
public function removeItemAt(index:int):Object{
var message:String;
var oldItem:Object;
if ((((index < 0)) || ((index >= length)))){
message = resourceManager.getString("collections", "outOfBounds", [index]);
throw (new RangeError(message));
};
var listIndex:int = index;
if (localIndex){
oldItem = localIndex[index];
listIndex = list.getItemIndex(oldItem);
};
return (list.removeItemAt(listIndex));
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function getProperty(name){
var n:Number;
var message:String;
var name = name;
if ((name is QName)){
name = name.localName;
};
var index = -1;
n = parseInt(String(name));
if (!isNaN(n)){
index = int(n);
};
//unresolved jump
var _slot1 = e;
if (index == -1){
message = resourceManager.getString("collections", "unknownProperty", [name]);
throw (new Error(message));
};
return (getItemAt(index));
}
public function enableAutoUpdate():void{
if (autoUpdateCounter > 0){
autoUpdateCounter--;
if (autoUpdateCounter == 0){
handlePendingUpdates();
};
};
}
mx_internal function reset():void{
var event:CollectionEvent;
internalRefresh(false);
if (dispatchResetEvent){
event = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
event.kind = CollectionEventKind.RESET;
dispatchEvent(event);
};
}
public function toArray():Array{
var ret:Array;
if (localIndex){
ret = localIndex.concat();
} else {
ret = list.toArray();
};
return (ret);
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function callProperty(name, ... _args){
return (null);
}
public function initialized(document:Object, id:String):void{
refresh();
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function setProperty(name, value):void{
var n:Number;
var message:String;
var name = name;
var value = value;
if ((name is QName)){
name = name.localName;
};
var index = -1;
n = parseInt(String(name));
if (!isNaN(n)){
index = int(n);
};
//unresolved jump
var _slot1 = e;
if (index == -1){
message = resourceManager.getString("collections", "unknownProperty", [name]);
throw (new Error(message));
};
setItemAt(value, index);
}
public function addItem(item:Object):void{
addItemAt(item, length);
}
private function internalRefresh(dispatch:Boolean):Boolean{
var tmp:Array;
var len:int;
var i:int;
var item:Object;
var refreshEvent:CollectionEvent;
var dispatch = dispatch;
if (((sort) || (!((filterFunction == null))))){
populateLocalIndex();
//unresolved jump
var _slot1 = pending;
_slot1.addResponder(new ItemResponder(function (data:Object, token:Object=null):void{
internalRefresh(dispatch);
}, function (info:Object, token:Object=null):void{
}));
return (false);
if (filterFunction != null){
tmp = [];
len = localIndex.length;
i = 0;
while (i < len) {
item = localIndex[i];
if (filterFunction(item)){
tmp.push(item);
};
i = (i + 1);
};
localIndex = tmp;
};
if (sort){
sort.sort(localIndex);
dispatch = true;
};
} else {
if (localIndex){
localIndex = null;
};
};
revision++;
pendingUpdates = null;
if (dispatch){
refreshEvent = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
refreshEvent.kind = CollectionEventKind.REFRESH;
dispatchEvent(refreshEvent);
};
return (true);
}
public function set filterFunction(f:Function):void{
_filterFunction = f;
dispatchEvent(new Event("filterFunctionChanged"));
}
mx_internal function getBookmarkIndex(bookmark:CursorBookmark):int{
var message:String;
if (((!((bookmark is ListCollectionViewBookmark))) || (!((ListCollectionViewBookmark(bookmark).view == this))))){
message = resourceManager.getString("collections", "bookmarkNotFound");
throw (new CollectionViewError(message));
};
var bm:ListCollectionViewBookmark = ListCollectionViewBookmark(bookmark);
if (bm.viewRevision != revision){
if ((((((bm.index < 0)) || ((bm.index >= length)))) || (!((getItemAt(bm.index) == bm.value))))){
bm.index = getItemIndex(bm.value);
};
bm.viewRevision = revision;
};
return (bm.index);
}
public function refresh():Boolean{
return (internalRefresh(true));
}
public function get filterFunction():Function{
return (_filterFunction);
}
public function createCursor():IViewCursor{
return (new ListCollectionViewCursor(this));
}
public function hasEventListener(type:String):Boolean{
return (eventDispatcher.hasEventListener(type));
}
public function get length():int{
if (localIndex){
return (localIndex.length);
};
if (list){
return (list.length);
};
return (0);
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function nextNameIndex(index:int):int{
return (((index < length)) ? (index + 1) : 0);
}
public function disableAutoUpdate():void{
autoUpdateCounter++;
}
public function toString():String{
if (localIndex){
return (ObjectUtil.toString(localIndex));
};
if (((list) && (Object(list).toString))){
return (Object(list).toString());
};
return (getQualifiedClassName(this));
}
private function listChangeHandler(event:CollectionEvent):void{
if (autoUpdateCounter > 0){
if (!pendingUpdates){
pendingUpdates = [];
};
pendingUpdates.push(event);
} else {
switch (event.kind){
case CollectionEventKind.ADD:
addItemsToView(event.items, event.location);
break;
case CollectionEventKind.RESET:
reset();
break;
case CollectionEventKind.REMOVE:
removeItemsFromView(event.items, event.location);
break;
case CollectionEventKind.REPLACE:
replaceItemsInView(event.items, event.location);
break;
case CollectionEventKind.UPDATE:
handlePropertyChangeEvents(event.items);
break;
default:
dispatchEvent(event);
};
};
}
}
}//package mx.collections
import flash.events.*;
import mx.events.*;
import mx.resources.*;
import mx.core.*;
import mx.collections.errors.*;
class ListCollectionViewBookmark extends CursorBookmark {
mx_internal var viewRevision:int;
mx_internal var index:int;
mx_internal var view:ListCollectionView;
private function ListCollectionViewBookmark(value:Object, view:ListCollectionView, viewRevision:int, index:int){
super(value);
this.view = view;
this.viewRevision = viewRevision;
this.index = index;
}
override public function getViewIndex():int{
return (view.getBookmarkIndex(this));
}
}
class ListCollectionViewCursor extends EventDispatcher implements IViewCursor {
private var _view:ListCollectionView;
private var invalid:Boolean;
private var resourceManager:IResourceManager;
private var currentIndex:int;
private var currentValue:Object;
private static const BEFORE_FIRST_INDEX:int = -1;
private static const AFTER_LAST_INDEX:int = -2;
private function ListCollectionViewCursor(view:ListCollectionView){
var view = view;
resourceManager = ResourceManager.getInstance();
super();
_view = view;
_view.addEventListener(CollectionEvent.COLLECTION_CHANGE, collectionEventHandler, false, 0, true);
currentIndex = ((view.length > 0)) ? 0 : AFTER_LAST_INDEX;
if (currentIndex == 0){
setCurrent(view.getItemAt(0), false);
//unresolved jump
var _slot1 = e;
currentIndex = BEFORE_FIRST_INDEX;
setCurrent(null, false);
};
}
public function findAny(values:Object):Boolean{
var index:int;
var values = values;
checkValid();
var lcView:ListCollectionView = ListCollectionView(view);
index = lcView.findItem(values, Sort.ANY_INDEX_MODE);
//unresolved jump
var _slot1 = e;
throw (new CursorError(_slot1.message));
if (index > -1){
currentIndex = index;
setCurrent(lcView.getItemAt(currentIndex));
};
return ((index > -1));
}
public function remove():Object{
var oldIndex:int;
var message:String;
if (((beforeFirst) || (afterLast))){
message = resourceManager.getString("collections", "invalidRemove");
throw (new CursorError(message));
};
oldIndex = currentIndex;
currentIndex++;
if (currentIndex >= view.length){
currentIndex = AFTER_LAST_INDEX;
setCurrent(null);
} else {
setCurrent(ListCollectionView(view).getItemAt(currentIndex));
//unresolved jump
var _slot1 = e;
setCurrent(null, false);
ListCollectionView(view).removeItemAt(oldIndex);
throw (_slot1);
};
var removed:Object = ListCollectionView(view).removeItemAt(oldIndex);
return (removed);
}
private function setCurrent(value:Object, dispatch:Boolean=true):void{
currentValue = value;
if (dispatch){
dispatchEvent(new FlexEvent(FlexEvent.CURSOR_UPDATE));
};
}
public function seek(bookmark:CursorBookmark, offset:int=0, prefetch:int=0):void{
var message:String;
var bookmark = bookmark;
var offset = offset;
var prefetch = prefetch;
checkValid();
if (view.length == 0){
currentIndex = AFTER_LAST_INDEX;
setCurrent(null, false);
return;
};
var newIndex:int = currentIndex;
if (bookmark == CursorBookmark.FIRST){
newIndex = 0;
} else {
if (bookmark == CursorBookmark.LAST){
newIndex = (view.length - 1);
} else {
if (bookmark != CursorBookmark.CURRENT){
newIndex = ListCollectionView(view).getBookmarkIndex(bookmark);
if (newIndex < 0){
setCurrent(null);
message = resourceManager.getString("collections", "bookmarkInvalid");
throw (new CursorError(message));
};
//unresolved jump
var _slot1 = bmError;
message = resourceManager.getString("collections", "bookmarkInvalid");
throw (new CursorError(message));
};
};
};
newIndex = (newIndex + offset);
var newCurrent:Object;
if (newIndex >= view.length){
currentIndex = AFTER_LAST_INDEX;
} else {
if (newIndex < 0){
currentIndex = BEFORE_FIRST_INDEX;
} else {
newCurrent = ListCollectionView(view).getItemAt(newIndex, prefetch);
currentIndex = newIndex;
};
};
setCurrent(newCurrent);
}
public function insert(item:Object):void{
var insertIndex:int;
var message:String;
if (afterLast){
insertIndex = view.length;
} else {
if (beforeFirst){
if (view.length > 0){
message = resourceManager.getString("collections", "invalidInsert");
throw (new CursorError(message));
};
insertIndex = 0;
} else {
insertIndex = currentIndex;
};
};
ListCollectionView(view).addItemAt(item, insertIndex);
}
public function get afterLast():Boolean{
checkValid();
return ((((currentIndex == AFTER_LAST_INDEX)) || ((view.length == 0))));
}
private function checkValid():void{
var message:String;
if (invalid){
message = resourceManager.getString("collections", "invalidCursor");
throw (new CursorError(message));
};
}
private function collectionEventHandler(event:CollectionEvent):void{
var event = event;
switch (event.kind){
case CollectionEventKind.ADD:
if (event.location <= currentIndex){
currentIndex = (currentIndex + event.items.length);
};
break;
case CollectionEventKind.REMOVE:
if (event.location < currentIndex){
currentIndex = (currentIndex - event.items.length);
} else {
if (event.location == currentIndex){
if (currentIndex < view.length){
setCurrent(ListCollectionView(view).getItemAt(currentIndex));
//unresolved jump
var _slot1 = error;
setCurrent(null, false);
} else {
currentIndex = AFTER_LAST_INDEX;
setCurrent(null);
};
};
};
break;
case CollectionEventKind.MOVE:
if (event.oldLocation == currentIndex){
currentIndex = event.location;
} else {
if (event.oldLocation < currentIndex){
currentIndex = (currentIndex - event.items.length);
};
if (event.location <= currentIndex){
currentIndex = (currentIndex + event.items.length);
};
};
break;
case CollectionEventKind.REFRESH:
if (!((beforeFirst) || (afterLast))){
currentIndex = ListCollectionView(view).getItemIndex(currentValue);
if (currentIndex == -1){
setCurrent(null);
};
};
break;
case CollectionEventKind.REPLACE:
if (event.location == currentIndex){
setCurrent(ListCollectionView(view).getItemAt(currentIndex));
//unresolved jump
var _slot1 = error;
setCurrent(null, false);
};
break;
case CollectionEventKind.RESET:
currentIndex = BEFORE_FIRST_INDEX;
setCurrent(null);
break;
};
}
public function moveNext():Boolean{
if (afterLast){
return (false);
};
var tempIndex:int = (beforeFirst) ? 0 : (currentIndex + 1);
if (tempIndex >= view.length){
tempIndex = AFTER_LAST_INDEX;
setCurrent(null);
} else {
setCurrent(ListCollectionView(view).getItemAt(tempIndex));
};
currentIndex = tempIndex;
return (!(afterLast));
}
public function get view():ICollectionView{
checkValid();
return (_view);
}
public function movePrevious():Boolean{
if (beforeFirst){
return (false);
};
var tempIndex:int = (afterLast) ? (view.length - 1) : (currentIndex - 1);
if (tempIndex == -1){
tempIndex = BEFORE_FIRST_INDEX;
setCurrent(null);
} else {
setCurrent(ListCollectionView(view).getItemAt(tempIndex));
};
currentIndex = tempIndex;
return (!(beforeFirst));
}
public function findLast(values:Object):Boolean{
var index:int;
var values = values;
checkValid();
var lcView:ListCollectionView = ListCollectionView(view);
index = lcView.findItem(values, Sort.LAST_INDEX_MODE);
//unresolved jump
var _slot1 = sortError;
throw (new CursorError(_slot1.message));
if (index > -1){
currentIndex = index;
setCurrent(lcView.getItemAt(currentIndex));
};
return ((index > -1));
}
public function get beforeFirst():Boolean{
checkValid();
return ((((currentIndex == BEFORE_FIRST_INDEX)) || ((view.length == 0))));
}
public function get bookmark():CursorBookmark{
checkValid();
if ((((view.length == 0)) || (beforeFirst))){
return (CursorBookmark.FIRST);
};
if (afterLast){
return (CursorBookmark.LAST);
};
return (ListCollectionView(view).getBookmark(currentIndex));
}
public function findFirst(values:Object):Boolean{
var index:int;
var values = values;
checkValid();
var lcView:ListCollectionView = ListCollectionView(view);
index = lcView.findItem(values, Sort.FIRST_INDEX_MODE);
//unresolved jump
var _slot1 = sortError;
throw (new CursorError(_slot1.message));
if (index > -1){
currentIndex = index;
setCurrent(lcView.getItemAt(currentIndex));
};
return ((index > -1));
}
public function get current():Object{
checkValid();
return (currentValue);
}
}
Section 96
//Sort (mx.collections.Sort)
package mx.collections {
import flash.events.*;
import mx.resources.*;
import mx.utils.*;
import mx.core.*;
import mx.collections.errors.*;
public class Sort extends EventDispatcher {
private var noFieldsDescending:Boolean;// = false
private var usingCustomCompareFunction:Boolean;
private var defaultEmptyField:SortField;
private var _fields:Array;
private var _compareFunction:Function;
private var _unique:Boolean;
private var fieldList:Array;
private var resourceManager:IResourceManager;
public static const ANY_INDEX_MODE:String = "any";
mx_internal static const VERSION:String = "3.4.0.9271";
public static const LAST_INDEX_MODE:String = "last";
public static const FIRST_INDEX_MODE:String = "first";
public function Sort(){
resourceManager = ResourceManager.getInstance();
fieldList = [];
super();
}
public function get unique():Boolean{
return (_unique);
}
public function get compareFunction():Function{
return ((usingCustomCompareFunction) ? _compareFunction : internalCompare);
}
public function set unique(value:Boolean):void{
_unique = value;
}
public function sort(items:Array):void{
var fixedCompareFunction:Function;
var message:String;
var uniqueRet1:Object;
var fields:Array;
var i:int;
var sortArgs:Object;
var uniqueRet2:Object;
var items = items;
if (((!(items)) || ((items.length <= 1)))){
return;
};
if (usingCustomCompareFunction){
fixedCompareFunction = function (a:Object, b:Object):int{
return (compareFunction(a, b, _fields));
};
if (unique){
uniqueRet1 = items.sort(fixedCompareFunction, Array.UNIQUESORT);
if (uniqueRet1 == 0){
message = resourceManager.getString("collections", "nonUnique");
throw (new SortError(message));
};
} else {
items.sort(fixedCompareFunction);
};
} else {
fields = this.fields;
if (((fields) && ((fields.length > 0)))){
sortArgs = initSortFields(items[0], true);
if (unique){
if (((sortArgs) && ((fields.length == 1)))){
uniqueRet2 = items.sortOn(sortArgs.fields[0], (sortArgs.options[0] | Array.UNIQUESORT));
} else {
uniqueRet2 = items.sort(internalCompare, Array.UNIQUESORT);
};
if (uniqueRet2 == 0){
message = resourceManager.getString("collections", "nonUnique");
throw (new SortError(message));
};
} else {
if (sortArgs){
items.sortOn(sortArgs.fields, sortArgs.options);
} else {
items.sort(internalCompare);
};
};
} else {
items.sort(internalCompare);
};
};
}
public function propertyAffectsSort(property:String):Boolean{
var field:SortField;
if (((usingCustomCompareFunction) || (!(fields)))){
return (true);
};
var i:int;
while (i < fields.length) {
field = fields[i];
if ((((field.name == property)) || (field.usingCustomCompareFunction))){
return (true);
};
i++;
};
return (false);
}
private function internalCompare(a:Object, b:Object, fields:Array=null):int{
var i:int;
var len:int;
var sf:SortField;
var result:int;
if (!_fields){
result = noFieldsCompare(a, b);
} else {
i = 0;
len = (fields) ? fields.length : _fields.length;
while ((((result == 0)) && ((i < len)))) {
sf = SortField(_fields[i]);
result = sf.internalCompare(a, b);
i++;
};
};
return (result);
}
public function reverse():void{
var i:int;
if (fields){
i = 0;
while (i < fields.length) {
SortField(fields[i]).reverse();
i++;
};
};
noFieldsDescending = !(noFieldsDescending);
}
private function noFieldsCompare(a:Object, b:Object, fields:Array=null):int{
var message:String;
var a = a;
var b = b;
var fields = fields;
if (!defaultEmptyField){
defaultEmptyField = new SortField();
defaultEmptyField.initCompare(a);
//unresolved jump
var _slot1 = e;
message = resourceManager.getString("collections", "noComparator", [a]);
throw (new SortError(message));
};
var result:int = defaultEmptyField.compareFunction(a, b);
if (noFieldsDescending){
result = (result * -1);
};
return (result);
}
public function findItem(items:Array, values:Object, mode:String, returnInsertionIndex:Boolean=false, compareFunction:Function=null):int{
var compareForFind:Function;
var fieldsForCompare:Array;
var message:String;
var index:int;
var fieldName:String;
var hadPreviousFieldName:Boolean;
var i:int;
var hasFieldName:Boolean;
var objIndex:int;
var match:Boolean;
var prevCompare:int;
var nextCompare:int;
var items = items;
var values = values;
var mode = mode;
var returnInsertionIndex = returnInsertionIndex;
var compareFunction = compareFunction;
if (!items){
message = resourceManager.getString("collections", "noItems");
throw (new SortError(message));
};
if (items.length == 0){
return ((returnInsertionIndex) ? 1 : -1);
};
if (compareFunction == null){
compareForFind = this.compareFunction;
if (((values) && ((fieldList.length > 0)))){
fieldsForCompare = [];
hadPreviousFieldName = true;
i = 0;
for (;i < fieldList.length;if (hasFieldName){
if (!hadPreviousFieldName){
message = resourceManager.getString("collections", "findCondition", [fieldName]);
throw (new SortError(message));
};
fieldsForCompare.push(fieldName);
} else {
hadPreviousFieldName = false;
}, continue, fieldsForCompare.push(null), (i = (i + 1))) {
fieldName = fieldList[i];
//unresolved if
hasFieldName = !((values[fieldName] === undefined));
continue;
var _slot1 = e;
hasFieldName = false;
};
if (fieldsForCompare.length == 0){
message = resourceManager.getString("collections", "findRestriction");
throw (new SortError(message));
};
initSortFields(items[0]);
//unresolved jump
var _slot1 = initSortError;
};
} else {
compareForFind = compareFunction;
};
var found:Boolean;
var objFound:Boolean;
index = 0;
var lowerBound:int;
var upperBound:int = (items.length - 1);
var obj:Object;
var direction = 1;
while (((!(objFound)) && ((lowerBound <= upperBound)))) {
index = Math.round(((lowerBound + upperBound) / 2));
obj = items[index];
direction = (fieldsForCompare) ? compareForFind(values, obj, fieldsForCompare) : compareForFind(values, obj);
switch (direction){
case -1:
upperBound = (index - 1);
break;
case 0:
objFound = true;
switch (mode){
case ANY_INDEX_MODE:
found = true;
break;
case FIRST_INDEX_MODE:
found = (index == lowerBound);
objIndex = (index - 1);
match = true;
while (((((match) && (!(found)))) && ((objIndex >= lowerBound)))) {
obj = items[objIndex];
prevCompare = (fieldsForCompare) ? compareForFind(values, obj, fieldsForCompare) : compareForFind(values, obj);
match = (prevCompare == 0);
if (((!(match)) || (((match) && ((objIndex == lowerBound)))))){
found = true;
index = (objIndex + (match) ? 0 : 1);
};
objIndex = (objIndex - 1);
};
break;
case LAST_INDEX_MODE:
found = (index == upperBound);
objIndex = (index + 1);
match = true;
while (((((match) && (!(found)))) && ((objIndex <= upperBound)))) {
obj = items[objIndex];
nextCompare = (fieldsForCompare) ? compareForFind(values, obj, fieldsForCompare) : compareForFind(values, obj);
match = (nextCompare == 0);
if (((!(match)) || (((match) && ((objIndex == upperBound)))))){
found = true;
index = (objIndex - (match) ? 0 : 1);
};
objIndex = (objIndex + 1);
};
break;
default:
message = resourceManager.getString("collections", "unknownMode");
throw (new SortError(message));
};
break;
case 1:
lowerBound = (index + 1);
break;
};
};
if (((!(found)) && (!(returnInsertionIndex)))){
return (-1);
};
return (((direction)>0) ? (index + 1) : index);
}
private function initSortFields(item:Object, buildArraySortArgs:Boolean=false):Object{
var i:int;
var field:SortField;
var options:int;
var arraySortArgs:Object;
i = 0;
while (i < fields.length) {
SortField(fields[i]).initCompare(item);
i++;
};
if (buildArraySortArgs){
arraySortArgs = {fields:[], options:[]};
i = 0;
while (i < fields.length) {
field = fields[i];
options = field.getArraySortOnOptions();
if (options == -1){
return (null);
};
arraySortArgs.fields.push(field.name);
arraySortArgs.options.push(options);
i++;
};
};
return (arraySortArgs);
}
public function set fields(value:Array):void{
var field:SortField;
var i:int;
_fields = value;
fieldList = [];
if (_fields){
i = 0;
while (i < _fields.length) {
field = SortField(_fields[i]);
fieldList.push(field.name);
i++;
};
};
dispatchEvent(new Event("fieldsChanged"));
}
public function get fields():Array{
return (_fields);
}
public function set compareFunction(value:Function):void{
_compareFunction = value;
usingCustomCompareFunction = !((_compareFunction == null));
}
override public function toString():String{
return (ObjectUtil.toString(this));
}
}
}//package mx.collections
Section 97
//SortField (mx.collections.SortField)
package mx.collections {
import flash.events.*;
import mx.resources.*;
import mx.utils.*;
import mx.core.*;
import mx.collections.errors.*;
public class SortField extends EventDispatcher {
private var _caseInsensitive:Boolean;
private var _numeric:Object;
private var _descending:Boolean;
private var _compareFunction:Function;
private var _usingCustomCompareFunction:Boolean;
private var _name:String;
private var resourceManager:IResourceManager;
mx_internal static const VERSION:String = "3.4.0.9271";
public function SortField(name:String=null, caseInsensitive:Boolean=false, descending:Boolean=false, numeric:Object=null){
resourceManager = ResourceManager.getInstance();
super();
_name = name;
_caseInsensitive = caseInsensitive;
_descending = descending;
_numeric = numeric;
_compareFunction = stringCompare;
}
public function get caseInsensitive():Boolean{
return (_caseInsensitive);
}
mx_internal function get usingCustomCompareFunction():Boolean{
return (_usingCustomCompareFunction);
}
public function set caseInsensitive(value:Boolean):void{
if (value != _caseInsensitive){
_caseInsensitive = value;
dispatchEvent(new Event("caseInsensitiveChanged"));
};
}
public function get name():String{
return (_name);
}
public function get numeric():Object{
return (_numeric);
}
public function set name(n:String):void{
_name = n;
dispatchEvent(new Event("nameChanged"));
}
private function numericCompare(a:Object, b:Object):int{
var fa:Number;
var fb:Number;
var a = a;
var b = b;
fa = ((_name == null)) ? Number(a) : Number(a[_name]);
//unresolved jump
var _slot1 = error;
fb = ((_name == null)) ? Number(b) : Number(b[_name]);
//unresolved jump
var _slot1 = error;
return (ObjectUtil.numericCompare(fa, fb));
}
public function set numeric(value:Object):void{
if (_numeric != value){
_numeric = value;
dispatchEvent(new Event("numericChanged"));
};
}
private function stringCompare(a:Object, b:Object):int{
var fa:String;
var fb:String;
var a = a;
var b = b;
fa = ((_name == null)) ? String(a) : String(a[_name]);
//unresolved jump
var _slot1 = error;
fb = ((_name == null)) ? String(b) : String(b[_name]);
//unresolved jump
var _slot1 = error;
return (ObjectUtil.stringCompare(fa, fb, _caseInsensitive));
}
public function get compareFunction():Function{
return (_compareFunction);
}
public function reverse():void{
descending = !(descending);
}
mx_internal function getArraySortOnOptions():int{
if (((((((usingCustomCompareFunction) || ((name == null)))) || ((_compareFunction == xmlCompare)))) || ((_compareFunction == dateCompare)))){
return (-1);
};
var options:int;
if (caseInsensitive){
options = (options | Array.CASEINSENSITIVE);
};
if (descending){
options = (options | Array.DESCENDING);
};
if ((((numeric == true)) || ((_compareFunction == numericCompare)))){
options = (options | Array.NUMERIC);
};
return (options);
}
private function dateCompare(a:Object, b:Object):int{
var fa:Date;
var fb:Date;
var a = a;
var b = b;
fa = ((_name == null)) ? (a as Date) : (a[_name] as Date);
//unresolved jump
var _slot1 = error;
fb = ((_name == null)) ? (b as Date) : (b[_name] as Date);
//unresolved jump
var _slot1 = error;
return (ObjectUtil.dateCompare(fa, fb));
}
mx_internal function internalCompare(a:Object, b:Object):int{
var result:int = compareFunction(a, b);
if (descending){
result = (result * -1);
};
return (result);
}
override public function toString():String{
return (ObjectUtil.toString(this));
}
private function nullCompare(a:Object, b:Object):int{
var value:Object;
var left:Object;
var right:Object;
var message:String;
var a = a;
var b = b;
var found:Boolean;
if ((((a == null)) && ((b == null)))){
return (0);
};
if (_name){
left = a[_name];
//unresolved jump
var _slot1 = error;
right = b[_name];
//unresolved jump
var _slot1 = error;
};
if ((((left == null)) && ((right == null)))){
return (0);
};
if (left == null){
left = a;
};
if (right == null){
right = b;
};
var typeLeft = typeof(left);
var typeRight = typeof(right);
if ((((typeLeft == "string")) || ((typeRight == "string")))){
found = true;
_compareFunction = stringCompare;
} else {
if ((((typeLeft == "object")) || ((typeRight == "object")))){
if ((((left is Date)) || ((right is Date)))){
found = true;
_compareFunction = dateCompare;
};
} else {
if ((((typeLeft == "xml")) || ((typeRight == "xml")))){
found = true;
_compareFunction = xmlCompare;
} else {
if ((((((((typeLeft == "number")) || ((typeRight == "number")))) || ((typeLeft == "boolean")))) || ((typeRight == "boolean")))){
found = true;
_compareFunction = numericCompare;
};
};
};
};
if (found){
return (_compareFunction(left, right));
};
message = resourceManager.getString("collections", "noComparatorSortField", [name]);
throw (new SortError(message));
}
public function set descending(value:Boolean):void{
if (_descending != value){
_descending = value;
dispatchEvent(new Event("descendingChanged"));
};
}
mx_internal function initCompare(obj:Object):void{
var value:Object;
var typ:String;
var test:String;
var obj = obj;
if (!usingCustomCompareFunction){
if (numeric == true){
_compareFunction = numericCompare;
} else {
if (((caseInsensitive) || ((numeric == false)))){
_compareFunction = stringCompare;
} else {
if (_name){
value = obj[_name];
//unresolved jump
var _slot1 = error;
};
if (value == null){
value = obj;
};
typ = typeof(value);
switch (typ){
case "string":
_compareFunction = stringCompare;
break;
case "object":
if ((value is Date)){
_compareFunction = dateCompare;
} else {
_compareFunction = stringCompare;
test = value.toString();
//unresolved jump
var _slot1 = error2;
if (((!(test)) || ((test == "[object Object]")))){
_compareFunction = nullCompare;
};
};
break;
case "xml":
_compareFunction = xmlCompare;
break;
case "boolean":
case "number":
_compareFunction = numericCompare;
break;
};
};
};
};
}
public function get descending():Boolean{
return (_descending);
}
public function set compareFunction(c:Function):void{
_compareFunction = c;
_usingCustomCompareFunction = !((c == null));
}
private function xmlCompare(a:Object, b:Object):int{
var sa:String;
var sb:String;
var a = a;
var b = b;
sa = ((_name == null)) ? a.toString() : a[_name].toString();
//unresolved jump
var _slot1 = error;
sb = ((_name == null)) ? b.toString() : b[_name].toString();
//unresolved jump
var _slot1 = error;
if (numeric == true){
return (ObjectUtil.numericCompare(parseFloat(sa), parseFloat(sb)));
};
return (ObjectUtil.stringCompare(sa, sb, _caseInsensitive));
}
}
}//package mx.collections
Section 98
//IButton (mx.core.IButton)
package mx.core {
public interface IButton extends IUIComponent {
function get emphasized():Boolean;
function set emphasized(C:\autobuild\galaga\frameworks\projects\framework\src;mx\core;IButton.as:Boolean):void;
function callLater(_arg1:Function, _arg2:Array=null):void;
}
}//package mx.core
Section 99
//IChildList (mx.core.IChildList)
package mx.core {
import flash.display.*;
import flash.geom.*;
public interface IChildList {
function get numChildren():int;
function removeChild(C:\autobuild\galaga\frameworks\projects\framework\src;mx\core;IChildList.as:DisplayObject):DisplayObject;
function getChildByName(C:\autobuild\galaga\frameworks\projects\framework\src;mx\core;IChildList.as:String):DisplayObject;
function removeChildAt(C:\autobuild\galaga\frameworks\projects\framework\src;mx\core;IChildList.as:int):DisplayObject;
function getChildIndex(:DisplayObject):int;
function addChildAt(_arg1:DisplayObject, _arg2:int):DisplayObject;
function getObjectsUnderPoint(child:Point):Array;
function setChildIndex(_arg1:DisplayObject, _arg2:int):void;
function getChildAt(C:\autobuild\galaga\frameworks\projects\framework\src;mx\core;IChildList.as:int):DisplayObject;
function addChild(C:\autobuild\galaga\frameworks\projects\framework\src;mx\core;IChildList.as:DisplayObject):DisplayObject;
function contains(flash.display:DisplayObject):Boolean;
}
}//package mx.core
Section 100
//IFlexDisplayObject (mx.core.IFlexDisplayObject)
package mx.core {
import flash.events.*;
import flash.display.*;
import flash.geom.*;
import flash.accessibility.*;
public interface IFlexDisplayObject extends IBitmapDrawable, IEventDispatcher {
function get visible():Boolean;
function get rotation():Number;
function localToGlobal(void:Point):Point;
function get name():String;
function set width(flash.display:Number):void;
function get measuredHeight():Number;
function get blendMode():String;
function get scale9Grid():Rectangle;
function set name(flash.display:String):void;
function set scaleX(flash.display:Number):void;
function set scaleY(flash.display:Number):void;
function get measuredWidth():Number;
function get accessibilityProperties():AccessibilityProperties;
function set scrollRect(flash.display:Rectangle):void;
function get cacheAsBitmap():Boolean;
function globalToLocal(void:Point):Point;
function get height():Number;
function set blendMode(flash.display:String):void;
function get parent():DisplayObjectContainer;
function getBounds(String:DisplayObject):Rectangle;
function get opaqueBackground():Object;
function set scale9Grid(flash.display:Rectangle):void;
function setActualSize(_arg1:Number, _arg2:Number):void;
function set alpha(flash.display:Number):void;
function set accessibilityProperties(flash.display:AccessibilityProperties):void;
function get width():Number;
function hitTestPoint(_arg1:Number, _arg2:Number, _arg3:Boolean=false):Boolean;
function set cacheAsBitmap(flash.display:Boolean):void;
function get scaleX():Number;
function get scaleY():Number;
function get scrollRect():Rectangle;
function get mouseX():Number;
function get mouseY():Number;
function set height(flash.display:Number):void;
function set mask(flash.display:DisplayObject):void;
function getRect(String:DisplayObject):Rectangle;
function get alpha():Number;
function set transform(flash.display:Transform):void;
function move(_arg1:Number, _arg2:Number):void;
function get loaderInfo():LoaderInfo;
function get root():DisplayObject;
function hitTestObject(mx.core:IFlexDisplayObject/mx.core:IFlexDisplayObject:stage/get:DisplayObject):Boolean;
function set opaqueBackground(flash.display:Object):void;
function set visible(flash.display:Boolean):void;
function get mask():DisplayObject;
function set x(flash.display:Number):void;
function set y(flash.display:Number):void;
function get transform():Transform;
function set filters(flash.display:Array):void;
function get x():Number;
function get y():Number;
function get filters():Array;
function set rotation(flash.display:Number):void;
function get stage():Stage;
}
}//package mx.core
Section 101
//IFlexModuleFactory (mx.core.IFlexModuleFactory)
package mx.core {
import flash.utils.*;
public interface IFlexModuleFactory {
function get preloadedRSLs():Dictionary;
function allowInsecureDomain(... _args):void;
function create(... _args):Object;
function allowDomain(... _args):void;
function info():Object;
}
}//package mx.core
Section 102
//IMXMLObject (mx.core.IMXMLObject)
package mx.core {
public interface IMXMLObject {
function initialized(_arg1:Object, _arg2:String):void;
}
}//package mx.core
Section 103
//IPropertyChangeNotifier (mx.core.IPropertyChangeNotifier)
package mx.core {
import flash.events.*;
public interface IPropertyChangeNotifier extends IEventDispatcher, IUID {
}
}//package mx.core
Section 104
//ISWFBridgeGroup (mx.core.ISWFBridgeGroup)
package mx.core {
import flash.events.*;
public interface ISWFBridgeGroup {
function getChildBridgeProvider(mx.core:ISWFBridgeGroup/mx.core:ISWFBridgeGroup:parentBridge/get:IEventDispatcher):ISWFBridgeProvider;
function removeChildBridge(C:\autobuild\galaga\frameworks\projects\framework\src;mx\core;ISWFBridgeGroup.as:IEventDispatcher):void;
function get parentBridge():IEventDispatcher;
function addChildBridge(_arg1:IEventDispatcher, _arg2:ISWFBridgeProvider):void;
function set parentBridge(C:\autobuild\galaga\frameworks\projects\framework\src;mx\core;ISWFBridgeGroup.as:IEventDispatcher):void;
function containsBridge(IEventDispatcher:IEventDispatcher):Boolean;
function getChildBridges():Array;
}
}//package mx.core
Section 105
//ISWFBridgeProvider (mx.core.ISWFBridgeProvider)
package mx.core {
import flash.events.*;
public interface ISWFBridgeProvider {
function get childAllowsParent():Boolean;
function get swfBridge():IEventDispatcher;
function get parentAllowsChild():Boolean;
}
}//package mx.core
Section 106
//IUIComponent (mx.core.IUIComponent)
package mx.core {
import flash.display.*;
import mx.managers.*;
public interface IUIComponent extends IFlexDisplayObject {
function set focusPane(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Sprite):void;
function get enabled():Boolean;
function set enabled(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Boolean):void;
function set isPopUp(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Boolean):void;
function get explicitMinHeight():Number;
function get percentWidth():Number;
function get isPopUp():Boolean;
function get owner():DisplayObjectContainer;
function get percentHeight():Number;
function get baselinePosition():Number;
function owns(Number:DisplayObject):Boolean;
function initialize():void;
function get maxWidth():Number;
function get minWidth():Number;
function getExplicitOrMeasuredWidth():Number;
function get explicitMaxWidth():Number;
function get explicitMaxHeight():Number;
function set percentHeight(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Number):void;
function get minHeight():Number;
function set percentWidth(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Number):void;
function get document():Object;
function get focusPane():Sprite;
function getExplicitOrMeasuredHeight():Number;
function set tweeningProperties(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Array):void;
function set explicitWidth(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Number):void;
function set measuredMinHeight(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Number):void;
function get explicitMinWidth():Number;
function get tweeningProperties():Array;
function get maxHeight():Number;
function set owner(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:DisplayObjectContainer):void;
function set includeInLayout(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Boolean):void;
function setVisible(_arg1:Boolean, _arg2:Boolean=false):void;
function parentChanged(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:DisplayObjectContainer):void;
function get explicitWidth():Number;
function get measuredMinHeight():Number;
function set measuredMinWidth(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Number):void;
function set explicitHeight(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Number):void;
function get includeInLayout():Boolean;
function get measuredMinWidth():Number;
function get explicitHeight():Number;
function set systemManager(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:ISystemManager):void;
function set document(mx.core:IUIComponent/mx.core:IUIComponent:baselinePosition/get:Object):void;
function get systemManager():ISystemManager;
}
}//package mx.core
Section 107
//IUID (mx.core.IUID)
package mx.core {
public interface IUID {
function get uid():String;
function set uid(C:\autobuild\galaga\frameworks\projects\framework\src;mx\core;IUID.as:String):void;
}
}//package mx.core
Section 108
//mx_internal (mx.core.mx_internal)
package mx.core {
public namespace mx_internal = "http://www.adobe.com/2006/flex/mx/internal";
}//package mx.core
Section 109
//Singleton (mx.core.Singleton)
package mx.core {
public class Singleton {
mx_internal static const VERSION:String = "3.4.0.9271";
private static var classMap:Object = {};
public function Singleton(){
super();
}
public static function registerClass(interfaceName:String, clazz:Class):void{
var c:Class = classMap[interfaceName];
if (!c){
classMap[interfaceName] = clazz;
};
}
public static function getClass(interfaceName:String):Class{
return (classMap[interfaceName]);
}
public static function getInstance(interfaceName:String):Object{
var c:Class = classMap[interfaceName];
if (!c){
throw (new Error((("No class registered for interface '" + interfaceName) + "'.")));
};
return (c["getInstance"]());
}
}
}//package mx.core
Section 110
//CollectionEvent (mx.events.CollectionEvent)
package mx.events {
import flash.events.*;
import mx.core.*;
public class CollectionEvent extends Event {
public var kind:String;
public var location:int;
public var items:Array;
public var oldLocation:int;
mx_internal static const VERSION:String = "3.4.0.9271";
public static const COLLECTION_CHANGE:String = "collectionChange";
public function CollectionEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false, kind:String=null, location:int=-1, oldLocation:int=-1, items:Array=null){
super(type, bubbles, cancelable);
this.kind = kind;
this.location = location;
this.oldLocation = oldLocation;
this.items = (items) ? items : [];
}
override public function toString():String{
return (formatToString("CollectionEvent", "kind", "location", "oldLocation", "type", "bubbles", "cancelable", "eventPhase"));
}
override public function clone():Event{
return (new CollectionEvent(type, bubbles, cancelable, kind, location, oldLocation, items));
}
}
}//package mx.events
Section 111
//CollectionEventKind (mx.events.CollectionEventKind)
package mx.events {
import mx.core.*;
public final class CollectionEventKind {
public static const ADD:String = "add";
public static const REMOVE:String = "remove";
public static const UPDATE:String = "update";
public static const MOVE:String = "move";
mx_internal static const EXPAND:String = "expand";
public static const REPLACE:String = "replace";
mx_internal static const VERSION:String = "3.4.0.9271";
public static const REFRESH:String = "refresh";
public static const RESET:String = "reset";
public function CollectionEventKind(){
super();
}
}
}//package mx.events
Section 112
//FlexEvent (mx.events.FlexEvent)
package mx.events {
import flash.events.*;
import mx.core.*;
public class FlexEvent extends Event {
public static const ADD:String = "add";
public static const TRANSFORM_CHANGE:String = "transformChange";
public static const ENTER_FRAME:String = "flexEventEnterFrame";
public static const INIT_COMPLETE:String = "initComplete";
public static const REMOVE:String = "remove";
public static const BUTTON_DOWN:String = "buttonDown";
public static const EXIT_STATE:String = "exitState";
public static const CREATION_COMPLETE:String = "creationComplete";
public static const REPEAT:String = "repeat";
public static const LOADING:String = "loading";
public static const RENDER:String = "flexEventRender";
public static const REPEAT_START:String = "repeatStart";
public static const INITIALIZE:String = "initialize";
public static const ENTER_STATE:String = "enterState";
public static const URL_CHANGED:String = "urlChanged";
public static const REPEAT_END:String = "repeatEnd";
mx_internal static const VERSION:String = "3.4.0.9271";
public static const HIDE:String = "hide";
public static const ENTER:String = "enter";
public static const PRELOADER_DONE:String = "preloaderDone";
public static const CURSOR_UPDATE:String = "cursorUpdate";
public static const PREINITIALIZE:String = "preinitialize";
public static const INVALID:String = "invalid";
public static const IDLE:String = "idle";
public static const VALID:String = "valid";
public static const DATA_CHANGE:String = "dataChange";
public static const APPLICATION_COMPLETE:String = "applicationComplete";
public static const VALUE_COMMIT:String = "valueCommit";
public static const UPDATE_COMPLETE:String = "updateComplete";
public static const INIT_PROGRESS:String = "initProgress";
public static const SHOW:String = "show";
public function FlexEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false){
super(type, bubbles, cancelable);
}
override public function clone():Event{
return (new FlexEvent(type, bubbles, cancelable));
}
}
}//package mx.events
Section 113
//ModuleEvent (mx.events.ModuleEvent)
package mx.events {
import flash.events.*;
import mx.modules.*;
import mx.core.*;
public class ModuleEvent extends ProgressEvent {
public var errorText:String;
private var _module:IModuleInfo;
public static const READY:String = "ready";
public static const ERROR:String = "error";
public static const PROGRESS:String = "progress";
mx_internal static const VERSION:String = "3.4.0.9271";
public static const SETUP:String = "setup";
public static const UNLOAD:String = "unload";
public function ModuleEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false, bytesLoaded:uint=0, bytesTotal:uint=0, errorText:String=null, module:IModuleInfo=null){
super(type, bubbles, cancelable, bytesLoaded, bytesTotal);
this.errorText = errorText;
this._module = module;
}
public function get module():IModuleInfo{
if (_module){
return (_module);
};
return ((target as IModuleInfo));
}
override public function clone():Event{
return (new ModuleEvent(type, bubbles, cancelable, bytesLoaded, bytesTotal, errorText, module));
}
}
}//package mx.events
Section 114
//PropertyChangeEvent (mx.events.PropertyChangeEvent)
package mx.events {
import flash.events.*;
import mx.core.*;
public class PropertyChangeEvent extends Event {
public var newValue:Object;
public var kind:String;
public var property:Object;
public var oldValue:Object;
public var source:Object;
mx_internal static const VERSION:String = "3.4.0.9271";
public static const PROPERTY_CHANGE:String = "propertyChange";
public function PropertyChangeEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false, kind:String=null, property:Object=null, oldValue:Object=null, newValue:Object=null, source:Object=null){
super(type, bubbles, cancelable);
this.kind = kind;
this.property = property;
this.oldValue = oldValue;
this.newValue = newValue;
this.source = source;
}
override public function clone():Event{
return (new PropertyChangeEvent(type, bubbles, cancelable, kind, property, oldValue, newValue, source));
}
public static function createUpdateEvent(source:Object, property:Object, oldValue:Object, newValue:Object):PropertyChangeEvent{
var event:PropertyChangeEvent = new PropertyChangeEvent(PROPERTY_CHANGE);
event.kind = PropertyChangeEventKind.UPDATE;
event.oldValue = oldValue;
event.newValue = newValue;
event.source = source;
event.property = property;
return (event);
}
}
}//package mx.events
Section 115
//PropertyChangeEventKind (mx.events.PropertyChangeEventKind)
package mx.events {
import mx.core.*;
public final class PropertyChangeEventKind {
mx_internal static const VERSION:String = "3.4.0.9271";
public static const UPDATE:String = "update";
public static const DELETE:String = "delete";
public function PropertyChangeEventKind(){
super();
}
}
}//package mx.events
Section 116
//ResourceEvent (mx.events.ResourceEvent)
package mx.events {
import flash.events.*;
import mx.core.*;
public class ResourceEvent extends ProgressEvent {
public var errorText:String;
mx_internal static const VERSION:String = "3.4.0.9271";
public static const COMPLETE:String = "complete";
public static const PROGRESS:String = "progress";
public static const ERROR:String = "error";
public function ResourceEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false, bytesLoaded:uint=0, bytesTotal:uint=0, errorText:String=null){
super(type, bubbles, cancelable, bytesLoaded, bytesTotal);
this.errorText = errorText;
}
override public function clone():Event{
return (new ResourceEvent(type, bubbles, cancelable, bytesLoaded, bytesTotal, errorText));
}
}
}//package mx.events
Section 117
//IFocusManager (mx.managers.IFocusManager)
package mx.managers {
import flash.events.*;
import flash.display.*;
import mx.core.*;
public interface IFocusManager {
function get focusPane():Sprite;
function getFocus():IFocusManagerComponent;
function deactivate():void;
function set defaultButton(C:\autobuild\galaga\frameworks\projects\framework\src;mx\managers;IFocusManager.as:IButton):void;
function set focusPane(C:\autobuild\galaga\frameworks\projects\framework\src;mx\managers;IFocusManager.as:Sprite):void;
function set showFocusIndicator(C:\autobuild\galaga\frameworks\projects\framework\src;mx\managers;IFocusManager.as:Boolean):void;
function moveFocus(_arg1:String, _arg2:DisplayObject=null):void;
function addSWFBridge(_arg1:IEventDispatcher, _arg2:DisplayObject):void;
function removeSWFBridge(C:\autobuild\galaga\frameworks\projects\framework\src;mx\managers;IFocusManager.as:IEventDispatcher):void;
function get defaultButtonEnabled():Boolean;
function findFocusManagerComponent(value:InteractiveObject):IFocusManagerComponent;
function get nextTabIndex():int;
function get defaultButton():IButton;
function get showFocusIndicator():Boolean;
function setFocus(C:\autobuild\galaga\frameworks\projects\framework\src;mx\managers;IFocusManager.as:IFocusManagerComponent):void;
function activate():void;
function showFocus():void;
function set defaultButtonEnabled(C:\autobuild\galaga\frameworks\projects\framework\src;mx\managers;IFocusManager.as:Boolean):void;
function hideFocus():void;
function getNextFocusManagerComponent(value:Boolean=false):IFocusManagerComponent;
}
}//package mx.managers
Section 118
//IFocusManagerComponent (mx.managers.IFocusManagerComponent)
package mx.managers {
public interface IFocusManagerComponent {
function set focusEnabled(C:\autobuild\galaga\frameworks\projects\framework\src;mx\managers;IFocusManagerComponent.as:Boolean):void;
function drawFocus(C:\autobuild\galaga\frameworks\projects\framework\src;mx\managers;IFocusManagerComponent.as:Boolean):void;
function setFocus():void;
function get focusEnabled():Boolean;
function get tabEnabled():Boolean;
function get tabIndex():int;
function get mouseFocusEnabled():Boolean;
}
}//package mx.managers
Section 119
//IFocusManagerContainer (mx.managers.IFocusManagerContainer)
package mx.managers {
import flash.events.*;
import flash.display.*;
public interface IFocusManagerContainer extends IEventDispatcher {
function set focusManager(C:\autobuild\galaga\frameworks\projects\framework\src;mx\managers;IFocusManagerContainer.as:IFocusManager):void;
function get focusManager():IFocusManager;
function get systemManager():ISystemManager;
function contains(mx.managers:DisplayObject):Boolean;
}
}//package mx.managers
Section 120
//ISystemManager (mx.managers.ISystemManager)
package mx.managers {
import flash.events.*;
import flash.display.*;
import mx.core.*;
import flash.geom.*;
import flash.text.*;
public interface ISystemManager extends IEventDispatcher, IChildList, IFlexModuleFactory {
function set focusPane(mx.managers:ISystemManager/mx.managers:ISystemManager:cursorChildren/get:Sprite):void;
function get toolTipChildren():IChildList;
function useSWFBridge():Boolean;
function isFontFaceEmbedded(flash.display:TextFormat):Boolean;
function deployMouseShields(mx.managers:ISystemManager/mx.managers:ISystemManager:cursorChildren/get:Boolean):void;
function get rawChildren():IChildList;
function get topLevelSystemManager():ISystemManager;
function dispatchEventFromSWFBridges(_arg1:Event, _arg2:IEventDispatcher=null, _arg3:Boolean=false, _arg4:Boolean=false):void;
function getSandboxRoot():DisplayObject;
function get swfBridgeGroup():ISWFBridgeGroup;
function removeFocusManager(mx.managers:ISystemManager/mx.managers:ISystemManager:cursorChildren/get:IFocusManagerContainer):void;
function addChildToSandboxRoot(_arg1:String, _arg2:DisplayObject):void;
function get document():Object;
function get focusPane():Sprite;
function get loaderInfo():LoaderInfo;
function addChildBridge(_arg1:IEventDispatcher, _arg2:DisplayObject):void;
function getTopLevelRoot():DisplayObject;
function removeChildBridge(mx.managers:ISystemManager/mx.managers:ISystemManager:cursorChildren/get:IEventDispatcher):void;
function isDisplayObjectInABridgedApplication(flash.display:DisplayObject):Boolean;
function get popUpChildren():IChildList;
function get screen():Rectangle;
function removeChildFromSandboxRoot(_arg1:String, _arg2:DisplayObject):void;
function getDefinitionByName(C:\autobuild\galaga\frameworks\projects\framework\src;mx\managers;ISystemManager.as:String):Object;
function activate(mx.managers:ISystemManager/mx.managers:ISystemManager:cursorChildren/get:IFocusManagerContainer):void;
function deactivate(mx.managers:ISystemManager/mx.managers:ISystemManager:cursorChildren/get:IFocusManagerContainer):void;
function get cursorChildren():IChildList;
function set document(mx.managers:ISystemManager/mx.managers:ISystemManager:cursorChildren/get:Object):void;
function get embeddedFontList():Object;
function set numModalWindows(mx.managers:ISystemManager/mx.managers:ISystemManager:cursorChildren/get:int):void;
function isTopLevel():Boolean;
function isTopLevelRoot():Boolean;
function get numModalWindows():int;
function addFocusManager(mx.managers:ISystemManager/mx.managers:ISystemManager:cursorChildren/get:IFocusManagerContainer):void;
function get stage():Stage;
function getVisibleApplicationRect(value:Rectangle=null):Rectangle;
}
}//package mx.managers
Section 121
//IModuleInfo (mx.modules.IModuleInfo)
package mx.modules {
import flash.events.*;
import flash.utils.*;
import flash.system.*;
import mx.core.*;
public interface IModuleInfo extends IEventDispatcher {
function get ready():Boolean;
function get loaded():Boolean;
function load(_arg1:ApplicationDomain=null, _arg2:SecurityDomain=null, _arg3:ByteArray=null):void;
function release():void;
function get error():Boolean;
function get data():Object;
function publish(C:\autobuild\galaga\frameworks\projects\framework\src;mx\modules;IModuleInfo.as:IFlexModuleFactory):void;
function get factory():IFlexModuleFactory;
function set data(C:\autobuild\galaga\frameworks\projects\framework\src;mx\modules;IModuleInfo.as:Object):void;
function get url():String;
function get setup():Boolean;
function unload():void;
}
}//package mx.modules
Section 122
//ModuleManager (mx.modules.ModuleManager)
package mx.modules {
import mx.core.*;
public class ModuleManager {
mx_internal static const VERSION:String = "3.4.0.9271";
public function ModuleManager(){
super();
}
public static function getModule(url:String):IModuleInfo{
return (getSingleton().getModule(url));
}
private static function getSingleton():Object{
if (!ModuleManagerGlobals.managerSingleton){
ModuleManagerGlobals.managerSingleton = new ModuleManagerImpl();
};
return (ModuleManagerGlobals.managerSingleton);
}
public static function getAssociatedFactory(object:Object):IFlexModuleFactory{
return (getSingleton().getAssociatedFactory(object));
}
}
}//package mx.modules
import flash.events.*;
import flash.display.*;
import flash.utils.*;
import flash.net.*;
import mx.events.*;
import flash.system.*;
import mx.core.*;
class ModuleInfoProxy extends EventDispatcher implements IModuleInfo {
private var _data:Object;
private var info:ModuleInfo;
private var referenced:Boolean;// = false
private function ModuleInfoProxy(info:ModuleInfo){
super();
this.info = info;
info.addEventListener(ModuleEvent.SETUP, moduleEventHandler, false, 0, true);
info.addEventListener(ModuleEvent.PROGRESS, moduleEventHandler, false, 0, true);
info.addEventListener(ModuleEvent.READY, moduleEventHandler, false, 0, true);
info.addEventListener(ModuleEvent.ERROR, moduleEventHandler, false, 0, true);
info.addEventListener(ModuleEvent.UNLOAD, moduleEventHandler, false, 0, true);
}
public function get loaded():Boolean{
return (info.loaded);
}
public function release():void{
if (referenced){
info.removeReference();
referenced = false;
};
}
public function get error():Boolean{
return (info.error);
}
public function get factory():IFlexModuleFactory{
return (info.factory);
}
public function publish(factory:IFlexModuleFactory):void{
info.publish(factory);
}
public function set data(value:Object):void{
_data = value;
}
public function get ready():Boolean{
return (info.ready);
}
public function load(applicationDomain:ApplicationDomain=null, securityDomain:SecurityDomain=null, bytes:ByteArray=null):void{
var moduleEvent:ModuleEvent;
info.resurrect();
if (!referenced){
info.addReference();
referenced = true;
};
if (info.error){
dispatchEvent(new ModuleEvent(ModuleEvent.ERROR));
} else {
if (info.loaded){
if (info.setup){
dispatchEvent(new ModuleEvent(ModuleEvent.SETUP));
if (info.ready){
moduleEvent = new ModuleEvent(ModuleEvent.PROGRESS);
moduleEvent.bytesLoaded = info.size;
moduleEvent.bytesTotal = info.size;
dispatchEvent(moduleEvent);
dispatchEvent(new ModuleEvent(ModuleEvent.READY));
};
};
} else {
info.load(applicationDomain, securityDomain, bytes);
};
};
}
private function moduleEventHandler(event:ModuleEvent):void{
dispatchEvent(event);
}
public function get url():String{
return (info.url);
}
public function get data():Object{
return (_data);
}
public function get setup():Boolean{
return (info.setup);
}
public function unload():void{
info.unload();
info.removeEventListener(ModuleEvent.SETUP, moduleEventHandler);
info.removeEventListener(ModuleEvent.PROGRESS, moduleEventHandler);
info.removeEventListener(ModuleEvent.READY, moduleEventHandler);
info.removeEventListener(ModuleEvent.ERROR, moduleEventHandler);
info.removeEventListener(ModuleEvent.UNLOAD, moduleEventHandler);
}
}
class ModuleManagerImpl extends EventDispatcher {
private var moduleList:Object;
private function ModuleManagerImpl(){
moduleList = {};
super();
}
public function getModule(url:String):IModuleInfo{
var info:ModuleInfo = (moduleList[url] as ModuleInfo);
if (!info){
info = new ModuleInfo(url);
moduleList[url] = info;
};
return (new ModuleInfoProxy(info));
}
public function getAssociatedFactory(object:Object):IFlexModuleFactory{
var m:Object;
var info:ModuleInfo;
var domain:ApplicationDomain;
var cls:Class;
var object = object;
var className:String = getQualifiedClassName(object);
for each (m in moduleList) {
info = (m as ModuleInfo);
if (!info.ready){
} else {
domain = info.applicationDomain;
cls = Class(domain.getDefinition(className));
if ((object is cls)){
return (info.factory);
};
//unresolved jump
var _slot1 = error;
};
};
return (null);
}
}
class ModuleInfo extends EventDispatcher {
private var _error:Boolean;// = false
private var loader:Loader;
private var factoryInfo:FactoryInfo;
private var limbo:Dictionary;
private var _loaded:Boolean;// = false
private var _ready:Boolean;// = false
private var numReferences:int;// = 0
private var _url:String;
private var _setup:Boolean;// = false
private function ModuleInfo(url:String){
super();
_url = url;
}
private function clearLoader():void{
if (loader){
if (loader.contentLoaderInfo){
loader.contentLoaderInfo.removeEventListener(Event.INIT, initHandler);
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, completeHandler);
loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
loader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
};
if (loader.content){
loader.content.removeEventListener("ready", readyHandler);
loader.content.removeEventListener("error", moduleErrorHandler);
};
//unresolved jump
var _slot1 = error;
if (_loaded){
loader.close();
//unresolved jump
var _slot1 = error;
};
loader.unload();
//unresolved jump
var _slot1 = error;
loader = null;
};
}
public function get size():int{
return ((((!(limbo)) && (factoryInfo))) ? factoryInfo.bytesTotal : 0);
}
public function get loaded():Boolean{
return ((limbo) ? false : _loaded);
}
public function release():void{
if (((_ready) && (!(limbo)))){
limbo = new Dictionary(true);
limbo[factoryInfo] = 1;
factoryInfo = null;
} else {
unload();
};
}
public function get error():Boolean{
return ((limbo) ? false : _error);
}
public function get factory():IFlexModuleFactory{
return ((((!(limbo)) && (factoryInfo))) ? factoryInfo.factory : null);
}
public function completeHandler(event:Event):void{
var moduleEvent:ModuleEvent = new ModuleEvent(ModuleEvent.PROGRESS, event.bubbles, event.cancelable);
moduleEvent.bytesLoaded = loader.contentLoaderInfo.bytesLoaded;
moduleEvent.bytesTotal = loader.contentLoaderInfo.bytesTotal;
dispatchEvent(moduleEvent);
}
public function publish(factory:IFlexModuleFactory):void{
if (factoryInfo){
return;
};
if (_url.indexOf("published://") != 0){
return;
};
factoryInfo = new FactoryInfo();
factoryInfo.factory = factory;
_loaded = true;
_setup = true;
_ready = true;
_error = false;
dispatchEvent(new ModuleEvent(ModuleEvent.SETUP));
dispatchEvent(new ModuleEvent(ModuleEvent.PROGRESS));
dispatchEvent(new ModuleEvent(ModuleEvent.READY));
}
public function initHandler(event:Event):void{
var moduleEvent:ModuleEvent;
var event = event;
factoryInfo = new FactoryInfo();
factoryInfo.factory = (loader.content as IFlexModuleFactory);
//unresolved jump
var _slot1 = error;
if (!factoryInfo.factory){
moduleEvent = new ModuleEvent(ModuleEvent.ERROR, event.bubbles, event.cancelable);
moduleEvent.bytesLoaded = 0;
moduleEvent.bytesTotal = 0;
moduleEvent.errorText = "SWF is not a loadable module";
dispatchEvent(moduleEvent);
return;
};
loader.content.addEventListener("ready", readyHandler);
loader.content.addEventListener("error", moduleErrorHandler);
factoryInfo.applicationDomain = loader.contentLoaderInfo.applicationDomain;
//unresolved jump
var _slot1 = error;
_setup = true;
dispatchEvent(new ModuleEvent(ModuleEvent.SETUP));
}
public function resurrect():void{
var f:Object;
if (((!(factoryInfo)) && (limbo))){
for (f in limbo) {
factoryInfo = (f as FactoryInfo);
break;
};
limbo = null;
};
if (!factoryInfo){
if (_loaded){
dispatchEvent(new ModuleEvent(ModuleEvent.UNLOAD));
};
loader = null;
_loaded = false;
_setup = false;
_ready = false;
_error = false;
};
}
public function errorHandler(event:ErrorEvent):void{
_error = true;
var moduleEvent:ModuleEvent = new ModuleEvent(ModuleEvent.ERROR, event.bubbles, event.cancelable);
moduleEvent.bytesLoaded = 0;
moduleEvent.bytesTotal = 0;
moduleEvent.errorText = event.text;
dispatchEvent(moduleEvent);
}
public function get ready():Boolean{
return ((limbo) ? false : _ready);
}
private function loadBytes(applicationDomain:ApplicationDomain, bytes:ByteArray):void{
var c:LoaderContext = new LoaderContext();
c.applicationDomain = (applicationDomain) ? applicationDomain : new ApplicationDomain(ApplicationDomain.currentDomain);
if (("allowLoadBytesCodeExecution" in c)){
c["allowLoadBytesCodeExecution"] = true;
};
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
loader.loadBytes(bytes, c);
}
public function removeReference():void{
numReferences--;
if (numReferences == 0){
release();
};
}
public function addReference():void{
numReferences++;
}
public function progressHandler(event:ProgressEvent):void{
var moduleEvent:ModuleEvent = new ModuleEvent(ModuleEvent.PROGRESS, event.bubbles, event.cancelable);
moduleEvent.bytesLoaded = event.bytesLoaded;
moduleEvent.bytesTotal = event.bytesTotal;
dispatchEvent(moduleEvent);
}
public function load(applicationDomain:ApplicationDomain=null, securityDomain:SecurityDomain=null, bytes:ByteArray=null):void{
if (_loaded){
return;
};
_loaded = true;
limbo = null;
if (bytes){
loadBytes(applicationDomain, bytes);
return;
};
if (_url.indexOf("published://") == 0){
return;
};
var r:URLRequest = new URLRequest(_url);
var c:LoaderContext = new LoaderContext();
c.applicationDomain = (applicationDomain) ? applicationDomain : new ApplicationDomain(ApplicationDomain.currentDomain);
c.securityDomain = securityDomain;
if ((((securityDomain == null)) && ((Security.sandboxType == Security.REMOTE)))){
c.securityDomain = SecurityDomain.currentDomain;
};
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
loader.load(r, c);
}
public function get url():String{
return (_url);
}
public function get applicationDomain():ApplicationDomain{
return ((((!(limbo)) && (factoryInfo))) ? factoryInfo.applicationDomain : null);
}
public function moduleErrorHandler(event:Event):void{
var errorEvent:ModuleEvent;
_ready = true;
factoryInfo.bytesTotal = loader.contentLoaderInfo.bytesTotal;
clearLoader();
if ((event is ModuleEvent)){
errorEvent = ModuleEvent(event);
} else {
errorEvent = new ModuleEvent(ModuleEvent.ERROR);
};
dispatchEvent(errorEvent);
}
public function readyHandler(event:Event):void{
_ready = true;
factoryInfo.bytesTotal = loader.contentLoaderInfo.bytesTotal;
var moduleEvent:ModuleEvent = new ModuleEvent(ModuleEvent.READY);
moduleEvent.bytesLoaded = loader.contentLoaderInfo.bytesLoaded;
moduleEvent.bytesTotal = loader.contentLoaderInfo.bytesTotal;
clearLoader();
dispatchEvent(moduleEvent);
}
public function get setup():Boolean{
return ((limbo) ? false : _setup);
}
public function unload():void{
clearLoader();
if (_loaded){
dispatchEvent(new ModuleEvent(ModuleEvent.UNLOAD));
};
limbo = null;
factoryInfo = null;
_loaded = false;
_setup = false;
_ready = false;
_error = false;
}
}
class FactoryInfo {
public var bytesTotal:int;// = 0
public var factory:IFlexModuleFactory;
public var applicationDomain:ApplicationDomain;
private function FactoryInfo(){
super();
}
}
Section 123
//ModuleManagerGlobals (mx.modules.ModuleManagerGlobals)
package mx.modules {
public class ModuleManagerGlobals {
public static var managerSingleton:Object = null;
public function ModuleManagerGlobals(){
super();
}
}
}//package mx.modules
Section 124
//IResourceBundle (mx.resources.IResourceBundle)
package mx.resources {
public interface IResourceBundle {
function get content():Object;
function get locale():String;
function get bundleName():String;
}
}//package mx.resources
Section 125
//IResourceManager (mx.resources.IResourceManager)
package mx.resources {
import flash.events.*;
import flash.system.*;
public interface IResourceManager extends IEventDispatcher {
function loadResourceModule(_arg1:String, _arg2:Boolean=true, _arg3:ApplicationDomain=null, _arg4:SecurityDomain=null):IEventDispatcher;
function getBoolean(_arg1:String, _arg2:String, _arg3:String=null):Boolean;
function getClass(_arg1:String, _arg2:String, _arg3:String=null):Class;
function getLocales():Array;
function removeResourceBundlesForLocale(C:\autobuild\galaga\frameworks\projects\framework\src;mx\resources;IResourceManager.as:String):void;
function getResourceBundle(_arg1:String, _arg2:String):IResourceBundle;
function get localeChain():Array;
function getInt(_arg1:String, _arg2:String, _arg3:String=null):int;
function update():void;
function set localeChain(C:\autobuild\galaga\frameworks\projects\framework\src;mx\resources;IResourceManager.as:Array):void;
function getUint(_arg1:String, _arg2:String, _arg3:String=null):uint;
function addResourceBundle(C:\autobuild\galaga\frameworks\projects\framework\src;mx\resources;IResourceManager.as:IResourceBundle):void;
function getStringArray(_arg1:String, _arg2:String, _arg3:String=null):Array;
function getBundleNamesForLocale(:String):Array;
function removeResourceBundle(_arg1:String, _arg2:String):void;
function getObject(_arg1:String, _arg2:String, _arg3:String=null);
function getString(_arg1:String, _arg2:String, _arg3:Array=null, _arg4:String=null):String;
function installCompiledResourceBundles(_arg1:ApplicationDomain, _arg2:Array, _arg3:Array):void;
function unloadResourceModule(_arg1:String, _arg2:Boolean=true):void;
function getPreferredLocaleChain():Array;
function findResourceBundleWithResource(_arg1:String, _arg2:String):IResourceBundle;
function initializeLocaleChain(C:\autobuild\galaga\frameworks\projects\framework\src;mx\resources;IResourceManager.as:Array):void;
function getNumber(_arg1:String, _arg2:String, _arg3:String=null):Number;
}
}//package mx.resources
Section 126
//IResourceModule (mx.resources.IResourceModule)
package mx.resources {
public interface IResourceModule {
function get resourceBundles():Array;
}
}//package mx.resources
Section 127
//LocaleSorter (mx.resources.LocaleSorter)
package mx.resources {
import mx.core.*;
public class LocaleSorter {
mx_internal static const VERSION:String = "3.4.0.9271";
public function LocaleSorter(){
super();
}
private static function normalizeLocale(locale:String):String{
return (locale.toLowerCase().replace(/-/g, "_"));
}
public static function sortLocalesByPreference(appLocales:Array, systemPreferences:Array, ultimateFallbackLocale:String=null, addAll:Boolean=false):Array{
var result:Array;
var hasLocale:Object;
var i:int;
var j:int;
var k:int;
var l:int;
var locale:String;
var plocale:LocaleID;
var appLocales = appLocales;
var systemPreferences = systemPreferences;
var ultimateFallbackLocale = ultimateFallbackLocale;
var addAll = addAll;
var promote:Function = function (locale:String):void{
if (typeof(hasLocale[locale]) != "undefined"){
result.push(appLocales[hasLocale[locale]]);
delete hasLocale[locale];
};
};
result = [];
hasLocale = {};
var locales:Array = trimAndNormalize(appLocales);
var preferenceLocales:Array = trimAndNormalize(systemPreferences);
addUltimateFallbackLocale(preferenceLocales, ultimateFallbackLocale);
j = 0;
while (j < locales.length) {
hasLocale[locales[j]] = j;
j = (j + 1);
};
i = 0;
l = preferenceLocales.length;
while (i < l) {
plocale = LocaleID.fromString(preferenceLocales[i]);
promote(preferenceLocales[i]);
promote(plocale.toString());
while (plocale.transformToParent()) {
promote(plocale.toString());
};
plocale = LocaleID.fromString(preferenceLocales[i]);
j = 0;
while (j < l) {
locale = preferenceLocales[j];
if (plocale.isSiblingOf(LocaleID.fromString(locale))){
promote(locale);
};
j = (j + 1);
};
j = 0;
k = locales.length;
while (j < k) {
locale = locales[j];
if (plocale.isSiblingOf(LocaleID.fromString(locale))){
promote(locale);
};
j = (j + 1);
};
i = (i + 1);
};
if (addAll){
j = 0;
k = locales.length;
while (j < k) {
promote(locales[j]);
j = (j + 1);
};
};
return (result);
}
private static function addUltimateFallbackLocale(preferenceLocales:Array, ultimateFallbackLocale:String):void{
var locale:String;
if (((!((ultimateFallbackLocale == null))) && (!((ultimateFallbackLocale == ""))))){
locale = normalizeLocale(ultimateFallbackLocale);
if (preferenceLocales.indexOf(locale) == -1){
preferenceLocales.push(locale);
};
};
}
private static function trimAndNormalize(list:Array):Array{
var resultList:Array = [];
var i:int;
while (i < list.length) {
resultList.push(normalizeLocale(list[i]));
i++;
};
return (resultList);
}
}
}//package mx.resources
class LocaleID {
private var privateLangs:Boolean;// = false
private var script:String;// = ""
private var variants:Array;
private var privates:Array;
private var extensions:Object;
private var lang:String;// = ""
private var region:String;// = ""
private var extended_langs:Array;
public static const STATE_PRIMARY_LANGUAGE:int = 0;
public static const STATE_REGION:int = 3;
public static const STATE_EXTENDED_LANGUAGES:int = 1;
public static const STATE_EXTENSIONS:int = 5;
public static const STATE_SCRIPT:int = 2;
public static const STATE_VARIANTS:int = 4;
public static const STATE_PRIVATES:int = 6;
private function LocaleID(){
extended_langs = [];
variants = [];
extensions = {};
privates = [];
super();
}
public function equals(locale:LocaleID):Boolean{
return ((toString() == locale.toString()));
}
public function canonicalize():void{
var i:String;
for (i in extensions) {
if (extensions.hasOwnProperty(i)){
if (extensions[i].length == 0){
delete extensions[i];
} else {
extensions[i] = extensions[i].sort();
};
};
};
extended_langs = extended_langs.sort();
variants = variants.sort();
privates = privates.sort();
if (script == ""){
script = LocaleRegistry.getScriptByLang(lang);
};
if ((((script == "")) && (!((region == ""))))){
script = LocaleRegistry.getScriptByLangAndRegion(lang, region);
};
if ((((region == "")) && (!((script == ""))))){
region = LocaleRegistry.getDefaultRegionForLangAndScript(lang, script);
};
}
public function toString():String{
var i:String;
var stack:Array = [lang];
Array.prototype.push.apply(stack, extended_langs);
if (script != ""){
stack.push(script);
};
if (region != ""){
stack.push(region);
};
Array.prototype.push.apply(stack, variants);
for (i in extensions) {
if (extensions.hasOwnProperty(i)){
stack.push(i);
Array.prototype.push.apply(stack, extensions[i]);
};
};
if (privates.length > 0){
stack.push("x");
Array.prototype.push.apply(stack, privates);
};
return (stack.join("_"));
}
public function isSiblingOf(other:LocaleID):Boolean{
return ((((lang == other.lang)) && ((script == other.script))));
}
public function transformToParent():Boolean{
var i:String;
var lastExtension:Array;
var defaultRegion:String;
if (privates.length > 0){
privates.splice((privates.length - 1), 1);
return (true);
};
var lastExtensionName:String;
for (i in extensions) {
if (extensions.hasOwnProperty(i)){
lastExtensionName = i;
};
};
if (lastExtensionName){
lastExtension = extensions[lastExtensionName];
if (lastExtension.length == 1){
delete extensions[lastExtensionName];
return (true);
};
lastExtension.splice((lastExtension.length - 1), 1);
return (true);
};
if (variants.length > 0){
variants.splice((variants.length - 1), 1);
return (true);
};
if (script != ""){
if (LocaleRegistry.getScriptByLang(lang) != ""){
script = "";
return (true);
};
if (region == ""){
defaultRegion = LocaleRegistry.getDefaultRegionForLangAndScript(lang, script);
if (defaultRegion != ""){
region = defaultRegion;
script = "";
return (true);
};
};
};
if (region != ""){
if (!(((script == "")) && ((LocaleRegistry.getScriptByLang(lang) == "")))){
region = "";
return (true);
};
};
if (extended_langs.length > 0){
extended_langs.splice((extended_langs.length - 1), 1);
return (true);
};
return (false);
}
public static function fromString(str:String):LocaleID{
var last_extension:Array;
var subtag:String;
var subtag_length:int;
var firstChar:String;
var localeID:LocaleID = new (LocaleID);
var state:int = STATE_PRIMARY_LANGUAGE;
var subtags:Array = str.replace(/-/g, "_").split("_");
var i:int;
var l:int = subtags.length;
while (i < l) {
subtag = subtags[i].toLowerCase();
if (state == STATE_PRIMARY_LANGUAGE){
if (subtag == "x"){
localeID.privateLangs = true;
} else {
if (subtag == "i"){
localeID.lang = (localeID.lang + "i-");
} else {
localeID.lang = (localeID.lang + subtag);
state = STATE_EXTENDED_LANGUAGES;
};
};
} else {
subtag_length = subtag.length;
if (subtag_length == 0){
} else {
firstChar = subtag.charAt(0).toLowerCase();
if ((((state <= STATE_EXTENDED_LANGUAGES)) && ((subtag_length == 3)))){
localeID.extended_langs.push(subtag);
if (localeID.extended_langs.length == 3){
state = STATE_SCRIPT;
};
} else {
if ((((state <= STATE_SCRIPT)) && ((subtag_length == 4)))){
localeID.script = subtag;
state = STATE_REGION;
} else {
if ((((state <= STATE_REGION)) && ((((subtag_length == 2)) || ((subtag_length == 3)))))){
localeID.region = subtag;
state = STATE_VARIANTS;
} else {
if ((((state <= STATE_VARIANTS)) && ((((((((firstChar >= "a")) && ((firstChar <= "z")))) && ((subtag_length >= 5)))) || ((((((firstChar >= "0")) && ((firstChar <= "9")))) && ((subtag_length >= 4)))))))){
localeID.variants.push(subtag);
state = STATE_VARIANTS;
} else {
if ((((state < STATE_PRIVATES)) && ((subtag_length == 1)))){
if (subtag == "x"){
state = STATE_PRIVATES;
last_extension = localeID.privates;
} else {
state = STATE_EXTENSIONS;
last_extension = ((localeID.extensions[subtag]) || ([]));
localeID.extensions[subtag] = last_extension;
};
} else {
if (state >= STATE_EXTENSIONS){
last_extension.push(subtag);
};
};
};
};
};
};
};
};
i++;
};
localeID.canonicalize();
return (localeID);
}
}
class LocaleRegistry {
private static const SCRIPT_ID_BY_LANG:Object = {ab:5, af:1, am:2, ar:3, as:4, ay:1, be:5, bg:5, bn:4, bs:1, ca:1, ch:1, cs:1, cy:1, da:1, de:1, dv:6, dz:7, el:8, en:1, eo:1, es:1, et:1, eu:1, fa:3, fi:1, fj:1, fo:1, fr:1, frr:1, fy:1, ga:1, gl:1, gn:1, gu:9, gv:1, he:10, hi:11, hr:1, ht:1, hu:1, hy:12, id:1, in:1, is:1, it:1, iw:10, ja:13, ka:14, kk:5, kl:1, km:15, kn:16, ko:17, la:1, lb:1, ln:1, lo:18, lt:1, lv:1, mg:1, mh:1, mk:5, ml:19, mo:1, mr:11, ms:1, mt:1, my:20, na:1, nb:1, nd:1, ne:11, nl:1, nn:1, no:1, nr:1, ny:1, om:1, or:21, pa:22, pl:1, ps:3, pt:1, qu:1, rn:1, ro:1, ru:5, rw:1, sg:1, si:23, sk:1, sl:1, sm:1, so:1, sq:1, ss:1, st:1, sv:1, sw:1, ta:24, te:25, th:26, ti:2, tl:1, tn:1, to:1, tr:1, ts:1, uk:5, ur:3, ve:1, vi:1, wo:1, xh:1, yi:10, zu:1, cpe:1, dsb:1, frs:1, gsw:1, hsb:1, kok:11, mai:11, men:1, nds:1, niu:1, nqo:27, nso:1, son:1, tem:1, tkl:1, tmh:1, tpi:1, tvl:1, zbl:28};
private static const SCRIPTS:Array = ["", "latn", "ethi", "arab", "beng", "cyrl", "thaa", "tibt", "grek", "gujr", "hebr", "deva", "armn", "jpan", "geor", "khmr", "knda", "kore", "laoo", "mlym", "mymr", "orya", "guru", "sinh", "taml", "telu", "thai", "nkoo", "blis", "hans", "hant", "mong", "syrc"];
private static const DEFAULT_REGION_BY_LANG_AND_SCRIPT:Object = {bg:{5:"bg"}, ca:{1:"es"}, zh:{30:"tw", 29:"cn"}, cs:{1:"cz"}, da:{1:"dk"}, de:{1:"de"}, el:{8:"gr"}, en:{1:"us"}, es:{1:"es"}, fi:{1:"fi"}, fr:{1:"fr"}, he:{10:"il"}, hu:{1:"hu"}, is:{1:"is"}, it:{1:"it"}, ja:{13:"jp"}, ko:{17:"kr"}, nl:{1:"nl"}, nb:{1:"no"}, pl:{1:"pl"}, pt:{1:"br"}, ro:{1:"ro"}, ru:{5:"ru"}, hr:{1:"hr"}, sk:{1:"sk"}, sq:{1:"al"}, sv:{1:"se"}, th:{26:"th"}, tr:{1:"tr"}, ur:{3:"pk"}, id:{1:"id"}, uk:{5:"ua"}, be:{5:"by"}, sl:{1:"si"}, et:{1:"ee"}, lv:{1:"lv"}, lt:{1:"lt"}, fa:{3:"ir"}, vi:{1:"vn"}, hy:{12:"am"}, az:{1:"az", 5:"az"}, eu:{1:"es"}, mk:{5:"mk"}, af:{1:"za"}, ka:{14:"ge"}, fo:{1:"fo"}, hi:{11:"in"}, ms:{1:"my"}, kk:{5:"kz"}, ky:{5:"kg"}, sw:{1:"ke"}, uz:{1:"uz", 5:"uz"}, tt:{5:"ru"}, pa:{22:"in"}, gu:{9:"in"}, ta:{24:"in"}, te:{25:"in"}, kn:{16:"in"}, mr:{11:"in"}, sa:{11:"in"}, mn:{5:"mn"}, gl:{1:"es"}, kok:{11:"in"}, syr:{32:"sy"}, dv:{6:"mv"}, nn:{1:"no"}, sr:{1:"cs", 5:"cs"}, cy:{1:"gb"}, mi:{1:"nz"}, mt:{1:"mt"}, quz:{1:"bo"}, tn:{1:"za"}, xh:{1:"za"}, zu:{1:"za"}, nso:{1:"za"}, se:{1:"no"}, smj:{1:"no"}, sma:{1:"no"}, sms:{1:"fi"}, smn:{1:"fi"}, bs:{1:"ba"}};
private static const SCRIPT_BY_ID:Object = {latn:1, ethi:2, arab:3, beng:4, cyrl:5, thaa:6, tibt:7, grek:8, gujr:9, hebr:10, deva:11, armn:12, jpan:13, geor:14, khmr:15, knda:16, kore:17, laoo:18, mlym:19, mymr:20, orya:21, guru:22, sinh:23, taml:24, telu:25, thai:26, nkoo:27, blis:28, hans:29, hant:30, mong:31, syrc:32};
private static const SCRIPT_ID_BY_LANG_AND_REGION:Object = {zh:{cn:29, sg:29, tw:30, hk:30, mo:30}, mn:{cn:31, sg:5}, pa:{pk:3, in:22}, ha:{gh:1, ne:1}};
private function LocaleRegistry(){
super();
}
public static function getScriptByLangAndRegion(lang:String, region:String):String{
var langRegions:Object = SCRIPT_ID_BY_LANG_AND_REGION[lang];
if (langRegions == null){
return ("");
};
var scriptID:Object = langRegions[region];
if (scriptID == null){
return ("");
};
return (SCRIPTS[int(scriptID)].toLowerCase());
}
public static function getScriptByLang(lang:String):String{
var scriptID:Object = SCRIPT_ID_BY_LANG[lang];
if (scriptID == null){
return ("");
};
return (SCRIPTS[int(scriptID)].toLowerCase());
}
public static function getDefaultRegionForLangAndScript(lang:String, script:String):String{
var langObj:Object = DEFAULT_REGION_BY_LANG_AND_SCRIPT[lang];
var scriptID:Object = SCRIPT_BY_ID[script];
if ((((langObj == null)) || ((scriptID == null)))){
return ("");
};
return (((langObj[int(scriptID)]) || ("")));
}
}
Section 128
//ResourceBundle (mx.resources.ResourceBundle)
package mx.resources {
import flash.system.*;
import mx.utils.*;
import mx.core.*;
public class ResourceBundle implements IResourceBundle {
mx_internal var _locale:String;
private var _content:Object;
mx_internal var _bundleName:String;
mx_internal static const VERSION:String = "3.4.0.9271";
mx_internal static var backupApplicationDomain:ApplicationDomain;
mx_internal static var locale:String;
public function ResourceBundle(locale:String=null, bundleName:String=null){
_content = {};
super();
mx_internal::_locale = locale;
mx_internal::_bundleName = bundleName;
_content = getContent();
}
protected function getContent():Object{
return ({});
}
public function getString(key:String):String{
return (String(_getObject(key)));
}
public function get content():Object{
return (_content);
}
public function getBoolean(key:String, defaultValue:Boolean=true):Boolean{
var temp:String = _getObject(key).toLowerCase();
if (temp == "false"){
return (false);
};
if (temp == "true"){
return (true);
};
return (defaultValue);
}
public function getStringArray(key:String):Array{
var array:Array = _getObject(key).split(",");
var n:int = array.length;
var i:int;
while (i < n) {
array[i] = StringUtil.trim(array[i]);
i++;
};
return (array);
}
public function getObject(key:String):Object{
return (_getObject(key));
}
private function _getObject(key:String):Object{
var value:Object = content[key];
if (!value){
throw (new Error(((("Key " + key) + " was not found in resource bundle ") + bundleName)));
};
return (value);
}
public function get locale():String{
return (mx_internal::_locale);
}
public function get bundleName():String{
return (mx_internal::_bundleName);
}
public function getNumber(key:String):Number{
return (Number(_getObject(key)));
}
private static function getClassByName(name:String, domain:ApplicationDomain):Class{
var c:Class;
if (domain.hasDefinition(name)){
c = (domain.getDefinition(name) as Class);
};
return (c);
}
public static function getResourceBundle(baseName:String, currentDomain:ApplicationDomain=null):ResourceBundle{
var className:String;
var bundleClass:Class;
var bundleObj:Object;
var bundle:ResourceBundle;
if (!currentDomain){
currentDomain = ApplicationDomain.currentDomain;
};
className = (((mx_internal::locale + "$") + baseName) + "_properties");
bundleClass = getClassByName(className, currentDomain);
if (!bundleClass){
className = (baseName + "_properties");
bundleClass = getClassByName(className, currentDomain);
};
if (!bundleClass){
className = baseName;
bundleClass = getClassByName(className, currentDomain);
};
if (((!(bundleClass)) && (mx_internal::backupApplicationDomain))){
className = (baseName + "_properties");
bundleClass = getClassByName(className, mx_internal::backupApplicationDomain);
if (!bundleClass){
className = baseName;
bundleClass = getClassByName(className, mx_internal::backupApplicationDomain);
};
};
if (bundleClass){
bundleObj = new (bundleClass);
if ((bundleObj is ResourceBundle)){
bundle = ResourceBundle(bundleObj);
return (bundle);
};
};
throw (new Error(("Could not find resource bundle " + baseName)));
}
}
}//package mx.resources
Section 129
//ResourceManager (mx.resources.ResourceManager)
package mx.resources {
import mx.core.*;
public class ResourceManager {
mx_internal static const VERSION:String = "3.4.0.9271";
private static var implClassDependency:ResourceManagerImpl;
private static var instance:IResourceManager;
public function ResourceManager(){
super();
}
public static function getInstance():IResourceManager{
if (!instance){
instance = IResourceManager(Singleton.getInstance("mx.resources::IResourceManager"));
//unresolved jump
var _slot1 = e;
instance = new ResourceManagerImpl();
};
return (instance);
}
}
}//package mx.resources
Section 130
//ResourceManagerImpl (mx.resources.ResourceManagerImpl)
package mx.resources {
import flash.events.*;
import flash.utils.*;
import mx.events.*;
import flash.system.*;
import mx.modules.*;
import mx.utils.*;
import mx.core.*;
public class ResourceManagerImpl extends EventDispatcher implements IResourceManager {
private var resourceModules:Object;
private var initializedForNonFrameworkApp:Boolean;// = false
private var localeMap:Object;
private var _localeChain:Array;
mx_internal static const VERSION:String = "3.4.0.9271";
private static var instance:IResourceManager;
public function ResourceManagerImpl(){
localeMap = {};
resourceModules = {};
super();
}
public function get localeChain():Array{
return (_localeChain);
}
public function set localeChain(value:Array):void{
_localeChain = value;
update();
}
public function getStringArray(bundleName:String, resourceName:String, locale:String=null):Array{
var resourceBundle:IResourceBundle = findBundle(bundleName, resourceName, locale);
if (!resourceBundle){
return (null);
};
var value:* = resourceBundle.content[resourceName];
var array:Array = String(value).split(",");
var n:int = array.length;
var i:int;
while (i < n) {
array[i] = StringUtil.trim(array[i]);
i++;
};
return (array);
}
mx_internal function installCompiledResourceBundle(applicationDomain:ApplicationDomain, locale:String, bundleName:String):void{
var packageName:String;
var localName:String = bundleName;
var colonIndex:int = bundleName.indexOf(":");
if (colonIndex != -1){
packageName = bundleName.substring(0, colonIndex);
localName = bundleName.substring((colonIndex + 1));
};
if (getResourceBundle(locale, bundleName)){
return;
};
var resourceBundleClassName = (((locale + "$") + localName) + "_properties");
if (packageName != null){
resourceBundleClassName = ((packageName + ".") + resourceBundleClassName);
};
var bundleClass:Class;
if (applicationDomain.hasDefinition(resourceBundleClassName)){
bundleClass = Class(applicationDomain.getDefinition(resourceBundleClassName));
};
if (!bundleClass){
resourceBundleClassName = bundleName;
if (applicationDomain.hasDefinition(resourceBundleClassName)){
bundleClass = Class(applicationDomain.getDefinition(resourceBundleClassName));
};
};
if (!bundleClass){
resourceBundleClassName = (bundleName + "_properties");
if (applicationDomain.hasDefinition(resourceBundleClassName)){
bundleClass = Class(applicationDomain.getDefinition(resourceBundleClassName));
};
};
if (!bundleClass){
throw (new Error((((("Could not find compiled resource bundle '" + bundleName) + "' for locale '") + locale) + "'.")));
};
var resourceBundle:ResourceBundle = ResourceBundle(new (bundleClass));
resourceBundle.mx_internal::_locale = locale;
resourceBundle.mx_internal::_bundleName = bundleName;
addResourceBundle(resourceBundle);
}
public function getString(bundleName:String, resourceName:String, parameters:Array=null, locale:String=null):String{
var resourceBundle:IResourceBundle = findBundle(bundleName, resourceName, locale);
if (!resourceBundle){
return (null);
};
var value:String = String(resourceBundle.content[resourceName]);
if (parameters){
value = StringUtil.substitute(value, parameters);
};
return (value);
}
public function loadResourceModule(url:String, updateFlag:Boolean=true, applicationDomain:ApplicationDomain=null, securityDomain:SecurityDomain=null):IEventDispatcher{
var moduleInfo:IModuleInfo;
var resourceEventDispatcher:ResourceEventDispatcher;
var timer:Timer;
var timerHandler:Function;
var url = url;
var updateFlag = updateFlag;
var applicationDomain = applicationDomain;
var securityDomain = securityDomain;
moduleInfo = ModuleManager.getModule(url);
resourceEventDispatcher = new ResourceEventDispatcher(moduleInfo);
var readyHandler:Function = function (event:ModuleEvent):void{
var resourceModule:* = event.module.factory.create();
resourceModules[event.module.url].resourceModule = resourceModule;
if (updateFlag){
update();
};
};
moduleInfo.addEventListener(ModuleEvent.READY, readyHandler, false, 0, true);
var errorHandler:Function = function (event:ModuleEvent):void{
var resourceEvent:ResourceEvent;
var message:String = ("Unable to load resource module from " + url);
if (resourceEventDispatcher.willTrigger(ResourceEvent.ERROR)){
resourceEvent = new ResourceEvent(ResourceEvent.ERROR, event.bubbles, event.cancelable);
resourceEvent.bytesLoaded = 0;
resourceEvent.bytesTotal = 0;
resourceEvent.errorText = message;
resourceEventDispatcher.dispatchEvent(resourceEvent);
} else {
throw (new Error(message));
};
};
moduleInfo.addEventListener(ModuleEvent.ERROR, errorHandler, false, 0, true);
resourceModules[url] = new ResourceModuleInfo(moduleInfo, readyHandler, errorHandler);
timer = new Timer(0);
timerHandler = function (event:TimerEvent):void{
timer.removeEventListener(TimerEvent.TIMER, timerHandler);
timer.stop();
moduleInfo.load(applicationDomain, securityDomain);
};
timer.addEventListener(TimerEvent.TIMER, timerHandler, false, 0, true);
timer.start();
return (resourceEventDispatcher);
}
public function getLocales():Array{
var p:String;
var locales:Array = [];
for (p in localeMap) {
locales.push(p);
};
return (locales);
}
public function removeResourceBundlesForLocale(locale:String):void{
delete localeMap[locale];
}
public function getResourceBundle(locale:String, bundleName:String):IResourceBundle{
var bundleMap:Object = localeMap[locale];
if (!bundleMap){
return (null);
};
return (bundleMap[bundleName]);
}
private function dumpResourceModule(resourceModule):void{
var bundle:ResourceBundle;
var p:String;
for each (bundle in resourceModule.resourceBundles) {
trace(bundle.locale, bundle.bundleName);
for (p in bundle.content) {
};
};
}
public function addResourceBundle(resourceBundle:IResourceBundle):void{
var locale:String = resourceBundle.locale;
var bundleName:String = resourceBundle.bundleName;
if (!localeMap[locale]){
localeMap[locale] = {};
};
localeMap[locale][bundleName] = resourceBundle;
}
public function getObject(bundleName:String, resourceName:String, locale:String=null){
var resourceBundle:IResourceBundle = findBundle(bundleName, resourceName, locale);
if (!resourceBundle){
return (undefined);
};
return (resourceBundle.content[resourceName]);
}
public function getInt(bundleName:String, resourceName:String, locale:String=null):int{
var resourceBundle:IResourceBundle = findBundle(bundleName, resourceName, locale);
if (!resourceBundle){
return (0);
};
var value:* = resourceBundle.content[resourceName];
return (int(value));
}
private function findBundle(bundleName:String, resourceName:String, locale:String):IResourceBundle{
supportNonFrameworkApps();
return (((locale)!=null) ? getResourceBundle(locale, bundleName) : findResourceBundleWithResource(bundleName, resourceName));
}
private function supportNonFrameworkApps():void{
if (initializedForNonFrameworkApp){
return;
};
initializedForNonFrameworkApp = true;
if (getLocales().length > 0){
return;
};
var applicationDomain:ApplicationDomain = ApplicationDomain.currentDomain;
if (!applicationDomain.hasDefinition("_CompiledResourceBundleInfo")){
return;
};
var c:Class = Class(applicationDomain.getDefinition("_CompiledResourceBundleInfo"));
var locales:Array = c.compiledLocales;
var bundleNames:Array = c.compiledResourceBundleNames;
installCompiledResourceBundles(applicationDomain, locales, bundleNames);
localeChain = locales;
}
public function getBundleNamesForLocale(locale:String):Array{
var p:String;
var bundleNames:Array = [];
for (p in localeMap[locale]) {
bundleNames.push(p);
};
return (bundleNames);
}
public function getPreferredLocaleChain():Array{
return (LocaleSorter.sortLocalesByPreference(getLocales(), getSystemPreferredLocales(), null, true));
}
public function getNumber(bundleName:String, resourceName:String, locale:String=null):Number{
var resourceBundle:IResourceBundle = findBundle(bundleName, resourceName, locale);
if (!resourceBundle){
return (NaN);
};
var value:* = resourceBundle.content[resourceName];
return (Number(value));
}
public function update():void{
dispatchEvent(new Event(Event.CHANGE));
}
public function getClass(bundleName:String, resourceName:String, locale:String=null):Class{
var resourceBundle:IResourceBundle = findBundle(bundleName, resourceName, locale);
if (!resourceBundle){
return (null);
};
var value:* = resourceBundle.content[resourceName];
return ((value as Class));
}
public function removeResourceBundle(locale:String, bundleName:String):void{
delete localeMap[locale][bundleName];
if (getBundleNamesForLocale(locale).length == 0){
delete localeMap[locale];
};
}
public function initializeLocaleChain(compiledLocales:Array):void{
localeChain = LocaleSorter.sortLocalesByPreference(compiledLocales, getSystemPreferredLocales(), null, true);
}
public function findResourceBundleWithResource(bundleName:String, resourceName:String):IResourceBundle{
var locale:String;
var bundleMap:Object;
var bundle:ResourceBundle;
if (!_localeChain){
return (null);
};
var n:int = _localeChain.length;
var i:int;
while (i < n) {
locale = localeChain[i];
bundleMap = localeMap[locale];
if (!bundleMap){
} else {
bundle = bundleMap[bundleName];
if (!bundle){
} else {
if ((resourceName in bundle.content)){
return (bundle);
};
};
};
i++;
};
return (null);
}
public function getUint(bundleName:String, resourceName:String, locale:String=null):uint{
var resourceBundle:IResourceBundle = findBundle(bundleName, resourceName, locale);
if (!resourceBundle){
return (0);
};
var value:* = resourceBundle.content[resourceName];
return (uint(value));
}
private function getSystemPreferredLocales():Array{
var systemPreferences:Array;
if (Capabilities["languages"]){
systemPreferences = Capabilities["languages"];
} else {
systemPreferences = [Capabilities.language];
};
return (systemPreferences);
}
public function installCompiledResourceBundles(applicationDomain:ApplicationDomain, locales:Array, bundleNames:Array):void{
var locale:String;
var j:int;
var bundleName:String;
var n:int = (locales) ? locales.length : 0;
var m:int = (bundleNames) ? bundleNames.length : 0;
var i:int;
while (i < n) {
locale = locales[i];
j = 0;
while (j < m) {
bundleName = bundleNames[j];
mx_internal::installCompiledResourceBundle(applicationDomain, locale, bundleName);
j++;
};
i++;
};
}
public function getBoolean(bundleName:String, resourceName:String, locale:String=null):Boolean{
var resourceBundle:IResourceBundle = findBundle(bundleName, resourceName, locale);
if (!resourceBundle){
return (false);
};
var value:* = resourceBundle.content[resourceName];
return ((String(value).toLowerCase() == "true"));
}
public function unloadResourceModule(url:String, update:Boolean=true):void{
var bundles:Array;
var n:int;
var i:int;
var locale:String;
var bundleName:String;
var rmi:ResourceModuleInfo = resourceModules[url];
if (!rmi){
return;
};
if (rmi.resourceModule){
bundles = rmi.resourceModule.resourceBundles;
if (bundles){
n = bundles.length;
i = 0;
while (i < n) {
locale = bundles[i].locale;
bundleName = bundles[i].bundleName;
removeResourceBundle(locale, bundleName);
i++;
};
};
};
resourceModules[url] = null;
delete resourceModules[url];
rmi.moduleInfo.unload();
if (update){
this.update();
};
}
public static function getInstance():IResourceManager{
if (!instance){
instance = new (ResourceManagerImpl);
};
return (instance);
}
}
}//package mx.resources
import flash.events.*;
import mx.events.*;
import mx.modules.*;
class ResourceModuleInfo {
public var resourceModule:IResourceModule;
public var errorHandler:Function;
public var readyHandler:Function;
public var moduleInfo:IModuleInfo;
private function ResourceModuleInfo(moduleInfo:IModuleInfo, readyHandler:Function, errorHandler:Function){
super();
this.moduleInfo = moduleInfo;
this.readyHandler = readyHandler;
this.errorHandler = errorHandler;
}
}
class ResourceEventDispatcher extends EventDispatcher {
private function ResourceEventDispatcher(moduleInfo:IModuleInfo){
super();
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler, false, 0, true);
moduleInfo.addEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler, false, 0, true);
moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler, false, 0, true);
}
private function moduleInfo_progressHandler(event:ModuleEvent):void{
var resourceEvent:ResourceEvent = new ResourceEvent(ResourceEvent.PROGRESS, event.bubbles, event.cancelable);
resourceEvent.bytesLoaded = event.bytesLoaded;
resourceEvent.bytesTotal = event.bytesTotal;
dispatchEvent(resourceEvent);
}
private function moduleInfo_readyHandler(event:ModuleEvent):void{
var resourceEvent:ResourceEvent = new ResourceEvent(ResourceEvent.COMPLETE);
dispatchEvent(resourceEvent);
}
private function moduleInfo_errorHandler(event:ModuleEvent):void{
var resourceEvent:ResourceEvent = new ResourceEvent(ResourceEvent.ERROR, event.bubbles, event.cancelable);
resourceEvent.bytesLoaded = event.bytesLoaded;
resourceEvent.bytesTotal = event.bytesTotal;
resourceEvent.errorText = event.errorText;
dispatchEvent(resourceEvent);
}
}
Section 131
//IResponder (mx.rpc.IResponder)
package mx.rpc {
public interface IResponder {
function fault(:Object):void;
function result(:Object):void;
}
}//package mx.rpc
Section 132
//ArrayUtil (mx.utils.ArrayUtil)
package mx.utils {
import mx.core.*;
public class ArrayUtil {
mx_internal static const VERSION:String = "3.4.0.9271";
public function ArrayUtil(){
super();
}
public static function getItemIndex(item:Object, source:Array):int{
var n:int = source.length;
var i:int;
while (i < n) {
if (source[i] === item){
return (i);
};
i++;
};
return (-1);
}
public static function toArray(obj:Object):Array{
if (!obj){
return ([]);
};
if ((obj is Array)){
return ((obj as Array));
};
return ([obj]);
}
}
}//package mx.utils
Section 133
//Base64Encoder (mx.utils.Base64Encoder)
package mx.utils {
import flash.utils.*;
public class Base64Encoder {
private var _line:uint;
private var _count:uint;
private var _buffers:Array;
public var insertNewLines:Boolean;// = true
private var _work:Array;
public static const MAX_BUFFER_SIZE:uint = 32767;
private static const ALPHABET_CHAR_CODES:Array = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47];
public static const CHARSET_UTF_8:String = "UTF-8";
private static const ESCAPE_CHAR_CODE:Number = 61;
public static var newLine:int = 10;
public function Base64Encoder(){
_work = [0, 0, 0];
super();
reset();
}
public function flush():String{
if (_count > 0){
encodeBlock();
};
var result:String = drain();
reset();
return (result);
}
public function toString():String{
return (flush());
}
public function reset():void{
_buffers = [];
_buffers.push([]);
_count = 0;
_line = 0;
_work[0] = 0;
_work[1] = 0;
_work[2] = 0;
}
public function encodeBytes(data:ByteArray, offset:uint=0, length:uint=0):void{
if (length == 0){
length = data.length;
};
var oldPosition:uint = data.position;
data.position = offset;
var currentIndex:uint = offset;
var endIndex:uint = (offset + length);
if (endIndex > data.length){
endIndex = data.length;
};
while (currentIndex < endIndex) {
_work[_count] = data[currentIndex];
_count++;
if ((((_count == _work.length)) || (((endIndex - currentIndex) == 1)))){
encodeBlock();
_count = 0;
_work[0] = 0;
_work[1] = 0;
_work[2] = 0;
};
currentIndex++;
};
data.position = oldPosition;
}
public function encode(data:String, offset:uint=0, length:uint=0):void{
if (length == 0){
length = data.length;
};
var currentIndex:uint = offset;
var endIndex:uint = (offset + length);
if (endIndex > data.length){
endIndex = data.length;
};
while (currentIndex < endIndex) {
_work[_count] = data.charCodeAt(currentIndex);
_count++;
if ((((_count == _work.length)) || (((endIndex - currentIndex) == 1)))){
encodeBlock();
_count = 0;
_work[0] = 0;
_work[1] = 0;
_work[2] = 0;
};
currentIndex++;
};
}
private function encodeBlock():void{
var currentBuffer:Array = (_buffers[(_buffers.length - 1)] as Array);
if (currentBuffer.length >= MAX_BUFFER_SIZE){
currentBuffer = [];
_buffers.push(currentBuffer);
};
currentBuffer.push(ALPHABET_CHAR_CODES[((_work[0] & 0xFF) >> 2)]);
currentBuffer.push(ALPHABET_CHAR_CODES[(((_work[0] & 3) << 4) | ((_work[1] & 240) >> 4))]);
if (_count > 1){
currentBuffer.push(ALPHABET_CHAR_CODES[(((_work[1] & 15) << 2) | ((_work[2] & 192) >> 6))]);
} else {
currentBuffer.push(ESCAPE_CHAR_CODE);
};
if (_count > 2){
currentBuffer.push(ALPHABET_CHAR_CODES[(_work[2] & 63)]);
} else {
currentBuffer.push(ESCAPE_CHAR_CODE);
};
if (insertNewLines){
if ((_line = (_line + 4)) == 76){
currentBuffer.push(newLine);
_line = 0;
};
};
}
public function encodeUTFBytes(data:String):void{
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(data);
bytes.position = 0;
encodeBytes(bytes);
}
public function drain():String{
var buffer:Array;
var result:String = "";
var i:uint;
while (i < _buffers.length) {
buffer = (_buffers[i] as Array);
result = (result + String.fromCharCode.apply(null, buffer));
i++;
};
_buffers = [];
_buffers.push([]);
return (result);
}
}
}//package mx.utils
Section 134
//DescribeTypeCache (mx.utils.DescribeTypeCache)
package mx.utils {
import flash.utils.*;
import mx.core.*;
import mx.binding.*;
public class DescribeTypeCache {
mx_internal static const VERSION:String = "3.4.0.9271";
private static var cacheHandlers:Object = {};
private static var typeCache:Object = {};
public function DescribeTypeCache(){
super();
}
public static function describeType(o):DescribeTypeCacheRecord{
var className:String;
var typeDescription:XML;
var record:DescribeTypeCacheRecord;
if ((o is String)){
className = o;
} else {
className = getQualifiedClassName(o);
};
if ((className in typeCache)){
return (typeCache[className]);
};
if ((o is String)){
o = getDefinitionByName(o);
};
typeDescription = describeType(o);
record = new DescribeTypeCacheRecord();
record.typeDescription = typeDescription;
record.typeName = className;
typeCache[className] = record;
return (record);
}
public static function registerCacheHandler(valueName:String, handler:Function):void{
cacheHandlers[valueName] = handler;
}
static function extractValue(valueName:String, record:DescribeTypeCacheRecord){
if ((valueName in cacheHandlers)){
return (cacheHandlers[valueName](record));
};
return (undefined);
}
private static function bindabilityInfoHandler(record:DescribeTypeCacheRecord){
return (new BindabilityInfo(record.typeDescription));
}
registerCacheHandler("bindabilityInfo", bindabilityInfoHandler);
}
}//package mx.utils
Section 135
//DescribeTypeCacheRecord (mx.utils.DescribeTypeCacheRecord)
package mx.utils {
import flash.utils.*;
public dynamic class DescribeTypeCacheRecord extends Proxy {
public var typeDescription:XML;
public var typeName:String;
private var cache:Object;
public function DescribeTypeCacheRecord(){
cache = {};
super();
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function getProperty(name){
var result:* = cache[name];
if (result === undefined){
result = DescribeTypeCache.extractValue(name, this);
cache[name] = result;
};
return (result);
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function hasProperty(name):Boolean{
if ((name in cache)){
return (true);
};
var value:* = DescribeTypeCache.extractValue(name, this);
if (value === undefined){
return (false);
};
cache[name] = value;
return (true);
}
}
}//package mx.utils
Section 136
//IXMLNotifiable (mx.utils.IXMLNotifiable)
package mx.utils {
public interface IXMLNotifiable {
function xmlNotification(_arg1:Object, _arg2:String, _arg3:Object, _arg4:Object, _arg5:Object):void;
}
}//package mx.utils
Section 137
//object_proxy (mx.utils.object_proxy)
package mx.utils {
public namespace object_proxy = "http://www.adobe.com/2006/actionscript/flash/objectproxy";
}//package mx.utils
Section 138
//ObjectProxy (mx.utils.ObjectProxy)
package mx.utils {
import flash.events.*;
import flash.utils.*;
import mx.events.*;
import mx.core.*;
public dynamic class ObjectProxy extends Proxy implements IExternalizable, IPropertyChangeNotifier {
private var _id:String;
protected var notifiers:Object;
protected var propertyList:Array;
private var _proxyLevel:int;
private var _type:QName;
protected var dispatcher:EventDispatcher;
protected var proxyClass:Class;
private var _item:Object;
public function ObjectProxy(item:Object=null, uid:String=null, proxyDepth:int=-1){
proxyClass = ObjectProxy;
super();
if (!item){
item = {};
};
_item = item;
_proxyLevel = proxyDepth;
notifiers = {};
dispatcher = new EventDispatcher(this);
if (uid){
_id = uid;
};
}
public function dispatchEvent(event:Event):Boolean{
return (dispatcher.dispatchEvent(event));
}
public function hasEventListener(type:String):Boolean{
return (dispatcher.hasEventListener(type));
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function setProperty(name, value):void{
var notifier:IPropertyChangeNotifier;
var event:PropertyChangeEvent;
var oldVal:* = _item[name];
if (oldVal !== value){
_item[name] = value;
notifier = IPropertyChangeNotifier(notifiers[name]);
if (notifier){
notifier.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, propertyChangeHandler);
delete notifiers[name];
};
if (dispatcher.hasEventListener(PropertyChangeEvent.PROPERTY_CHANGE)){
if ((name is QName)){
name = QName(name).localName;
};
event = PropertyChangeEvent.createUpdateEvent(this, name.toString(), oldVal, value);
dispatcher.dispatchEvent(event);
};
};
}
public function willTrigger(type:String):Boolean{
return (dispatcher.willTrigger(type));
}
public function readExternal(input:IDataInput):void{
var value:Object = input.readObject();
_item = value;
}
public function writeExternal(output:IDataOutput):void{
output.writeObject(_item);
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function getProperty(name){
var result:*;
if (notifiers[name.toString()]){
return (notifiers[name]);
};
result = _item[name];
if (result){
if ((((_proxyLevel == 0)) || (ObjectUtil.isSimple(result)))){
return (result);
};
result = getComplexProperty(name, result);
};
return (result);
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function hasProperty(name):Boolean{
return ((name in _item));
}
public function get uid():String{
if (_id === null){
_id = UIDUtil.createUID();
};
return (_id);
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function nextNameIndex(index:int):int{
if (index == 0){
setupPropertyList();
};
if (index < propertyList.length){
return ((index + 1));
};
return (0);
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void{
dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function nextName(index:int):String{
return (propertyList[(index - 1)]);
}
public function set uid(value:String):void{
_id = value;
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function callProperty(name, ... _args){
return (_item[name].apply(_item, _args));
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void{
dispatcher.removeEventListener(type, listener, useCapture);
}
protected function setupPropertyList():void{
var prop:String;
if (getQualifiedClassName(_item) == "Object"){
propertyList = [];
for (prop in _item) {
propertyList.push(prop);
};
} else {
propertyList = ObjectUtil.getClassInfo(_item, null, {includeReadOnly:true, uris:["*"]}).properties;
};
}
object_proxy function getComplexProperty(name, value){
if ((value is IPropertyChangeNotifier)){
value.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, propertyChangeHandler);
notifiers[name] = value;
return (value);
};
if (getQualifiedClassName(value) == "Object"){
value = new proxyClass(_item[name], null, ((_proxyLevel > 0)) ? (_proxyLevel - 1) : _proxyLevel);
value.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, propertyChangeHandler);
notifiers[name] = value;
return (value);
};
return (value);
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function deleteProperty(name):Boolean{
var event:PropertyChangeEvent;
var notifier:IPropertyChangeNotifier = IPropertyChangeNotifier(notifiers[name]);
if (notifier){
notifier.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, propertyChangeHandler);
delete notifiers[name];
};
var oldVal:* = _item[name];
var deleted = delete _item[name];
if (dispatcher.hasEventListener(PropertyChangeEvent.PROPERTY_CHANGE)){
event = new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE);
event.kind = PropertyChangeEventKind.DELETE;
event.property = name;
event.oldValue = oldVal;
event.source = this;
dispatcher.dispatchEvent(event);
};
return (deleted);
}
object_proxy function get type():QName{
return (_type);
}
object_proxy function set type(value:QName):void{
_type = value;
}
public function propertyChangeHandler(event:PropertyChangeEvent):void{
dispatcher.dispatchEvent(event);
}
override "http://www.adobe.com/2006/actionscript/flash/proxy"?? function nextValue(index:int){
return (_item[propertyList[(index - 1)]]);
}
object_proxy function get object():Object{
return (_item);
}
}
}//package mx.utils
Section 139
//ObjectUtil (mx.utils.ObjectUtil)
package mx.utils {
import flash.utils.*;
import flash.xml.*;
import mx.collections.*;
import mx.core.*;
public class ObjectUtil {
mx_internal static const VERSION:String = "3.4.0.9271";
private static var defaultToStringExcludes:Array = ["password", "credentials"];
private static var CLASS_INFO_CACHE:Object = {};
private static var refCount:int = 0;
public function ObjectUtil(){
super();
}
public static function isSimple(value:Object):Boolean{
var type = typeof(value);
switch (type){
case "number":
case "string":
case "boolean":
return (true);
case "object":
return ((((value is Date)) || ((value is Array))));
};
return (false);
}
private static function internalToString(value:Object, indent:int=0, refs:Dictionary=null, namespaceURIs:Array=null, exclude:Array=null):String{
var str:String;
var classInfo:Object;
var properties:Array;
var isArray:Boolean;
var isDict:Boolean;
var prop:*;
var j:int;
var id:Object;
var value = value;
var indent = indent;
var refs = refs;
var namespaceURIs = namespaceURIs;
var exclude = exclude;
var type:String = ((value == null)) ? "null" : typeof(value);
switch (type){
case "boolean":
case "number":
return (value.toString());
case "string":
return ((("\"" + value.toString()) + "\""));
case "object":
if ((value is Date)){
return (value.toString());
};
if ((value is XMLNode)){
return (value.toString());
};
if ((value is Class)){
return ((("(" + getQualifiedClassName(value)) + ")"));
};
classInfo = getClassInfo(value, exclude, {includeReadOnly:true, uris:namespaceURIs});
properties = classInfo.properties;
str = (("(" + classInfo.name) + ")");
if (refs == null){
refs = new Dictionary(true);
};
id = refs[value];
if (id != null){
str = (str + ("#" + int(id)));
return (str);
};
//unresolved jump
var _slot1 = e;
return (String(value));
if (value != null){
str = (str + ("#" + refCount.toString()));
refs[value] = refCount;
refCount++;
};
isArray = (value is Array);
isDict = (value is Dictionary);
indent = (indent + 2);
j = 0;
for (;j < properties.length;(j = (j + 1))) {
str = newline(str, indent);
prop = properties[j];
if (isArray){
str = (str + "[");
} else {
if (isDict){
str = (str + "{");
};
};
if (isDict){
str = (str + internalToString(prop, indent, refs, namespaceURIs, exclude));
} else {
str = (str + prop.toString());
};
if (isArray){
str = (str + "] ");
} else {
if (isDict){
str = (str + "} = ");
} else {
str = (str + " = ");
};
};
str = (str + internalToString(value[prop], indent, refs, namespaceURIs, exclude));
continue;
var _slot1 = e;
str = (str + "?");
};
indent = (indent - 2);
return (str);
case "xml":
return (value.toString());
default:
return ((("(" + type) + ")"));
};
}
public static function getClassInfo(obj:Object, excludes:Array=null, options:Object=null):Object{
var n:int;
var i:int;
var result:Object;
var cacheKey:String;
var className:String;
var classAlias:String;
var properties:XMLList;
var prop:XML;
var metadataInfo:Object;
var classInfo:XML;
var numericIndex:Boolean;
var key:*;
var p:String;
var pi:Number;
var uris:Array;
var uri:String;
var qName:QName;
var j:int;
var obj = obj;
var excludes = excludes;
var options = options;
if ((obj is ObjectProxy)){
obj = ObjectProxy(obj).object_proxy::object;
};
if (options == null){
options = {includeReadOnly:true, uris:null, includeTransient:true};
};
var propertyNames:Array = [];
var dynamic:Boolean;
if (typeof(obj) == "xml"){
className = "XML";
properties = obj.text();
if (properties.length()){
propertyNames.push("*");
};
properties = obj.attributes();
} else {
classInfo = DescribeTypeCache.describeType(obj).typeDescription;
className = classInfo.@name.toString();
classAlias = classInfo.@alias.toString();
dynamic = (classInfo.@isDynamic.toString() == "true");
if (options.includeReadOnly){
properties = (classInfo..accessor.(@access != "writeonly") + classInfo..variable);
} else {
properties = (classInfo..accessor.(@access == "readwrite") + classInfo..variable);
};
numericIndex = false;
};
if (!dynamic){
cacheKey = getCacheKey(obj, excludes, options);
result = CLASS_INFO_CACHE[cacheKey];
if (result != null){
return (result);
};
};
result = {};
result["name"] = className;
result["alias"] = classAlias;
result["properties"] = propertyNames;
result["dynamic"] = dynamic;
var _local5 = recordMetadata(properties);
metadataInfo = _local5;
result["metadata"] = _local5;
var excludeObject:Object = {};
if (excludes){
n = excludes.length;
i = 0;
while (i < n) {
excludeObject[excludes[i]] = 1;
i = (i + 1);
};
};
var isArray = (className == "Array");
var isDict = (className == "flash.utils::Dictionary");
if (isDict){
for (key in obj) {
propertyNames.push(key);
};
} else {
if (dynamic){
for (p in obj) {
if (excludeObject[p] != 1){
if (isArray){
pi = parseInt(p);
if (isNaN(pi)){
propertyNames.push(new QName("", p));
} else {
propertyNames.push(pi);
};
} else {
propertyNames.push(new QName("", p));
};
};
};
numericIndex = ((isArray) && (!(isNaN(Number(p)))));
};
};
if (((((isArray) || (isDict))) || ((className == "Object")))){
} else {
if (className == "XML"){
n = properties.length();
i = 0;
while (i < n) {
p = properties[i].name();
if (excludeObject[p] != 1){
propertyNames.push(new QName("", ("@" + p)));
};
i = (i + 1);
};
} else {
n = properties.length();
uris = options.uris;
i = 0;
for (;i < n;(i = (i + 1))) {
prop = properties[i];
p = prop.@name.toString();
uri = prop.@uri.toString();
if (excludeObject[p] == 1){
} else {
if (((!(options.includeTransient)) && (internalHasMetadata(metadataInfo, p, "Transient")))){
} else {
if (uris != null){
if ((((uris.length == 1)) && ((uris[0] == "*")))){
qName = new QName(uri, p);
obj[qName];
propertyNames.push();
//unresolved jump
var _slot1 = e;
} else {
j = 0;
for (;j < uris.length;(j = (j + 1))) {
uri = uris[j];
if (prop.@uri.toString() == uri){
qName = new QName(uri, p);
obj[qName];
propertyNames.push(qName);
continue;
var _slot1 = e;
};
};
};
} else {
if (uri.length == 0){
qName = new QName(uri, p);
obj[qName];
propertyNames.push(qName);
continue;
var _slot1 = e;
};
};
};
};
};
};
};
propertyNames.sort((Array.CASEINSENSITIVE | (numericIndex) ? Array.NUMERIC : 0));
if (!isDict){
i = 0;
while (i < (propertyNames.length - 1)) {
if (propertyNames[i].toString() == propertyNames[(i + 1)].toString()){
propertyNames.splice(i, 1);
i = (i - 1);
};
i = (i + 1);
};
};
if (!dynamic){
cacheKey = getCacheKey(obj, excludes, options);
CLASS_INFO_CACHE[cacheKey] = result;
};
return (result);
}
private static function arrayCompare(a:Array, b:Array, currentDepth:int, desiredDepth:int, refs:Dictionary):int{
var key:Object;
var result:int;
if (a.length != b.length){
if (a.length < b.length){
result = -1;
} else {
result = 1;
};
} else {
for (key in a) {
if (b.hasOwnProperty(key)){
result = internalCompare(a[key], b[key], currentDepth, desiredDepth, refs);
if (result != 0){
return (result);
};
} else {
return (-1);
};
};
for (key in b) {
if (!a.hasOwnProperty(key)){
return (1);
};
};
};
return (result);
}
public static function stringCompare(a:String, b:String, caseInsensitive:Boolean=false):int{
if ((((a == null)) && ((b == null)))){
return (0);
};
if (a == null){
return (1);
};
if (b == null){
return (-1);
};
if (caseInsensitive){
a = a.toLocaleLowerCase();
b = b.toLocaleLowerCase();
};
var result:int = a.localeCompare(b);
if (result < -1){
result = -1;
} else {
if (result > 1){
result = 1;
};
};
return (result);
}
public static function dateCompare(a:Date, b:Date):int{
if ((((a == null)) && ((b == null)))){
return (0);
};
if (a == null){
return (1);
};
if (b == null){
return (-1);
};
var na:Number = a.getTime();
var nb:Number = b.getTime();
if (na < nb){
return (-1);
};
if (na > nb){
return (1);
};
return (0);
}
public static function numericCompare(a:Number, b:Number):int{
if (((isNaN(a)) && (isNaN(b)))){
return (0);
};
if (isNaN(a)){
return (1);
};
if (isNaN(b)){
return (-1);
};
if (a < b){
return (-1);
};
if (a > b){
return (1);
};
return (0);
}
private static function newline(str:String, n:int=0):String{
var result:String = str;
result = (result + "\n");
var i:int;
while (i < n) {
result = (result + " ");
i++;
};
return (result);
}
private static function recordMetadata(properties:XMLList):Object{
var prop:XML;
var propName:String;
var metadataList:XMLList;
var metadata:Object;
var md:XML;
var mdName:String;
var argsList:XMLList;
var value:Object;
var arg:XML;
var existing:Object;
var argKey:String;
var argValue:String;
var existingArray:Array;
var properties = properties;
var result:Object;
for each (prop in properties) {
propName = prop.attribute("name").toString();
metadataList = prop.metadata;
if (metadataList.length() > 0){
if (result == null){
result = {};
};
metadata = {};
result[propName] = metadata;
for each (md in metadataList) {
mdName = md.attribute("name").toString();
argsList = md.arg;
value = {};
for each (arg in argsList) {
argKey = arg.attribute("key").toString();
if (argKey != null){
argValue = arg.attribute("value").toString();
value[argKey] = argValue;
};
};
existing = metadata[mdName];
if (existing != null){
if ((existing is Array)){
existingArray = (existing as Array);
} else {
existingArray = [existing];
delete metadata[mdName];
};
existingArray.push(value);
existing = existingArray;
} else {
existing = value;
};
metadata[mdName] = existing;
};
};
};
//unresolved jump
var _slot1 = e;
return (result);
}
public static function compare(a:Object, b:Object, depth:int=-1):int{
return (internalCompare(a, b, 0, depth, new Dictionary(true)));
}
private static function listCompare(a:IList, b:IList, currentDepth:int, desiredDepth:int, refs:Dictionary):int{
var i:int;
var result:int;
if (a.length != b.length){
if (a.length < b.length){
result = -1;
} else {
result = 1;
};
} else {
i = 0;
while (i < a.length) {
result = internalCompare(a.getItemAt(i), b.getItemAt(i), (currentDepth + 1), desiredDepth, refs);
if (result != 0){
i = a.length;
};
i++;
};
};
return (result);
}
private static function internalCompare(a:Object, b:Object, currentDepth:int, desiredDepth:int, refs:Dictionary):int{
var newDepth:int;
var aRef:Boolean;
var bRef:Boolean;
var aProps:Array;
var bProps:Array;
var propName:QName;
var aProp:Object;
var bProp:Object;
var i:int;
if ((((a == null)) && ((b == null)))){
return (0);
};
if (a == null){
return (1);
};
if (b == null){
return (-1);
};
if ((a is ObjectProxy)){
a = ObjectProxy(a).object_proxy::object;
};
if ((b is ObjectProxy)){
b = ObjectProxy(b).object_proxy::object;
};
var typeOfA = typeof(a);
var typeOfB = typeof(b);
var result:int;
if (typeOfA == typeOfB){
switch (typeOfA){
case "boolean":
result = numericCompare(Number(a), Number(b));
break;
case "number":
result = numericCompare((a as Number), (b as Number));
break;
case "string":
result = stringCompare((a as String), (b as String));
break;
case "object":
newDepth = ((desiredDepth > 0)) ? (desiredDepth - 1) : desiredDepth;
aRef = refs[a];
bRef = refs[b];
if (((aRef) && (!(bRef)))){
return (1);
};
if (((bRef) && (!(aRef)))){
return (-1);
};
if (((bRef) && (aRef))){
return (0);
};
refs[a] = true;
refs[b] = true;
if (((!((desiredDepth == -1))) && ((currentDepth > desiredDepth)))){
result = stringCompare(a.toString(), b.toString());
} else {
if ((((a is Array)) && ((b is Array)))){
result = arrayCompare((a as Array), (b as Array), currentDepth, desiredDepth, refs);
} else {
if ((((a is Date)) && ((b is Date)))){
result = dateCompare((a as Date), (b as Date));
} else {
if ((((a is IList)) && ((b is IList)))){
result = listCompare((a as IList), (b as IList), currentDepth, desiredDepth, refs);
} else {
if ((((a is ByteArray)) && ((b is ByteArray)))){
result = byteArrayCompare((a as ByteArray), (b as ByteArray));
} else {
if (getQualifiedClassName(a) == getQualifiedClassName(b)){
aProps = getClassInfo(a).properties;
if (getQualifiedClassName(a) == "Object"){
bProps = getClassInfo(b).properties;
result = arrayCompare(aProps, bProps, currentDepth, newDepth, refs);
};
if (result != 0){
return (result);
};
i = 0;
while (i < aProps.length) {
propName = aProps[i];
aProp = a[propName];
bProp = b[propName];
result = internalCompare(aProp, bProp, (currentDepth + 1), newDepth, refs);
if (result != 0){
i = aProps.length;
};
i++;
};
} else {
return (1);
};
};
};
};
};
};
break;
};
} else {
return (stringCompare(typeOfA, typeOfB));
};
return (result);
}
public static function hasMetadata(obj:Object, propName:String, metadataName:String, excludes:Array=null, options:Object=null):Boolean{
var classInfo:Object = getClassInfo(obj, excludes, options);
var metadataInfo:Object = classInfo["metadata"];
return (internalHasMetadata(metadataInfo, propName, metadataName));
}
private static function internalHasMetadata(metadataInfo:Object, propName:String, metadataName:String):Boolean{
var metadata:Object;
if (metadataInfo != null){
metadata = metadataInfo[propName];
if (metadata != null){
if (metadata[metadataName] != null){
return (true);
};
};
};
return (false);
}
public static function toString(value:Object, namespaceURIs:Array=null, exclude:Array=null):String{
if (exclude == null){
exclude = defaultToStringExcludes;
};
refCount = 0;
return (internalToString(value, 0, null, namespaceURIs, exclude));
}
private static function byteArrayCompare(a:ByteArray, b:ByteArray):int{
var i:int;
var result:int;
if (a == b){
return (result);
};
if (a.length != b.length){
if (a.length < b.length){
result = -1;
} else {
result = 1;
};
} else {
i = 0;
while (i < a.length) {
result = numericCompare(a[i], b[i]);
if (result != 0){
i = a.length;
};
i++;
};
};
return (result);
}
public static function copy(value:Object):Object{
var buffer:ByteArray = new ByteArray();
buffer.writeObject(value);
buffer.position = 0;
var result:Object = buffer.readObject();
return (result);
}
private static function getCacheKey(o:Object, excludes:Array=null, options:Object=null):String{
var i:uint;
var excl:String;
var flag:String;
var value:String;
var key:String = getQualifiedClassName(o);
if (excludes != null){
i = 0;
while (i < excludes.length) {
excl = (excludes[i] as String);
if (excl != null){
key = (key + excl);
};
i++;
};
};
if (options != null){
for (flag in options) {
key = (key + flag);
value = (options[flag] as String);
if (value != null){
key = (key + value);
};
};
};
return (key);
}
}
}//package mx.utils
Section 140
//StringUtil (mx.utils.StringUtil)
package mx.utils {
import mx.core.*;
public class StringUtil {
mx_internal static const VERSION:String = "3.4.0.9271";
public function StringUtil(){
super();
}
public static function trim(str:String):String{
if (str == null){
return ("");
};
var startIndex:int;
while (isWhitespace(str.charAt(startIndex))) {
startIndex++;
};
var endIndex:int = (str.length - 1);
while (isWhitespace(str.charAt(endIndex))) {
endIndex--;
};
if (endIndex >= startIndex){
return (str.slice(startIndex, (endIndex + 1)));
};
return ("");
}
public static function isWhitespace(character:String):Boolean{
switch (character){
case " ":
case "\t":
case "\r":
case "\n":
case "\f":
return (true);
default:
return (false);
};
}
public static function substitute(str:String, ... _args):String{
var args:Array;
if (str == null){
return ("");
};
var len:uint = _args.length;
if ((((len == 1)) && ((_args[0] is Array)))){
args = (_args[0] as Array);
len = args.length;
} else {
args = _args;
};
var i:int;
while (i < len) {
str = str.replace(new RegExp((("\\{" + i) + "\\}"), "g"), args[i]);
i++;
};
return (str);
}
public static function trimArrayElements(value:String, delimiter:String):String{
var items:Array;
var len:int;
var i:int;
if (((!((value == ""))) && (!((value == null))))){
items = value.split(delimiter);
len = items.length;
i = 0;
while (i < len) {
items[i] = StringUtil.trim(items[i]);
i++;
};
if (len > 0){
value = items.join(delimiter);
};
};
return (value);
}
}
}//package mx.utils
Section 141
//UIDUtil (mx.utils.UIDUtil)
package mx.utils {
import flash.utils.*;
import mx.core.*;
public class UIDUtil {
mx_internal static const VERSION:String = "3.4.0.9271";
private static const ALPHA_CHAR_CODES:Array = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70];
private static var uidDictionary:Dictionary = new Dictionary(true);
public function UIDUtil(){
super();
}
public static function fromByteArray(ba:ByteArray):String{
var chars:Array;
var index:uint;
var i:uint;
var b:int;
if (((((!((ba == null))) && ((ba.length >= 16)))) && ((ba.bytesAvailable >= 16)))){
chars = new Array(36);
index = 0;
i = 0;
while (i < 16) {
if ((((((((i == 4)) || ((i == 6)))) || ((i == 8)))) || ((i == 10)))){
var _temp1 = index;
index = (index + 1);
var _local6 = _temp1;
chars[_local6] = 45;
};
b = ba.readByte();
var _temp2 = index;
index = (index + 1);
_local6 = _temp2;
chars[_local6] = ALPHA_CHAR_CODES[((b & 240) >>> 4)];
var _temp3 = index;
index = (index + 1);
var _local7 = _temp3;
chars[_local7] = ALPHA_CHAR_CODES[(b & 15)];
i++;
};
return (String.fromCharCode.apply(null, chars));
};
return (null);
}
public static function isUID(uid:String):Boolean{
var i:uint;
var c:Number;
if (((!((uid == null))) && ((uid.length == 36)))){
i = 0;
while (i < 36) {
c = uid.charCodeAt(i);
if ((((((((i == 8)) || ((i == 13)))) || ((i == 18)))) || ((i == 23)))){
if (c != 45){
return (false);
};
} else {
if ((((((c < 48)) || ((c > 70)))) || ((((c > 57)) && ((c < 65)))))){
return (false);
};
};
i++;
};
return (true);
};
return (false);
}
public static function createUID():String{
var i:int;
var j:int;
var uid:Array = new Array(36);
var index:int;
i = 0;
while (i < 8) {
var _temp1 = index;
index = (index + 1);
var _local7 = _temp1;
uid[_local7] = ALPHA_CHAR_CODES[Math.floor((Math.random() * 16))];
i++;
};
i = 0;
while (i < 3) {
var _temp2 = index;
index = (index + 1);
_local7 = _temp2;
uid[_local7] = 45;
j = 0;
while (j < 4) {
var _temp3 = index;
index = (index + 1);
var _local8 = _temp3;
uid[_local8] = ALPHA_CHAR_CODES[Math.floor((Math.random() * 16))];
j++;
};
i++;
};
var _temp4 = index;
index = (index + 1);
_local7 = _temp4;
uid[_local7] = 45;
var time:Number = new Date().getTime();
var timeString:String = ("0000000" + time.toString(16).toUpperCase()).substr(-8);
i = 0;
while (i < 8) {
var _temp5 = index;
index = (index + 1);
_local8 = _temp5;
uid[_local8] = timeString.charCodeAt(i);
i++;
};
i = 0;
while (i < 4) {
var _temp6 = index;
index = (index + 1);
_local8 = _temp6;
uid[_local8] = ALPHA_CHAR_CODES[Math.floor((Math.random() * 16))];
i++;
};
return (String.fromCharCode.apply(null, uid));
}
public static function toByteArray(uid:String):ByteArray{
var result:ByteArray;
var i:uint;
var c:String;
var h1:uint;
var h2:uint;
if (isUID(uid)){
result = new ByteArray();
i = 0;
while (i < uid.length) {
c = uid.charAt(i);
if (c == "-"){
} else {
h1 = getDigit(c);
i++;
h2 = getDigit(uid.charAt(i));
result.writeByte((((h1 << 4) | h2) & 0xFF));
};
i++;
};
result.position = 0;
return (result);
};
return (null);
}
private static function getDigit(hex:String):uint{
switch (hex){
case "A":
case "a":
return (10);
case "B":
case "b":
return (11);
case "C":
case "c":
return (12);
case "D":
case "d":
return (13);
case "E":
case "e":
return (14);
case "F":
case "f":
return (15);
default:
return (new uint(hex));
};
}
public static function getUID(item:Object):String{
var result:String;
var xitem:XML;
var nodeKind:String;
var notificationFunction:Function;
var item = item;
result = null;
if (item == null){
return (result);
};
if ((item is IUID)){
result = IUID(item).uid;
if ((((result == null)) || ((result.length == 0)))){
result = createUID();
IUID(item).uid = result;
};
} else {
if ((((item is IPropertyChangeNotifier)) && (!((item is IUIComponent))))){
result = IPropertyChangeNotifier(item).uid;
if ((((result == null)) || ((result.length == 0)))){
result = createUID();
IPropertyChangeNotifier(item).uid = result;
};
} else {
if ((item is String)){
return ((item as String));
};
if ((((item is XMLList)) && ((item.length == 1)))){
item = item[0];
};
if ((item is XML)){
xitem = XML(item);
nodeKind = xitem.nodeKind();
if ((((nodeKind == "text")) || ((nodeKind == "attribute")))){
return (xitem.toString());
};
notificationFunction = xitem.notification();
if (!(notificationFunction is Function)){
notificationFunction = XMLNotifier.initializeXMLForNotification();
xitem.setNotification(notificationFunction);
};
if (notificationFunction["uid"] == undefined){
result = (notificationFunction["uid"] = createUID());
};
result = notificationFunction["uid"];
} else {
if (("mx_internal_uid" in item)){
return (item.mx_internal_uid);
};
if (("uid" in item)){
return (item.uid);
};
result = uidDictionary[item];
if (!result){
result = createUID();
item.mx_internal_uid = result;
//unresolved jump
var _slot1 = e;
uidDictionary[item] = result;
};
};
//unresolved jump
var _slot1 = e;
result = item.toString();
};
};
return (result);
}
}
}//package mx.utils
Section 142
//XMLNotifier (mx.utils.XMLNotifier)
package mx.utils {
import flash.utils.*;
import mx.core.*;
public class XMLNotifier {
mx_internal static const VERSION:String = "3.4.0.9271";
private static var instance:XMLNotifier;
public function XMLNotifier(x:XMLNotifierSingleton){
super();
}
public function watchXML(xml:Object, notifiable:IXMLNotifiable, uid:String=null):void{
var xmlWatchers:Dictionary;
var xitem:XML = XML(xml);
var watcherFunction:Object = xitem.notification();
if (!(watcherFunction is Function)){
watcherFunction = initializeXMLForNotification();
xitem.setNotification((watcherFunction as Function));
if (((uid) && ((watcherFunction["uid"] == null)))){
watcherFunction["uid"] = uid;
};
};
if (watcherFunction["watched"] == undefined){
xmlWatchers = new Dictionary(true);
watcherFunction["watched"] = xmlWatchers;
} else {
xmlWatchers = watcherFunction["watched"];
};
xmlWatchers[notifiable] = true;
}
public function unwatchXML(xml:Object, notifiable:IXMLNotifiable):void{
var xmlWatchers:Dictionary;
var xitem:XML = XML(xml);
var watcherFunction:Object = xitem.notification();
if (!(watcherFunction is Function)){
return;
};
if (watcherFunction["watched"] != undefined){
xmlWatchers = watcherFunction["watched"];
delete xmlWatchers[notifiable];
};
}
public static function getInstance():XMLNotifier{
if (!instance){
instance = new XMLNotifier(new XMLNotifierSingleton());
};
return (instance);
}
mx_internal static function initializeXMLForNotification():Function{
var notificationFunction:Function = function (currentTarget:Object, ty:String, tar:Object, value:Object, detail:Object):void{
var notifiable:Object;
var xmlWatchers:Dictionary = arguments.callee.watched;
if (xmlWatchers != null){
for (notifiable in xmlWatchers) {
IXMLNotifiable(notifiable).xmlNotification(currentTarget, ty, tar, value, detail);
};
};
};
return (notificationFunction);
}
}
}//package mx.utils
class XMLNotifierSingleton {
private function XMLNotifierSingleton(){
super();
}
}
Section 143
//Anonymous (org.jivesoftware.xiff.auth.Anonymous)
package org.jivesoftware.xiff.auth {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
public class Anonymous extends SASLAuth {
public function Anonymous(connection:XMPPConnection):void{
super();
var attrs:Object = {mechanism:"ANONYMOUS", xmlns:"urn:ietf:params:xml:ns:xmpp-sasl"};
req = new XMLNode(1, "auth");
req.attributes = attrs;
stage = 0;
}
override public function handleResponse(stage:int, response:XMLNode):Object{
var success = (response.nodeName == "success");
var _temp1 = stage;
stage = (stage + 1);
return ({authComplete:true, authSuccess:success, authStage:_temp1});
}
}
}//package org.jivesoftware.xiff.auth
Section 144
//Plain (org.jivesoftware.xiff.auth.Plain)
package org.jivesoftware.xiff.auth {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
import mx.utils.*;
public class Plain extends SASLAuth {
public function Plain(connection:XMPPConnection):void{
super();
var jid:JID = connection.jid;
var authContent:String = jid.toBareJID();
authContent = (authContent + "\x00");
authContent = (authContent + jid.node);
authContent = (authContent + "\x00");
authContent = (authContent + connection.password);
var b64coder:Base64Encoder = new Base64Encoder();
b64coder.insertNewLines = false;
b64coder.encode(authContent);
authContent = b64coder.flush();
var attrs:Object = {mechanism:"PLAIN", xmlns:"urn:ietf:params:xml:ns:xmpp-sasl"};
req = new XMLNode(1, "auth");
req.appendChild(new XMLNode(3, authContent));
req.attributes = attrs;
stage = 0;
}
override public function handleResponse(stage:int, response:XMLNode):Object{
var success = (response.nodeName == "success");
var _temp1 = stage;
stage = (stage + 1);
return ({authComplete:true, authSuccess:success, authStage:_temp1});
}
}
}//package org.jivesoftware.xiff.auth
Section 145
//SASLAuth (org.jivesoftware.xiff.auth.SASLAuth)
package org.jivesoftware.xiff.auth {
import flash.xml.*;
public class SASLAuth {
protected var stage:int;
protected var req:XMLNode;
public function SASLAuth(){
super();
}
public function handleResponse(stage:int, response:XMLNode):Object{
throw (new Error("Don't call this method on SASLAuth; use a subclass"));
}
public function get request():XMLNode{
return (req);
}
}
}//package org.jivesoftware.xiff.auth
Section 146
//Room (org.jivesoftware.xiff.conference.Room)
package org.jivesoftware.xiff.conference {
import org.jivesoftware.xiff.core.*;
import org.jivesoftware.xiff.events.*;
import org.jivesoftware.xiff.data.*;
import org.jivesoftware.xiff.data.muc.*;
import org.jivesoftware.xiff.data.forms.*;
import mx.collections.*;
public class Room extends ArrayCollection {
private var active:Boolean;
private var myAffiliation:String;
private var pendingNickname:String;
private var myConnection:XMPPConnection;
private var myIsReserved:Boolean;
private var myNickname:String;
private var myRole:String;
private var mySubject:String;
private var myPassword:String;
private var _anonymous:Boolean;// = true
private var myJID:JID;
public static const ADMIN_AFFILIATION:String = MUC.ADMIN_AFFILIATION;
public static const OWNER_AFFILIATION:String = MUC.OWNER_AFFILIATION;
public static const PARTICIPANT_ROLE:String = MUC.PARTICIPANT_ROLE;
public static const VISITOR_ROLE:String = MUC.VISITOR_ROLE;
public static const MODERATOR_ROLE:String = MUC.MODERATOR_ROLE;
public static const NO_AFFILIATION:String = MUC.NO_AFFILIATION;
public static const NO_ROLE:String = MUC.NO_ROLE;
public static const MEMBER_AFFILIATION:String = MUC.MEMBER_AFFILIATION;
public static const OUTCAST_AFFILIATION:String = MUC.OUTCAST_AFFILIATION;
private static var roomStaticConstructed:Boolean = RoomStaticConstructor();
private static var staticConstructorDependencies:Array = [FormExtension, MUC];
public function Room(aConnection:XMPPConnection=null){
super();
active = false;
if (aConnection != null){
connection = aConnection;
};
}
public function destroy(reason:String, alternateJID:JID=null, callback:Function=null):void{
var iq:IQ = new IQ(roomJID, IQ.SET_TYPE);
var owner:MUCOwnerExtension = new MUCOwnerExtension();
iq.callback = callback;
owner.destroy(reason, alternateJID);
iq.addExtension(owner);
myConnection.send(iq);
}
public function invite(jid:JID, reason:String):void{
var msg:Message = new Message(roomJID);
var muc:MUCUserExtension = new MUCUserExtension();
muc.invite(jid, undefined, reason);
msg.addExtension(muc);
myConnection.send(msg);
}
public function revoke(jids:Array):void{
grant(Room.NO_AFFILIATION, jids);
}
public function get conferenceServer():String{
return (myJID.domain);
}
public function ban(jids:Array):void{
var banJID:JID;
var iq:IQ = new IQ(roomJID, IQ.SET_TYPE);
var adminExt:MUCAdminExtension = new MUCAdminExtension();
iq.callbackScope = this;
iq.callback = finish_admin;
for each (banJID in jids) {
adminExt.addItem(Room.OUTCAST_AFFILIATION, null, null, banJID, null, null);
};
iq.addExtension(adminExt);
connection.send(iq);
}
private function finish_requestAffiliates(iq:IQ):void{
var owner:MUCOwnerExtension;
var items:Array;
var e:RoomEvent;
finish_admin(iq);
if (iq.type == IQ.RESULT_TYPE){
owner = iq.getAllExtensionsByNS(MUCOwnerExtension.NS)[0];
items = owner.getAllItems();
e = new RoomEvent(RoomEvent.AFFILIATIONS);
e.data = items;
dispatchEvent(e);
};
}
public function set roomName(aName:String):void{
roomJID = new JID(((aName + "@") + conferenceServer));
}
public function get roomName():String{
return (myJID.node);
}
public function get password():String{
return (myPassword);
}
public function grant(affiliation:String, jids:Array):void{
var jid:JID;
var iq:IQ = new IQ(roomJID, IQ.SET_TYPE);
var owner:MUCOwnerExtension = new MUCOwnerExtension();
iq.callbackScope = this;
iq.callback = finish_admin;
for each (jid in jids) {
owner.addItem(affiliation, null, null, jid, null, null);
};
iq.addExtension(owner);
connection.send(iq);
}
public function set nickname(theNickname:String):void{
var tempPresence:Presence;
if (isActive){
pendingNickname = theNickname;
tempPresence = new Presence(new JID(((userJID + "/") + pendingNickname)));
myConnection.send(tempPresence);
} else {
myNickname = theNickname;
};
}
public function cancelConfiguration():void{
var iq:IQ = new IQ(roomJID, IQ.SET_TYPE);
var owner:MUCOwnerExtension = new MUCOwnerExtension();
var form:FormExtension = new FormExtension();
form.type = FormExtension.CANCEL_TYPE;
owner.addExtension(form);
iq.addExtension(owner);
myConnection.send(iq);
}
public function requestConfiguration():void{
var iq:IQ = new IQ(roomJID, IQ.GET_TYPE);
var owner:MUCOwnerExtension = new MUCOwnerExtension();
iq.callbackScope = this;
iq.callbackName = "finish_requestConfiguration";
iq.addExtension(owner);
myConnection.send(iq);
}
public function get roomJID():JID{
return (myJID);
}
public function sendPrivateMessage(recipientNickname:String, body:String=null, htmlBody:String=null):void{
var tempMessage:Message;
if (isActive){
tempMessage = new Message(new JID(((roomJID + "/") + recipientNickname)), null, body, htmlBody, Message.CHAT_TYPE);
myConnection.send(tempMessage);
};
}
public function kickOccupant(occupantNick:String, reason:String):void{
var tempIQ:IQ;
var ext:MUCAdminExtension;
if (isActive){
tempIQ = new IQ(roomJID, IQ.SET_TYPE, XMPPStanza.generateID("kick_occupant_"));
ext = new MUCAdminExtension(tempIQ.getNode());
ext.addItem(null, MUC.NO_ROLE, occupantNick, null, null, reason);
tempIQ.addExtension(ext);
myConnection.send(tempIQ);
};
}
public function setOccupantVoice(occupantNick:String, voice:Boolean):void{
var tempIQ:IQ;
var ext:MUCAdminExtension;
if (isActive){
tempIQ = new IQ(roomJID, IQ.SET_TYPE, XMPPStanza.generateID("voice_"));
ext = new MUCAdminExtension(tempIQ.getNode());
ext.addItem(null, (voice) ? MUC.PARTICIPANT_ROLE : MUC.VISITOR_ROLE);
tempIQ.addExtension(ext);
myConnection.send(tempIQ);
};
}
public function get fullRoomName():String{
return (roomJID.toString());
}
public function set password(aPassword:String):void{
myPassword = aPassword;
}
public function leave():void{
var leavePresence:Presence;
if (isActive){
leavePresence = new Presence(userJID, null, Presence.UNAVAILABLE_TYPE);
myConnection.send(leavePresence);
removeAll();
myConnection.removeEventListener(MessageEvent.MESSAGE, handleEvent);
myConnection.removeEventListener(DisconnectionEvent.DISCONNECT, handleEvent);
};
}
public function join(createReserved:Boolean=false, status:String=null, historyMode:String=null, historyNum:Number=0, joinPresenceExtensions:Array=null):Boolean{
var joinExt:*;
if (((!(myConnection.isActive())) || (isActive))){
return (false);
};
myIsReserved = ((createReserved == true)) ? true : false;
var joinPresence:Presence = new Presence(userJID);
if (joinPresenceExtensions != null){
for each (joinExt in joinPresenceExtensions) {
joinPresence.addExtension(joinExt);
};
};
var muc:MUCExtension = new MUCExtension();
if (historyMode != null){
muc.history = true;
if (historyMode == "seconds"){
muc.seconds = historyNum;
};
if (historyMode == "maxstanzas"){
muc.maxstanzas = historyNum;
};
if (historyMode == "maxchars"){
muc.maxchars = historyNum;
};
};
if (status != null){
joinPresence.status = status;
};
if (password != null){
muc.password = password;
};
joinPresence.addExtension(muc);
myConnection.send(joinPresence);
return (true);
}
public function get userJID():JID{
return (new JID(((roomJID.toBareJID() + "/") + nickname)));
}
private function finish_admin(iq:IQ):void{
var e:RoomEvent;
if (iq.type == IQ.ERROR_TYPE){
e = new RoomEvent(RoomEvent.ADMIN_ERROR);
e.errorCondition = iq.errorCondition;
e.errorMessage = iq.errorMessage;
e.errorType = iq.errorType;
e.errorCode = iq.errorCode;
dispatchEvent(e);
};
}
public function set connection(connection:XMPPConnection):void{
if (myConnection != null){
myConnection.removeEventListener(MessageEvent.MESSAGE, handleEvent);
myConnection.removeEventListener(PresenceEvent.PRESENCE, handleEvent);
myConnection.removeEventListener(DisconnectionEvent.DISCONNECT, handleEvent);
};
myConnection = connection;
myConnection.addEventListener(MessageEvent.MESSAGE, handleEvent, false, 0, true);
myConnection.addEventListener(PresenceEvent.PRESENCE, handleEvent, false, 0, true);
myConnection.addEventListener(DisconnectionEvent.DISCONNECT, handleEvent, false, 0, true);
}
private function unlockRoom(isReserved:Boolean):void{
var iq:IQ;
var owner:MUCOwnerExtension;
var form:FormExtension;
if (isReserved){
requestConfiguration();
} else {
iq = new IQ(roomJID, IQ.SET_TYPE);
owner = new MUCOwnerExtension();
form = new FormExtension();
form.type = FormExtension.SUBMIT_TYPE;
owner.addExtension(form);
iq.addExtension(owner);
myConnection.send(iq);
};
}
public function get subject():String{
return (mySubject);
}
public function getOccupantNamed(inName:String):RoomOccupant{
var occ:RoomOccupant;
for each (occ in this) {
if (occ.displayName == inName){
return (occ);
};
};
return (null);
}
public function allow(jids:Array):void{
grant(Room.NO_AFFILIATION, jids);
}
public function get isActive():Boolean{
return (active);
}
public function getMessage(body:String=null, htmlBody:String=null):Message{
var tempMessage:Message = new Message(roomJID, null, body, htmlBody, Message.GROUPCHAT_TYPE);
return (tempMessage);
}
private function handleEvent(eventObj:Object):void{
var _local4:Message;
var e:RoomEvent;
var form:Array;
var mucExtensions:Array;
var muc:MUCUserExtension;
var presence:Presence;
var user:MUCUserExtension;
var status:MUCStatus;
switch (eventObj.type){
case "message":
_local4 = eventObj.data;
if (isThisRoom(_local4.from)){
if (_local4.type == Message.GROUPCHAT_TYPE){
if (_local4.subject != null){
mySubject = _local4.subject;
e = new RoomEvent(RoomEvent.SUBJECT_CHANGE);
e.subject = _local4.subject;
dispatchEvent(e);
} else {
e = new RoomEvent(RoomEvent.GROUP_MESSAGE);
e.data = _local4;
dispatchEvent(e);
};
} else {
if (_local4.type == Message.NORMAL_TYPE){
form = _local4.getAllExtensionsByNS(FormExtension.NS)[0];
if (form){
e = new RoomEvent(RoomEvent.CONFIGURE_ROOM);
e.data = form;
dispatchEvent(e);
};
};
};
} else {
if (((isThisUser(_local4.to)) && ((_local4.type == Message.CHAT_TYPE)))){
e = new RoomEvent(RoomEvent.PRIVATE_MESSAGE);
e.data = _local4;
dispatchEvent(e);
} else {
mucExtensions = _local4.getAllExtensionsByNS(MUCUserExtension.NS);
if (((!((mucExtensions == null))) && ((mucExtensions.length > 0)))){
muc = mucExtensions[0];
if (((muc) && ((muc.type == MUCUserExtension.DECLINE_TYPE)))){
e = new RoomEvent(RoomEvent.DECLINED);
e.from = muc.reason;
e.reason = muc.reason;
e.data = _local4;
dispatchEvent(e);
};
};
};
};
break;
case "presence":
for each (presence in eventObj.data) {
if (presence.type == Presence.ERROR_TYPE){
switch (presence.errorCode){
case 401:
e = new RoomEvent(RoomEvent.PASSWORD_ERROR);
break;
case 403:
e = new RoomEvent(RoomEvent.BANNED_ERROR);
break;
case 404:
e = new RoomEvent(RoomEvent.LOCKED_ERROR);
break;
case 407:
e = new RoomEvent(RoomEvent.REGISTRATION_REQ_ERROR);
break;
case 409:
e = new RoomEvent(RoomEvent.NICK_CONFLICT);
e.nickname = nickname;
break;
case 503:
e = new RoomEvent(RoomEvent.MAX_USERS_ERROR);
break;
default:
e = new RoomEvent(("MUC Error of type: " + presence.errorCode));
break;
};
dispatchEvent(e);
} else {
if (isThisRoom(presence.from)){
if (presence.from.resource == pendingNickname){
myNickname = pendingNickname;
pendingNickname = null;
};
user = presence.getAllExtensionsByNS(MUCUserExtension.NS)[0];
for each (status in user.statuses) {
switch (status.code){
case 100:
case 172:
anonymous = false;
break;
case 174:
anonymous = true;
break;
case 201:
unlockRoom(myIsReserved);
break;
case 307:
e = new RoomEvent(RoomEvent.USER_KICKED);
e.nickname = presence.from.resource;
dispatchEvent(e);
break;
case 301:
e = new RoomEvent(RoomEvent.USER_BANNED);
e.nickname = presence.from.resource;
dispatchEvent(e);
break;
};
};
updateRoomRoster(presence);
if ((((((presence.type == Presence.UNAVAILABLE_TYPE)) && (isActive))) && (isThisUser(presence.from)))){
active = false;
e = new RoomEvent(RoomEvent.ROOM_LEAVE);
dispatchEvent(e);
myConnection.removeEventListener(PresenceEvent.PRESENCE, handleEvent);
};
};
};
};
break;
case "disconnection":
active = false;
removeAll();
e = new RoomEvent(RoomEvent.ROOM_LEAVE);
dispatchEvent(e);
break;
};
}
public function finish_requestConfiguration(iq:IQ):void{
var e:RoomEvent;
if (iq.type == IQ.ERROR_TYPE){
finish_admin(iq);
return;
};
var owner:MUCOwnerExtension = iq.getAllExtensionsByNS(MUCOwnerExtension.NS)[0];
var form:FormExtension = owner.getAllExtensionsByNS(FormExtension.NS)[0];
if (form.type == FormExtension.REQUEST_TYPE){
e = new RoomEvent(RoomEvent.CONFIGURE_ROOM);
e.data = form;
dispatchEvent(e);
};
}
public function isThisUser(sender:JID):Boolean{
return ((sender.toString().toLowerCase() == userJID.toString().toLowerCase()));
}
public function set roomJID(jid:JID):void{
myJID = jid;
}
public function get connection():XMPPConnection{
return (myConnection);
}
public function sendMessage(body:String=null, htmlBody:String=null):void{
var tempMessage:Message;
if (isActive){
tempMessage = new Message(roomJID, null, body, htmlBody, Message.GROUPCHAT_TYPE);
myConnection.send(tempMessage);
};
}
public function set anonymous(newState:Boolean):void{
_anonymous = newState;
}
public function changeSubject(newSubject:String):void{
var tempMessage:Message;
if (isActive){
tempMessage = new Message(roomJID, null, null, null, Message.GROUPCHAT_TYPE, newSubject);
myConnection.send(tempMessage);
};
}
public function set status(status:String):void{
var presence:Presence = new Presence(userJID);
presence.status = status;
var muc:MUCExtension = new MUCExtension();
presence.addExtension(muc);
myConnection.send(presence);
}
public function configure(fieldmap:Object):void{
var form:FormExtension;
var iq:IQ = new IQ(roomJID, IQ.SET_TYPE);
var owner:MUCOwnerExtension = new MUCOwnerExtension();
if ((fieldmap is FormExtension)){
form = FormExtension(fieldmap);
} else {
form = new FormExtension();
fieldmap["FORM_TYPE"] = [MUCOwnerExtension.NS];
form.setFields(fieldmap);
};
form.type = FormExtension.SUBMIT_TYPE;
owner.addExtension(form);
iq.addExtension(owner);
myConnection.send(iq);
}
public function isThisRoom(sender:JID):Boolean{
return (((roomJID) && ((sender.toBareJID().toLowerCase() == roomJID.toBareJID().toLowerCase()))));
}
public function requestAffiliations(affiliation:String):void{
var iq:IQ = new IQ(roomJID, IQ.GET_TYPE);
var owner:MUCOwnerExtension = new MUCOwnerExtension();
iq.callbackScope = this;
iq.callbackName = "finish_requestAffiliates";
owner.addItem(affiliation);
iq.addExtension(owner);
connection.send(iq);
}
override public function toString():String{
return ("[object Room]");
}
public function get anonymous():Boolean{
return (_anonymous);
}
private function updateRoomRoster(aPresence:Presence):void{
var e:RoomEvent;
var user:MUCUserExtension;
var status:MUCStatus;
var userNickname:String = aPresence.from.resource;
var userExts:Array = aPresence.getAllExtensionsByNS(MUCUserExtension.NS);
var item:MUCItem = userExts[0].getAllItems()[0];
if (isThisUser(aPresence.from)){
myAffiliation = item.affiliation;
myRole = item.role;
if (((!(isActive)) && (!((aPresence.type == Presence.UNAVAILABLE_TYPE))))){
active = true;
e = new RoomEvent(RoomEvent.ROOM_JOIN);
dispatchEvent(e);
};
};
var occupant:RoomOccupant = getOccupantNamed(userNickname);
if (occupant){
if (aPresence.type == Presence.UNAVAILABLE_TYPE){
removeItemAt(getItemIndex(occupant));
user = aPresence.getAllExtensionsByNS(MUCUserExtension.NS)[0];
for each (status in user.statuses) {
if ((((status.code == 307)) || ((status.code == 301)))){
return;
};
};
e = new RoomEvent(RoomEvent.USER_DEPARTURE);
e.nickname = userNickname;
e.data = aPresence;
dispatchEvent(e);
} else {
occupant.affiliation = item.affiliation;
occupant.role = item.role;
occupant.show = aPresence.show;
e = new RoomEvent(RoomEvent.USER_CHANGED);
e.nickname = userNickname;
e.data = aPresence;
dispatchEvent(e);
};
} else {
if (aPresence.type != Presence.UNAVAILABLE_TYPE){
addItem(new RoomOccupant(userNickname, aPresence.show, aPresence.status, item.affiliation, item.role, item.jid, this));
e = new RoomEvent(RoomEvent.USER_JOIN);
e.nickname = userNickname;
e.data = aPresence;
dispatchEvent(e);
};
};
}
public function get affiliation():String{
return (myAffiliation);
}
public function get nickname():String{
return (((myNickname == null)) ? myConnection.username : myNickname);
}
public function decline(jid:JID, reason:String):void{
var msg:Message = new Message(roomJID);
var muc:MUCUserExtension = new MUCUserExtension();
muc.decline(jid, undefined, reason);
msg.addExtension(muc);
myConnection.send(msg);
}
public function sendMessageWithExtension(msg:Message):void{
if (isActive){
myConnection.send(msg);
};
}
public function get role():String{
return (myRole);
}
public function set conferenceServer(aServer:String):void{
roomJID = new JID(((roomName + "@") + aServer));
}
private static function RoomStaticConstructor():Boolean{
MUC.enable();
FormExtension.enable();
return (true);
}
}
}//package org.jivesoftware.xiff.conference
Section 147
//RoomOccupant (org.jivesoftware.xiff.conference.RoomOccupant)
package org.jivesoftware.xiff.conference {
import flash.events.*;
import org.jivesoftware.xiff.core.*;
import mx.events.*;
import org.jivesoftware.xiff.data.im.*;
public class RoomOccupant extends EventDispatcher implements Contact {
private var _uid:String;
private var _status:String;
private var _affiliation:String;
private var _room:Room;
private var _jid:JID;
private var _nickname:String;
private var _role:String;
private var _show:String;
public function RoomOccupant(nickname:String, show:String, status:String, affiliation:String, role:String, jid:JID, room:Room){
super();
this.displayName = nickname;
this.show = show;
this.status = status;
this.affiliation = affiliation;
this.role = role;
this.jid = jid;
this.room = room;
}
public function get show():String{
return (_show);
}
public function get jid():JID{
return (_jid);
}
private function set _3506395room(newRoom:Room):void{
_room = newRoom;
}
private function set _1714148973displayName(name:String):void{
_nickname = name;
}
private function set _892481550status(newStatus:String):void{
_status = newStatus;
}
public function set jid(value:JID):void{
var oldValue:Object = this.jid;
if (oldValue !== value){
this._105221jid = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "jid", oldValue, value));
};
}
public function set online(value:Boolean):void{
var oldValue:Object = this.online;
if (oldValue !== value){
this._1012222381online = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "online", oldValue, value));
};
}
public function set uid(i:String):void{
_uid = i;
}
private function set _2019918576affiliation(newAffil:String):void{
_affiliation = newAffil;
}
public function set room(value:Room):void{
var oldValue:Object = this.room;
if (oldValue !== value){
this._3506395room = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "room", oldValue, value));
};
}
private function set _3506294role(newRole:String):void{
_role = newRole;
}
public function get rosterItem():RosterItemVO{
if (!jid){
return (null);
};
return (RosterItemVO.get(jid, true));
}
public function get uid():String{
return (_uid);
}
public function get online():Boolean{
return (true);
}
private function set _105221jid(newJID:JID):void{
_jid = newJID;
}
private function set _1012222381online(newOnline:Boolean):void{
}
public function get room():Room{
return (_room);
}
private function set _3529469show(newShow:String):void{
_show = newShow;
}
public function set affiliation(value:String):void{
var oldValue:Object = this.affiliation;
if (oldValue !== value){
this._2019918576affiliation = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "affiliation", oldValue, value));
};
}
public function set displayName(value:String):void{
var oldValue:Object = this.displayName;
if (oldValue !== value){
this._1714148973displayName = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "displayName", oldValue, value));
};
}
public function set status(value:String):void{
var oldValue:Object = this.status;
if (oldValue !== value){
this._892481550status = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "status", oldValue, value));
};
}
public function set role(value:String):void{
var oldValue:Object = this.role;
if (oldValue !== value){
this._3506294role = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "role", oldValue, value));
};
}
public function get displayName():String{
return (_nickname);
}
public function get affiliation():String{
return (_affiliation);
}
public function get status():String{
return (_status);
}
public function get role():String{
return (_role);
}
public function set show(value:String):void{
var oldValue:Object = this.show;
if (oldValue !== value){
this._3529469show = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "show", oldValue, value));
};
}
}
}//package org.jivesoftware.xiff.conference
Section 148
//JID (org.jivesoftware.xiff.core.JID)
package org.jivesoftware.xiff.core {
public class JID {
private var bareJID:String;
private var jid:String;
private var jidNodeValidator:RegExp;
public function JID(inJID:String, validate:Boolean=false):void{
jidNodeValidator = /^([\x29\x23-\x25\x28-\x2E\x30-\x39\x3B\x3D\x3F\x41-\x7E\xA0 - - -
-
- ----uFDD0-uFDEF uFFFE-uFFFF?-?-�⿰-⿻]{1,1023})/;
super();
if (validate){
if (((!(jidNodeValidator.test(inJID))) || ((inJID.indexOf(" ") > -1)))){
trace("Invalid JID: %s", inJID);
throw ("Invalid JID");
};
};
jid = (inJID) ? inJID : "";
}
public function get domain():String{
var i:int = jid.indexOf("@");
var j:int = jid.indexOf("/");
if (i < 0){
i = -1;
};
if (j < 0){
return (jid.slice((i + 1)));
};
return (jid.slice((i + 1), j));
}
public function get node():String{
var i:int = jid.indexOf("@");
if (i < 0){
return (null);
};
return (jid.slice(0, i));
}
public function toString():String{
return (jid);
}
public function get resource():String{
var i:int = this.jid.indexOf("/");
if (i < 0){
return (null);
};
return (jid.slice((i + 1)));
}
public function get bareJid():JID{
return (new JID(this.toBareJID()));
}
public function toBareJID():String{
var i:int;
if (!bareJID){
i = jid.indexOf("/");
if (i < 0){
bareJID = jid;
} else {
bareJID = jid.slice(0, i);
};
};
return (bareJID);
}
public function equals(testJID:JID, shouldTestBareJID:Boolean):Boolean{
if (shouldTestBareJID){
return ((testJID.toBareJID() == toBareJID()));
};
return ((testJID.jid == jid));
}
}
}//package org.jivesoftware.xiff.core
Section 149
//XMPPBOSHConnection (org.jivesoftware.xiff.core.XMPPBOSHConnection)
package org.jivesoftware.xiff.core {
import flash.events.*;
import org.jivesoftware.xiff.events.*;
import flash.utils.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
import flash.net.*;
import org.jivesoftware.xiff.auth.*;
import org.jivesoftware.xiff.data.bind.*;
import org.jivesoftware.xiff.data.session.*;
public class XMPPBOSHConnection extends XMPPConnection {
private const responseTimer:Timer;
private var authHandler:Function;
private var headers:Object;
private var rid:Number;
private var boshVersion:Number;// = 1.6
private var maxConcurrentRequests:uint;// = 2
private var saslEnabled:Boolean;// = true
private var auth:SASLAuth;
private var pendingHttpRequests:Array;
private var httpResponses:Array;
private var inactivity:int;
private var expectedRid:Number;
private var isDisconnecting:Boolean;// = false
private var requestCount:int;// = 0
private var requestQueue:Array;
private var sid:String;
private var responseQueue:Array;
private var callbacks:Object;
private var _port:Number;// = -1
private var boshPollingInterval:Number;// = 10000
private var https:Boolean;// = false
private var wait:int;
private static const saslMechanisms:Object = {PLAIN:Plain, ANONYMOUS:Anonymous};
public static var logger:Object = null;
public function XMPPBOSHConnection(){
headers = {post:[], get:["Cache-Control", "no-store", "Cache-Control", "no-cache", "Pragma", "no-cache"]};
requestQueue = [];
responseQueue = [];
pendingHttpRequests = [];
httpResponses = [];
responseTimer = new Timer(0, 1);
callbacks = {};
super();
}
override public function get port():Number{
if (_port == -1){
return ((https) ? 8483 : 8080);
};
return (_port);
}
override public function set port(portnum:Number):void{
_port = portnum;
}
private function bindConnection():void{
var bindIQ:IQ = new IQ(null, "set");
var bindExt:BindExtension = new BindExtension();
if (resource){
bindExt.resource = resource;
};
bindIQ.addExtension(bindExt);
bindIQ.callbackName = "handleBindResponse";
bindIQ.callbackScope = this;
send(bindIQ);
}
public function processConnectionResponse(responseBody:XMLNode):void{
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
boshPollingInterval = (attributes.polling * 1000);
if ((((boshPollingInterval <= 1000)) && ((boshPollingInterval > 0)))){
boshPollingInterval = (boshPollingInterval + 1000);
};
wait = attributes.wait;
inactivity = attributes.inactivity;
var serverRequests:int = attributes.requests;
if (serverRequests){
maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests);
};
active = true;
configureConnection(responseBody);
responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse);
}
private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth{
var authMechanism:SASLAuth;
var authClass:Class;
var mechanism:XMLNode;
for each (mechanism in mechanisms.childNodes) {
authClass = saslMechanisms[mechanism.firstChild.nodeValue];
if (authClass){
return (new authClass(this));
};
};
if (!authMechanism){
throw (new Error("No auth mechanisms found"));
};
return (authMechanism);
}
private function establishSession():void{
var sessionIQ:IQ = new IQ(null, "set");
sessionIQ.addExtension(new SessionExtension());
sessionIQ.callbackName = "handleSessionResponse";
sessionIQ.callbackScope = this;
send(sessionIQ);
}
override public function sendKeepAlive():void{
}
private function get nextRID():Number{
if (!rid){
rid = Math.floor((Math.random() * 1000000));
};
return (++rid);
}
public function set useSasl(sasl:Boolean):void{
saslEnabled = sasl;
}
public function handleSessionResponse(packet:IQ):void{
dispatchEvent(new LoginEvent());
}
override public function disconnect():void{
super.disconnect();
}
private function handleAuthentication(responseBody:XMLNode):void{
var status:Object = auth.handleResponse(0, responseBody);
if (status.authComplete){
if (status.authSuccess){
bindConnection();
} else {
dispatchEvent(new ErrorEvent(ErrorEvent.ERROR));
disconnect();
};
};
}
private function resetResponseProcessor():void{
if (responseQueue.length > 0){
responseTimer.reset();
responseTimer.start();
};
}
public function get useSasl():Boolean{
return (saslEnabled);
}
private function logIncomingData(xmlData:XMLDocument):void{
if (logger){
logger.log(xmlData.toString(), "INCOMING");
};
var event:IncomingDataEvent = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent(event);
}
private function processResponse(event:TimerEvent=null):void{
if (((!(active)) || ((responseQueue.length == 0)))){
return;
};
var currentNode:XMLNode = responseQueue.shift();
var nodeName:String = currentNode.nodeName.toLowerCase();
switch (nodeName){
case "stream:features":
break;
case "stream:error":
handleStreamError(currentNode);
break;
case "iq":
handleIQ(currentNode);
break;
case "message":
handleMessage(currentNode);
break;
case "presence":
handlePresence(currentNode);
break;
case "success":
handleAuthentication(currentNode);
break;
default:
dispatchError("undefined-condition", "Unknown Error", "modify", 500);
break;
};
resetResponseProcessor();
}
private function pollServer():void{
if (((!(isActive())) || (sendQueuedRequests()))){
return;
};
if (requestCount > 0){
return;
};
sendRequests(null, true);
}
private function configureConnection(responseBody:XMLNode):void{
var feature:XMLNode;
var features:XMLNode = responseBody.firstChild;
var authentication:Object = {};
for each (feature in features.childNodes) {
if (feature.nodeName == "mechanisms"){
authentication.auth = configureAuthMechanisms(feature);
} else {
if (feature.nodeName == "bind"){
authentication.bind = true;
} else {
if (feature.nodeName == "session"){
authentication.session = true;
};
};
};
};
dispatchEvent(new ConnectionSuccessEvent());
if (useSasl){
auth = authentication.auth;
authHandler = handleAuthentication;
sendXML(auth.request);
} else {
beginAuthentication();
};
}
private function httpError(req:XMLNode, isPollResponse:Boolean, evt:Event):void{
var event:DisconnectionEvent;
if (isActive()){
active = false;
event = new DisconnectionEvent();
dispatchEvent(event);
} else {
dispatchError("service-unavailable", "Service Unavailable", "cancel", 503);
};
}
private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:Event):void{
var event:DisconnectionEvent;
requestCount--;
var loader:URLLoader = URLLoader(evt.target);
var rawXML:String = loader.data;
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML(rawXML);
var bodyNode:XMLNode = xmlData.firstChild;
if (((active) && ((bodyNode.attributes["type"] == "terminate")))){
logIncomingData(xmlData);
event = new DisconnectionEvent();
dispatchEvent(event);
active = false;
return;
};
logIncomingData(xmlData);
var thisRequest:Object = getPendingRequest(loader);
httpResponses.push({rid:thisRequest.rid, xml:bodyNode});
httpResponses.sortOn("rid", Array.NUMERIC);
processHttpResponses();
processResponse();
sendQueuedRequests();
pollServer();
}
override public function connect(streamType:String=null):Boolean{
if (logger){
logger.log("CONNECT()", "INFO");
};
BindExtension.enable();
active = false;
loggedIn = false;
var attrs:Object = {xmlns:"http://jabber.org/protocol/httpbind", hold:(maxConcurrentRequests - 1), rid:nextRID, secure:https, wait:30, ver:boshVersion};
pendingHttpRequests = [];
httpResponses = [];
requestQueue = [];
responseQueue = [];
var result:XMLNode = new XMLNode(1, "body");
result.attributes = attrs;
sendRequests(result);
expectedRid = attrs.rid;
return (true);
}
private function sendRequests(data:XMLNode=null, isPoll:Boolean=false):Boolean{
var onResponse:Function;
var onError:Function;
var temp:Array;
var i:uint;
var data = data;
var isPoll = isPoll;
if (requestCount >= maxConcurrentRequests){
return (false);
};
if (isPoll){
trace(("Polling at: " + new Date().getSeconds()));
};
requestCount++;
if (!data){
if (isPoll){
data = createRequest();
} else {
temp = [];
i = 0;
while ((((i < 10)) && ((requestQueue.length > 0)))) {
temp.push(requestQueue.shift());
i = (i + 1);
};
data = createRequest(temp);
};
};
onResponse = function (event:Event):void{
removeEventListeners((event.target as URLLoader));
httpResponse(data, isPoll, event);
};
onError = function (event:Event):void{
removeEventListeners((event.target as URLLoader));
httpError(data, isPoll, event);
};
var removeEventListeners:Function = function (loader:URLLoader):void{
loader.removeEventListener(Event.COMPLETE, onResponse);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
};
var request:URLRequest = new URLRequest(httpServer);
request.method = URLRequestMethod.POST;
request.requestHeaders = headers["post"];
request.contentType = "text/xml";
request.data = data.toString();
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, onResponse);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
pendingHttpRequests.push({loader:loader, rid:data.attributes.rid});
if (logger){
logger.log(data, "OUTGOING");
};
loader.load(request);
return (true);
}
public function handleBindResponse(packet:IQ):void{
var bind:BindExtension = (packet.getExtension("bind") as BindExtension);
var jid:String = bind.getJID();
var parts:Array = jid.split("/");
myResource = parts[1];
parts = parts[0].split("@");
myUsername = parts[0];
server = parts[1];
establishSession();
}
public function set secure(flag:Boolean):void{
https = flag;
}
override protected function sendXML(body):void{
sendQueuedRequests(body);
}
public function get httpServer():String{
return (((((((https) ? "https" : "http" + "://") + serverAddress) + ":") + port) + "/http-bind/"));
}
private function createRequest(bodyContent:Array=null):XMLNode{
var content:XMLNode;
var attrs:Object = {xmlns:"http://jabber.org/protocol/httpbind", rid:nextRID, sid:sid};
var req:XMLNode = new XMLNode(1, "body");
if (bodyContent){
for each (content in bodyContent) {
req.appendChild(content);
};
};
req.attributes = attrs;
return (req);
}
private function processHttpResponses():void{
var response:Object;
var xml:XMLNode;
var childNode:XMLNode;
var responses:Array = [];
while (((httpResponses[0]) && ((httpResponses[0].rid == expectedRid)))) {
responses.push(httpResponses.shift());
expectedRid++;
};
for each (response in responses) {
xml = response.xml;
for each (childNode in xml.childNodes) {
if (childNode.nodeName == "stream:features"){
_expireTagSearch = false;
processConnectionResponse(xml);
} else {
responseQueue.push(childNode);
};
};
};
resetResponseProcessor();
}
private function getPendingRequest(loader:URLLoader):Object{
var request:Object;
var i:int;
while (i < pendingHttpRequests.length) {
if (pendingHttpRequests[i].loader == loader){
request = pendingHttpRequests[i];
pendingHttpRequests.slice(i, 1);
return (request);
};
i++;
};
return (null);
}
private function sendQueuedRequests(body=null):Boolean{
if (body){
requestQueue.push(body);
} else {
if (requestQueue.length == 0){
return (false);
};
};
return (sendRequests());
}
public static function disableSASLMechanism(name:String):void{
saslMechanisms[name] = null;
}
public static function registerSASLMechanism(name:String, authClass:Class):void{
saslMechanisms[name] = authClass;
}
}
}//package org.jivesoftware.xiff.core
Section 150
//XMPPConnection (org.jivesoftware.xiff.core.XMPPConnection)
package org.jivesoftware.xiff.core {
import flash.events.*;
import org.jivesoftware.xiff.events.*;
import flash.utils.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
import flash.net.*;
import org.jivesoftware.xiff.data.register.*;
import org.jivesoftware.xiff.data.forms.*;
import org.jivesoftware.xiff.data.auth.*;
import org.jivesoftware.xiff.exception.*;
public class XMPPConnection extends EventDispatcher {
protected var openingStreamTag:String;
protected var myServer:String;
protected var _socket:XMLSocket;
private var presenceQueueTimer:Timer;
protected var myUsername:String;
protected var _active:Boolean;
protected var sessionID:String;
protected var closingStreamTag:String;
protected var loggedIn:Boolean;
protected var _expireTagSearch:Boolean;
protected var myPort:Number;
protected var pendingIQs:Object;
protected var myResource:String;
private var presenceQueue:Array;
protected var _useAnonymousLogin:Boolean;
protected var myServerAddress:String;
protected var myPassword:String;
protected var ignoreWhitespace:Boolean;
protected static var _openConnections:Array = [];
public function XMPPConnection(){
presenceQueue = [];
super();
pendingIQs = new Object();
_useAnonymousLogin = false;
active = false;
loggedIn = false;
ignoreWhitespace = true;
resource = "xiff";
port = 5222;
AuthExtension.enable();
RegisterExtension.enable();
FormExtension.enable();
}
protected function beginAuthentication():void{
var authIQ:IQ = new IQ(null, IQ.GET_TYPE, XMPPStanza.generateID("log_user_"), "beginAuthentication_result", this, null);
var authExt:AuthExtension = new AuthExtension(authIQ.getNode());
authExt.username = username;
authIQ.addExtension(authExt);
send(authIQ);
}
public function get jid():JID{
return (new JID(((((myUsername + "@") + myServer) + "/") + myResource)));
}
protected function get active():Boolean{
return (_active);
}
protected function sendRegistrationFields_result(resultIQ:IQ):void{
var event:RegistrationSuccessEvent;
if (resultIQ.type == IQ.RESULT_TYPE){
event = new RegistrationSuccessEvent();
dispatchEvent(event);
} else {
dispatchError("unexpected-request", "Unexpected Request", "wait", 400);
};
}
protected function set active(flag:Boolean):void{
if (flag){
_openConnections.push(this);
} else {
_openConnections.splice(_openConnections.indexOf(this), 1);
};
_active = flag;
}
public function set server(theServer:String):void{
myServer = theServer;
}
public function get port():Number{
return (myPort);
}
public function isLoggedIn():Boolean{
return (loggedIn);
}
public function get resource():String{
return (myResource);
}
public function send(o:XMPPStanza):void{
var root:XMLNode;
var iq:IQ;
if (isActive()){
if ((o is IQ)){
iq = (o as IQ);
if (((((!((iq.callbackName == null))) && (!((iq.callbackScope == null))))) || (!((iq.callback == null))))){
addIQCallbackToPending(iq.id, iq.callbackName, iq.callbackScope, iq.callback);
};
};
root = o.getNode().parentNode;
if (root == null){
root = new XMLDocument();
};
if (o.serialize(root)){
sendXML(root.firstChild);
} else {
throw (new SerializationException());
};
};
}
protected function sendAnonymousLogin_result(resultIQ:IQ):void{
var jid:JID;
var event:LoginEvent;
if (resultIQ.type == IQ.RESULT_TYPE){
jid = resultIQ.to;
resource = jid.resource;
username = jid.node;
loggedIn = true;
event = new LoginEvent();
dispatchEvent(event);
};
}
protected function beginAuthentication_result(resultIQ:IQ):void{
var authIQ:IQ;
var resultAuth:*;
var responseAuth:AuthExtension;
var resultIQ = resultIQ;
var connectionType = "none";
if (resultIQ.type == IQ.RESULT_TYPE){
authIQ = new IQ(null, IQ.SET_TYPE, XMPPStanza.generateID("log_user2_"), "sendAuthentication_result", this, null);
resultAuth = resultIQ.getAllExtensionsByNS(AuthExtension.NS)[0];
responseAuth = new AuthExtension(authIQ.getNode());
responseAuth.password = password;
responseAuth.username = username;
responseAuth.resource = resource;
authIQ.addExtension(responseAuth);
send(authIQ);
//unresolved jump
var _slot1 = e;
trace("Error : null trapped. Resuming.");
} else {
dispatchError("unexpected-request", "Unexpected Request", "wait", 400);
};
}
public function disconnect():void{
var event:DisconnectionEvent;
if (isActive()){
sendXML(closingStreamTag);
if (_socket){
_socket.close();
};
//unresolved jump
var _slot1 = e;
active = false;
loggedIn = false;
event = new DisconnectionEvent();
dispatchEvent(event);
};
}
protected function handleStreamError(node:XMLNode):void{
var node = node;
dispatchError("service-unavailable", node.firstChild.nodeName.toLowerCase(), "cancel", 502);
_socket.close();
//unresolved jump
var _slot1 = error;
active = false;
loggedIn = false;
var event:DisconnectionEvent = new DisconnectionEvent();
dispatchEvent(event);
}
protected function sendAuthentication_result(resultIQ:IQ):void{
var event:LoginEvent;
if (resultIQ.type == IQ.RESULT_TYPE){
loggedIn = true;
event = new LoginEvent();
dispatchEvent(event);
} else {
dispatchError("unexpected-request", "Unexpected Request", "wait", 400);
};
}
public function sendKeepAlive():void{
if (isActive()){
sendXML(" ");
};
}
public function get password():String{
return (myPassword);
}
protected function sendAnonymousLogin():void{
var anonIQ:IQ = new IQ(null, IQ.SET_TYPE, XMPPStanza.generateID("log_anom_"), "sendAnonymousLogin_result", this, null);
var authExt:AuthExtension = new AuthExtension(anonIQ.getNode());
anonIQ.addExtension(authExt);
send(anonIQ);
}
protected function dispatchError(condition:String, message:String, type:String, code:Number):void{
var event:XIFFErrorEvent = new XIFFErrorEvent();
event.errorCondition = condition;
event.errorMessage = message;
event.errorType = type;
event.errorCode = code;
dispatchEvent(event);
}
protected function securityError(event:SecurityErrorEvent):void{
dispatchError("service-unavailable-security", "Service Unavailable", "cancel", 503);
}
protected function flushPresenceQueue(evt:TimerEvent):void{
var event:PresenceEvent = new PresenceEvent();
event.data = presenceQueue;
dispatchEvent(event);
presenceQueue = [];
}
public function set password(thePassword:String):void{
myPassword = thePassword;
}
public function get serverAddress():String{
if (myServerAddress != null){
return (myServerAddress);
};
return (myServer);
}
public function set username(theUsername:String):void{
myUsername = theUsername;
}
private function _createXmlSocket():XMLSocket{
if (_socket != null){
_socket.removeEventListener(Event.CONNECT, socketConnected);
_socket.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
_socket.removeEventListener(Event.CLOSE, socketClosed);
_socket.removeEventListener(DataEvent.DATA, socketReceivedData);
_socket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
};
var socket:XMLSocket = new XMLSocket(serverAddress, port);
socket.addEventListener(Event.CONNECT, socketConnected);
socket.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
socket.addEventListener(Event.CLOSE, socketClosed);
socket.addEventListener(DataEvent.DATA, socketReceivedData);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
return (socket);
}
protected function socketReceivedData(ev:DataEvent):void{
var pattern:RegExp;
var resultObj:Object;
if (!_expireTagSearch){
pattern = new RegExp("<flash:stream");
resultObj = pattern.exec(ev.data);
if (resultObj != null){
ev.data = ev.data.concat("</flash:stream>");
_expireTagSearch = true;
};
};
if (ev.data == "</flash:stream>"){
socketClosed(null);
return;
};
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML(ev.data);
var event:IncomingDataEvent = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent(event);
var firstNode:XMLNode = xmlData.firstChild;
var nodeName:String = firstNode.nodeName.toLowerCase();
switch (nodeName){
case "stream:stream":
case "flash:stream":
_expireTagSearch = false;
handleStream(firstNode);
break;
case "stream:error":
handleStreamError(firstNode);
break;
case "iq":
handleIQ(firstNode);
break;
case "message":
handleMessage(firstNode);
break;
case "presence":
handlePresence(firstNode);
break;
case "stream:features":
break;
default:
dispatchError("undefined-condition", "Unknown Error", "modify", 500);
break;
};
}
protected function socketClosed(e:Event):void{
var event:DisconnectionEvent;
if (isActive()){
active = false;
event = new DisconnectionEvent();
dispatchEvent(event);
};
}
protected function handlePresence(node:XMLNode):Presence{
if (!presenceQueueTimer){
presenceQueueTimer = new Timer(1, 1);
presenceQueueTimer.addEventListener(TimerEvent.TIMER_COMPLETE, flushPresenceQueue);
};
var pres:Presence = new Presence();
if (!pres.deserialize(node)){
throw (new SerializationException());
};
presenceQueue.push(pres);
presenceQueueTimer.reset();
presenceQueueTimer.start();
return (pres);
}
protected function handleMessage(node:XMLNode):Message{
var event:MessageEvent;
var msg:Message = new Message();
if (!msg.deserialize(node)){
throw (new SerializationException());
};
if (msg.type == Message.ERROR_TYPE){
dispatchError(msg.errorCondition, msg.errorMessage, msg.errorType, msg.errorCode);
} else {
event = new MessageEvent();
event.data = msg;
dispatchEvent(event);
};
return (msg);
}
protected function handleStream(node:XMLNode):void{
sessionID = node.attributes.id;
server = node.attributes.from;
if (_useAnonymousLogin){
sendAnonymousLogin();
} else {
if (((!((username == null))) && ((username.length > 0)))){
beginAuthentication();
} else {
getRegistrationFields();
};
};
}
public function set resource(theResource:String):void{
if (theResource.length > 0){
myResource = theResource;
};
}
public function isActive():Boolean{
return (active);
}
protected function onIOError(event:IOErrorEvent):void{
dispatchError("service-unavailable-io", "Service Unavailable", "cancel", 503);
}
protected function addIQCallbackToPending(id:String, callbackName:String, callbackScope:Object, callbackFunc:Function):void{
pendingIQs[id] = {methodName:callbackName, methodScope:callbackScope, func:callbackFunc};
}
protected function socketConnected(ev:Event):void{
active = true;
sendXML(openingStreamTag);
var event:ConnectionSuccessEvent = new ConnectionSuccessEvent();
dispatchEvent(event);
}
public function getRegistrationFields():void{
var regIQ:IQ = new IQ(new JID(server), IQ.GET_TYPE, XMPPStanza.generateID("reg_info_"), "getRegistrationFields_result", this, null);
regIQ.addExtension(new RegisterExtension(regIQ.getNode()));
send(regIQ);
}
public function get server():String{
return (myServer);
}
protected function handleIQ(node:XMLNode):IQ{
var callbackInfo:*;
var exts:Array;
var ns:String;
var ext:IExtension;
var event:IQEvent;
var iq:IQ = new IQ();
if (!iq.deserialize(node)){
throw (new SerializationException());
};
if ((((iq.type == IQ.ERROR_TYPE)) && (!(pendingIQs[iq.id])))){
dispatchError(iq.errorCondition, iq.errorMessage, iq.errorType, iq.errorCode);
} else {
if (pendingIQs[iq.id] !== undefined){
callbackInfo = pendingIQs[iq.id];
if (((callbackInfo.methodScope) && (callbackInfo.methodName))){
callbackInfo.methodScope[callbackInfo.methodName].apply(callbackInfo.methodScope, [iq]);
};
if (callbackInfo.func != null){
callbackInfo.func(iq);
};
pendingIQs[iq.id] = null;
delete pendingIQs[iq.id];
} else {
exts = iq.getAllExtensions();
for (ns in exts) {
ext = (exts[ns] as IExtension);
if (ext != null){
event = new IQEvent(ext.getNS());
event.data = ext;
event.iq = iq;
dispatchEvent(event);
};
};
};
};
return (iq);
}
public function get useAnonymousLogin():Boolean{
return (_useAnonymousLogin);
}
public function set useAnonymousLogin(value:Boolean):void{
if (!isActive()){
_useAnonymousLogin = value;
};
}
public function set serverAddress(theServerAddress:String):void{
myServerAddress = theServerAddress;
}
public function connect(streamType:String="terminatedStandard"):Boolean{
_socket = _createXmlSocket();
active = false;
loggedIn = false;
switch (streamType){
case "flash":
openingStreamTag = new String((("<?xml version=\"1.0\"?><flash:stream to=\"" + server) + "\" xmlns=\"jabber:client\" xmlns:flash=\"http://www.jabber.com/streams/flash\" version=\"1.0\">"));
closingStreamTag = new String("</flash:stream>");
break;
case "terminatedFlash":
openingStreamTag = new String((("<?xml version=\"1.0\"?><flash:stream to=\"" + server) + "\" xmlns=\"jabber:client\" xmlns:flash=\"http://www.jabber.com/streams/flash\" version=\"1.0\" />"));
closingStreamTag = new String("</flash:stream>");
break;
case "standard":
openingStreamTag = new String((("<?xml version=\"1.0\"?><stream:stream to=\"" + server) + "\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">"));
closingStreamTag = new String("</stream:stream>");
break;
case "terminatedStandard":
default:
openingStreamTag = new String((("<?xml version=\"1.0\"?><stream:stream to=\"" + server) + "\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\" />"));
closingStreamTag = new String("</stream:stream>");
break;
};
_socket.connect(serverAddress, port);
return (true);
}
public function changePassword(newPassword:String):void{
var passwdIQ:IQ = new IQ(new JID(server), IQ.SET_TYPE, XMPPStanza.generateID("pswd_change_"), "changePassword_result", this, null);
var ext:RegisterExtension = new RegisterExtension(passwdIQ.getNode());
ext.username = jid.toBareJID();
ext.password = newPassword;
passwdIQ.addExtension(ext);
send(passwdIQ);
}
public function get username():String{
return (myUsername);
}
protected function changePassword_result(resultIQ:IQ):void{
var event:ChangePasswordSuccessEvent;
if (resultIQ.type == IQ.RESULT_TYPE){
event = new ChangePasswordSuccessEvent();
dispatchEvent(event);
} else {
dispatchError("unexpected-request", "Unexpected Request", "wait", 400);
};
}
protected function getRegistrationFields_result(resultIQ:IQ):void{
var ext:RegisterExtension;
var fields:Array;
var event:RegistrationFieldsEvent;
var resultIQ = resultIQ;
ext = resultIQ.getAllExtensionsByNS(RegisterExtension.NS)[0];
fields = ext.getRequiredFieldNames();
event = new RegistrationFieldsEvent();
event.fields = fields;
event.data = ext;
//unresolved jump
var _slot1 = e;
trace(_slot1.getStackTrace());
}
public function set port(portNum:Number):void{
myPort = portNum;
}
protected function sendXML(someData):void{
_socket.send(someData);
var event:OutgoingDataEvent = new OutgoingDataEvent();
event.data = someData;
dispatchEvent(event);
}
public function get ignoreWhite():Boolean{
return (ignoreWhitespace);
}
public function sendRegistrationFields(fieldMap:Object, key:String):void{
var i:String;
var regIQ:IQ = new IQ(new JID(server), IQ.SET_TYPE, XMPPStanza.generateID("reg_attempt_"), "sendRegistrationFields_result", this, null);
var ext:RegisterExtension = new RegisterExtension(regIQ.getNode());
for (i in fieldMap) {
ext[i] = fieldMap[i];
};
if (key != null){
ext.key = key;
};
regIQ.addExtension(ext);
send(regIQ);
}
public function set ignoreWhite(val:Boolean):void{
ignoreWhitespace = val;
}
public static function get openConnections():Array{
return (_openConnections);
}
}
}//package org.jivesoftware.xiff.core
Section 151
//XMPPSocketConnection (org.jivesoftware.xiff.core.XMPPSocketConnection)
package org.jivesoftware.xiff.core {
import flash.events.*;
import org.jivesoftware.xiff.events.*;
import com.kongregate.as3.common.util.*;
import flash.xml.*;
import org.jivesoftware.xiff.util.*;
public class XMPPSocketConnection extends XMPPConnection {
private var _streamNode:XMLNode;// = null
private var _compress:Boolean;// = false
private var _incompleteRawXML:String;// = ""
protected var binarySocket:SocketConn;
private var _compressedSessionInitialized:Boolean;// = false
public function XMPPSocketConnection(compress:Boolean=false){
super();
_compress = compress;
configureSocket();
}
protected function bSocketReceivedData(ev:SocketDataEvent):void{
var pattern:RegExp;
var resultObj:Object;
var pattern2:RegExp;
var resultObj2:Object;
var isComplete:Boolean;
var event:IncomingDataEvent;
var i:int;
var currentNode:XMLNode;
var nodeName:String;
var ev = ev;
var rawXML:String = ((_incompleteRawXML + ev.data) as String);
if (rawXML == null){
Log.error("Bad socket data event detected, disconnecting");
disconnect();
return;
};
if (rawXML.length == 0){
return;
};
rawXML = rawXML.replace("</flash:stream>", "");
rawXML = rawXML.replace("</stream:stream>", "");
if (!_expireTagSearch){
pattern = new RegExp("<flash:stream");
resultObj = pattern.exec(rawXML);
if (resultObj != null){
rawXML = rawXML.concat("</flash:stream>");
_expireTagSearch = true;
};
};
if (!_expireTagSearch){
pattern2 = new RegExp("<stream:stream");
resultObj2 = pattern2.exec(rawXML);
if (resultObj2 != null){
rawXML = rawXML.concat("</stream:stream>");
_expireTagSearch = true;
};
};
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
isComplete = true;
xmlData.parseXML(rawXML);
_incompleteRawXML = "";
//unresolved jump
var _slot1 = err;
isComplete = false;
_incompleteRawXML = (_incompleteRawXML + (ev.data as String));
if (isComplete){
event = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent(event);
i = 0;
while (i < xmlData.childNodes.length) {
currentNode = xmlData.childNodes[i];
nodeName = currentNode.nodeName.toLowerCase();
switch (nodeName){
case "stream:stream":
_expireTagSearch = false;
handleStream(currentNode);
break;
case "flash:stream":
_expireTagSearch = false;
handleStream(currentNode);
break;
case "stream:error":
handleStreamError(currentNode);
break;
case "compressed":
handleCompressed(currentNode);
break;
case "failure":
handleFailure(currentNode);
break;
case "iq":
handleIQ(currentNode);
break;
case "message":
handleMessage(currentNode);
break;
case "presence":
handlePresence(currentNode);
break;
case "stream:features":
break;
default:
dispatchError("undefined-condition", "Unknown Error", "modify", 500);
break;
};
i = (i + 1);
};
};
}
override public function disconnect():void{
var event:DisconnectionEvent;
if (isActive()){
sendXML(closingStreamTag);
if (binarySocket){
binarySocket.close();
};
//unresolved jump
var _slot1 = e;
active = false;
loggedIn = false;
event = new DisconnectionEvent();
dispatchEvent(event);
};
}
override public function connect(streamType:String="terminatedStandard"):Boolean{
active = false;
loggedIn = false;
_compressedSessionInitialized = false;
_streamNode = null;
switch (streamType){
case "flash":
binarySocket.flash = true;
openingStreamTag = (("<?xml version=\"1.0\"?><flash:stream to=\"" + server) + "\" xmlns=\"jabber:client\" xmlns:flash=\"http://www.jabber.com/streams/flash\" version=\"1.0\">");
closingStreamTag = "</flash:stream>";
break;
case "terminatedFlash":
binarySocket.flash = true;
openingStreamTag = (("<?xml version=\"1.0\"?><flash:stream to=\"" + server) + "\" xmlns=\"jabber:client\" xmlns:flash=\"http://www.jabber.com/streams/flash\" version=\"1.0\" />");
closingStreamTag = "</flash:stream>";
break;
case "standard":
binarySocket.flash = false;
openingStreamTag = (("<?xml version=\"1.0\"?><stream:stream to=\"" + server) + "\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">");
closingStreamTag = "</stream:stream>";
break;
case "terminatedStandard":
default:
binarySocket.flash = false;
openingStreamTag = (("<?xml version=\"1.0\"?><stream:stream to=\"" + server) + "\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\" />");
closingStreamTag = "</stream:stream>";
break;
};
binarySocket.connect(serverAddress, port);
return (true);
}
protected function handleCompressed(node:XMLNode):void{
_compressedSessionInitialized = true;
binarySocket.compress = true;
Log.info("Compressed stream initialized");
sendXML(openingStreamTag);
}
protected function handleFailure(node:XMLNode):void{
if (node.attributes.xmlns == "http://jabber.org/protocol/compress"){
Log.warn("Compression disabled on server, reverting to normal stream");
_compress = false;
super.handleStream(_streamNode);
_streamNode = null;
};
}
override protected function sendXML(someData):void{
binarySocket.sendString(someData);
var event:OutgoingDataEvent = new OutgoingDataEvent();
event.data = someData;
dispatchEvent(event);
}
override protected function handleStream(node:XMLNode):void{
if (((_compress) && (!(this._compressedSessionInitialized)))){
_streamNode = node;
sendXML("<compress xmlns='http://jabber.org/protocol/compress'><method>zlib</method></compress>");
Log.info("Initializing compression");
} else {
super.handleStream(node);
};
}
private function configureSocket():void{
binarySocket = new SocketConn();
binarySocket.addEventListener(Event.CLOSE, socketClosed);
binarySocket.addEventListener(Event.CONNECT, socketConnected);
binarySocket.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
binarySocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
binarySocket.addEventListener(SocketDataEvent.SOCKET_DATA_RECEIVED, bSocketReceivedData);
}
}
}//package org.jivesoftware.xiff.core
Section 152
//AuthExtension (org.jivesoftware.xiff.data.auth.AuthExtension)
package org.jivesoftware.xiff.data.auth {
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class AuthExtension extends Extension implements IExtension, ISerializable {
private var myUsernameNode:XMLNode;
private var myPasswordNode:XMLNode;
private var myDigestNode:XMLNode;
private var myResourceNode:XMLNode;
public static var NS:String = "jabber:iq:auth";
public static var ELEMENT:String = "query";
public function AuthExtension(parent:XMLNode=null){
super(parent);
}
public function deserialize(node:XMLNode):Boolean{
var i:String;
setNode(node);
var children:Array = node.childNodes;
for (i in children) {
switch (children[i].nodeName){
case "username":
myUsernameNode = children[i];
break;
case "password":
myPasswordNode = children[i];
break;
case "digest":
myDigestNode = children[i];
break;
case "resource":
myResourceNode = children[i];
break;
};
};
return (true);
}
public function get digest():String{
return (myDigestNode.firstChild.nodeValue);
}
public function isDigest():Boolean{
return (exists(myDigestNode));
}
public function set digest(val:String):void{
myPasswordNode.removeNode();
myPasswordNode = null;
myDigestNode = replaceTextNode(getNode(), myDigestNode, "digest", val);
}
public function get resource():String{
return (myResourceNode.firstChild.nodeValue);
}
public function get username():String{
return (myUsernameNode.firstChild.nodeValue);
}
public function set resource(val:String):void{
myResourceNode = replaceTextNode(getNode(), myResourceNode, "resource", val);
}
public function serialize(parent:XMLNode):Boolean{
if (!exists(getNode().parentNode)){
parent.appendChild(getNode().cloneNode(true));
};
return (true);
}
public function get password():String{
return (myPasswordNode.firstChild.nodeValue);
}
public function isPassword():Boolean{
return (exists(myPasswordNode));
}
public function getNS():String{
return (AuthExtension.NS);
}
public function set username(val:String):void{
myUsernameNode = replaceTextNode(getNode(), myUsernameNode, "username", val);
}
public function set password(val:String):void{
myDigestNode = ((myDigestNode)==null) ? XMLStanza.XMLFactory.createElement("") : myDigestNode;
myDigestNode.removeNode();
myDigestNode = null;
myPasswordNode = replaceTextNode(getNode(), myPasswordNode, "password", val);
}
public function getElementName():String{
return (AuthExtension.ELEMENT);
}
public static function enable():void{
ExtensionClassRegistry.register(AuthExtension);
}
public static function computeDigest(sessionID:String, password:String):String{
return (SHA1.calcSHA1((sessionID + password)).toLowerCase());
}
}
}//package org.jivesoftware.xiff.data.auth
Section 153
//SHA1 (org.jivesoftware.xiff.data.auth.SHA1)
package org.jivesoftware.xiff.data.auth {
public class SHA1 {
private static var hex_chr:String = "0123456789abcdef";
public function SHA1(){
super();
}
private static function kt(t:Number):Number{
return (((t)<20) ? 1518500249 : ((t)<40) ? 1859775393 : ((t)<60) ? -1894007588 : -899497514);
}
private static function str2blks(str:String):Array{
var nblk:Number = (((str.length + 8) >> 6) + 1);
var blks:Array = new Array((nblk * 16));
var i:Number = 0;
while (i < (nblk * 16)) {
blks[i] = 0;
i++;
};
var j:Number = 0;
while (j < str.length) {
blks[(j >> 2)] = (blks[(j >> 2)] | (str.charCodeAt(j) << (24 - ((j % 4) * 8))));
j++;
};
blks[(j >> 2)] = (blks[(j >> 2)] | (128 << (24 - ((j % 4) * 8))));
blks[((nblk * 16) - 1)] = (str.length * 8);
return (blks);
}
private static function rol(num:Number, cnt:Number):Number{
return (((num << cnt) | (num >>> (32 - cnt))));
}
public static function calcSHA1(str:String):String{
var olda:Number;
var oldb:Number;
var oldc:Number;
var oldd:Number;
var olde:Number;
var j:Number;
var t:Number;
var x:Array = SHA1.str2blks(str);
var w:Array = new Array(80);
var a:Number = 1732584193;
var b:Number = -271733879;
var c:Number = -1732584194;
var d:Number = 271733878;
var e:Number = -1009589776;
var i:Number = 0;
while (i < x.length) {
olda = a;
oldb = b;
oldc = c;
oldd = d;
olde = e;
j = 0;
while (j < 80) {
if (j < 16){
w[j] = x[(i + j)];
} else {
w[j] = SHA1.rol((((w[(j - 3)] ^ w[(j - 8)]) ^ w[(j - 14)]) ^ w[(j - 16)]), 1);
};
t = SHA1.safe_add(SHA1.safe_add(SHA1.rol(a, 5), SHA1.ft(j, b, c, d)), SHA1.safe_add(SHA1.safe_add(e, w[j]), SHA1.kt(j)));
e = d;
d = c;
c = SHA1.rol(b, 30);
b = a;
a = t;
j++;
};
a = SHA1.safe_add(a, olda);
b = SHA1.safe_add(b, oldb);
c = SHA1.safe_add(c, oldc);
d = SHA1.safe_add(d, oldd);
e = SHA1.safe_add(e, olde);
i = (i + 16);
};
return (((((SHA1.hex(a) + SHA1.hex(b)) + SHA1.hex(c)) + SHA1.hex(d)) + SHA1.hex(e)));
}
private static function hex(num:Number):String{
var str:String = "";
var j:Number = 7;
while (j >= 0) {
str = (str + hex_chr.charAt(((num >> (j * 4)) & 15)));
j--;
};
return (str);
}
private static function ft(t:Number, b:Number, c:Number, d:Number):Number{
if (t < 20){
return (((b & c) | (~(b) & d)));
};
if (t < 40){
return (((b ^ c) ^ d));
};
if (t < 60){
return ((((b & c) | (b & d)) | (c & d)));
};
return (((b ^ c) ^ d));
}
private static function safe_add(x:Number, y:Number):Number{
var lsw:Number = ((x & 0xFFFF) + (y & 0xFFFF));
var msw:Number = (((x >> 16) + (y >> 16)) + (lsw >> 16));
return (((msw << 16) | (lsw & 0xFFFF)));
}
}
}//package org.jivesoftware.xiff.data.auth
Section 154
//BindExtension (org.jivesoftware.xiff.data.bind.BindExtension)
package org.jivesoftware.xiff.data.bind {
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class BindExtension extends Extension implements IExtension, ISerializable {
private var jid:String;
private var _resource:String;
public static var NS:String = "urn:ietf:params:xml:ns:xmpp-bind";
public static var ELEMENT_NAME:String = "bind";
public function BindExtension(parent:XMLNode=null){
super(parent);
}
public function serialize(parent:XMLNode):Boolean{
var child:XMLNode;
var resourceNode:XMLNode;
if (!exists(getNode().parentNode)){
child = getNode().cloneNode(true);
resourceNode = new XMLNode(1, "resource");
resourceNode.appendChild(XMLStanza.XMLFactory.createTextNode((resource) ? resource : "xiff"));
child.appendChild(resourceNode);
parent.appendChild(child);
};
return (true);
}
public function get resource():String{
return (_resource);
}
public function getJID():String{
return (jid);
}
public function getElementName():String{
return (BindExtension.ELEMENT_NAME);
}
public function getNS():String{
return (BindExtension.NS);
}
public function set resource(newResource:String):void{
_resource = newResource;
}
public function deserialize(node:XMLNode):Boolean{
var i:String;
setNode(node);
var children:Array = node.childNodes;
for (i in children) {
switch (children[i].nodeName){
case "jid":
jid = children[i].firstChild.nodeValue;
break;
default:
throw (("Unknown element: " + children[i].nodeName));
};
};
return (true);
}
public static function enable():void{
ExtensionClassRegistry.register(BindExtension);
}
}
}//package org.jivesoftware.xiff.data.bind
Section 155
//FormExtension (org.jivesoftware.xiff.data.forms.FormExtension)
package org.jivesoftware.xiff.data.forms {
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class FormExtension extends Extension implements IExtension, ISerializable {
private var myFields:Array;
private var myReportedFields:Array;
private var myInstructionsNode:XMLNode;
private var myTitleNode:XMLNode;
private var myItems:Array;
public static var SUBMIT_TYPE:String = "submit";
public static var FIELD_TYPE_JID_MULTI:String = "jid-multi";
public static var FIELD_TYPE_TEXT_MULTI:String = "text-multi";
public static var FIELD_TYPE_BOOLEAN:String = "boolean";
public static var FIELD_TYPE_LIST_SINGLE:String = "list-single";
public static var REQUEST_TYPE:String = "form";
public static var NS:String = "jabber:x:data";
public static var FIELD_TYPE_TEXT_PRIVATE:String = "text-private";
public static var FIELD_TYPE_TEXT_SINGLE:String = "text-single";
public static var FIELD_TYPE_FIXED:String = "fixed";
public static var RESULT_TYPE:String = "result";
public static var CANCEL_TYPE:String = "cancel";
public static var FIELD_TYPE_JID_SINGLE:String = "jid-single";
public static var FIELD_TYPE_HIDDEN:String = "hidden";
public static var ELEMENT:String = "x";
public static var FIELD_TYPE_LIST_MULTI:String = "list-multi";
public function FormExtension(parent:XMLNode=null){
super(parent);
myItems = new Array();
myFields = new Array();
myReportedFields = new Array();
}
public function removeAllItems():void{
var i:String;
var j:String;
for (i in myItems) {
for (j in myItems) {
myItems[i][j].getNode().removeNode();
myItems[i][j].setNode(null);
};
};
myItems = new Array();
}
public function getAllFields():Array{
return (myFields);
}
public function deserialize(node:XMLNode):Boolean{
var i:String;
var c:XMLNode;
var field:FormField;
var _local8:Array;
var reportedFieldXML:XMLNode;
var itemFieldXML:XMLNode;
setNode(node);
removeAllItems();
removeAllFields();
var children:Array = node.childNodes;
for (i in children) {
c = children[i];
switch (children[i].nodeName){
case "instructions":
myInstructionsNode = c;
break;
case "title":
myTitleNode = c;
break;
case "reported":
for each (reportedFieldXML in c.childNodes) {
field = new FormField();
field.deserialize(reportedFieldXML);
myReportedFields.push(field);
};
break;
case "item":
_local8 = new Array();
for each (itemFieldXML in c.childNodes) {
field = new FormField();
field.deserialize(itemFieldXML);
_local8.push(field);
};
myItems.push(_local8);
break;
case "field":
field = new FormField();
field.deserialize(c);
myFields.push(field);
break;
};
};
return (true);
}
public function set type(val:String):void{
getNode().attributes.type = val;
}
public function set instructions(val:String):void{
myInstructionsNode = replaceTextNode(getNode(), myInstructionsNode, "instructions", val);
}
public function getFormType():String{
var i:int;
while (i < myFields.length) {
if (myFields[i].name == "FORM_TYPE"){
return (myFields[i].value);
};
i++;
};
return ("");
}
public function getAllItems():Array{
return (myItems);
}
public function removeAllFields():void{
var i:String;
var j:String;
for (i in myFields) {
for (j in myFields[i]) {
myFields[i][j].getNode().removeNode();
myFields[i][j].setNode(null);
};
};
myFields = new Array();
}
public function get title():String{
return (myTitleNode.firstChild.nodeValue);
}
public function serialize(parent:XMLNode):Boolean{
var i:String;
var node:XMLNode = getNode();
for (i in myFields) {
if (!myFields[i].serialize(node)){
return (false);
};
};
if (parent != node.parentNode){
parent.appendChild(node.cloneNode(true));
};
return (true);
}
public function getNS():String{
return (FormExtension.NS);
}
public function get instructions():String{
return (myInstructionsNode.firstChild.nodeValue);
}
public function getFormField(value:String):FormField{
var field:FormField;
var len:int = myFields.length;
for each (field in myFields) {
if (field.name == value){
break;
};
};
return (field);
}
public function getReportedFields():Array{
return (myReportedFields);
}
public function set title(val:String):void{
myTitleNode = replaceTextNode(getNode(), myTitleNode, "Title", val);
}
public function getElementName():String{
return (FormExtension.ELEMENT);
}
public function get type():String{
return (getNode().attributes.type);
}
public function setFields(fieldmap:Object):void{
var f:String;
var field:FormField;
removeAllFields();
for (f in fieldmap) {
field = new FormField();
field.name = f;
field.setAllValues(fieldmap[f]);
myFields.push(field);
};
}
public static function enable():Boolean{
ExtensionClassRegistry.register(FormExtension);
return (true);
}
}
}//package org.jivesoftware.xiff.data.forms
Section 156
//FormField (org.jivesoftware.xiff.data.forms.FormField)
package org.jivesoftware.xiff.data.forms {
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class FormField extends XMLStanza implements ISerializable {
private var myDescNode:XMLNode;
private var myValueNodes:Array;
private var myRequiredNode:XMLNode;
private var myOptionNodes:Array;
public static var ELEMENT:String = "field";
public function FormField(){
super();
}
public function serialize(parent:XMLNode):Boolean{
getNode().nodeName = FormField.ELEMENT;
if (parent != getNode().parentNode){
parent.appendChild(getNode().cloneNode(true));
};
return (true);
}
public function get type():String{
return (getNode().attributes.type);
}
public function set value(val:String):void{
if (myValueNodes == null){
myValueNodes = new Array();
};
myValueNodes[0] = replaceTextNode(getNode(), myValueNodes[0], "value", val);
}
public function set label(val:String):void{
getNode().attributes.label = val;
}
public function get name():String{
return (getNode().attributes["var"]);
}
public function get value():String{
if (((!((myValueNodes[0] == null))) && (!((myValueNodes[0].firstChild == null))))){
return (myValueNodes[0].firstChild.nodeValue);
};
//unresolved jump
var _slot1 = error;
trace(_slot1.getStackTrace());
return (null);
}
public function set type(val:String):void{
getNode().attributes.type = val;
}
public function getAllOptions():Array{
var res:Array = new Array();
var i:int;
while (i < myOptionNodes.length) {
res.push({label:myOptionNodes[i].attributes.label, value:myOptionNodes[i].firstChild.firstChild.nodeValue});
i++;
};
return (res);
}
public function set name(val:String):void{
getNode().attributes["var"] = val;
}
public function setAllOptions(val:Array):void{
var v:String;
var i:int;
var option:XMLNode;
for (v in myOptionNodes) {
myOptionNodes[v].removeNode();
};
myOptionNodes = new Array();
i = 0;
while (i < val.length) {
option = replaceTextNode(getNode(), undefined, "value", val[i].value);
option.attributes.label = val[i].label;
myOptionNodes[i] = option;
i++;
};
}
public function setAllValues(val:Array):void{
var v:String;
var i:int;
for (v in myValueNodes) {
myValueNodes[v].removeNode();
};
myValueNodes = new Array();
i = 0;
while (i < val.length) {
myValueNodes[i] = replaceTextNode(getNode(), undefined, "value", val[i]);
i++;
};
}
public function get label():String{
return (getNode().attributes.label);
}
public function getAllValues():Array{
var res:Array = new Array();
var i:int;
while (i < myValueNodes.length) {
res.push(myValueNodes[i].firstChild.nodeValue);
i++;
};
return (res);
}
public function deserialize(node:XMLNode):Boolean{
var i:String;
var c:XMLNode;
setNode(node);
myValueNodes = new Array();
myOptionNodes = new Array();
var children:Array = node.childNodes;
for (i in children) {
c = children[i];
switch (children[i].nodeName){
case "desc":
myDescNode = c;
break;
case "required":
myRequiredNode = c;
break;
case "value":
myValueNodes.push(c);
break;
case "option":
myOptionNodes.push(c);
break;
};
};
return (true);
}
}
}//package org.jivesoftware.xiff.data.forms
Section 157
//IIDGenerator (org.jivesoftware.xiff.data.id.IIDGenerator)
package org.jivesoftware.xiff.data.id {
public interface IIDGenerator {
function getID(:String):String;
}
}//package org.jivesoftware.xiff.data.id
Section 158
//IncrementalGenerator (org.jivesoftware.xiff.data.id.IncrementalGenerator)
package org.jivesoftware.xiff.data.id {
public class IncrementalGenerator implements IIDGenerator {
private var myCounter:Number;
private static var instance:IIDGenerator;
public function IncrementalGenerator(){
super();
myCounter = 0;
}
public function getID(prefix:String):String{
var id:String;
myCounter++;
if (prefix != null){
id = (prefix + myCounter);
} else {
id = myCounter.toString();
};
return (id);
}
public static function getInstance():IIDGenerator{
if (instance == null){
instance = new (IncrementalGenerator);
};
return (instance);
}
}
}//package org.jivesoftware.xiff.data.id
Section 159
//Contact (org.jivesoftware.xiff.data.im.Contact)
package org.jivesoftware.xiff.data.im {
import org.jivesoftware.xiff.core.*;
import mx.core.*;
public interface Contact extends IPropertyChangeNotifier {
function set jid(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;org/jivesoftware/xiff/data/im;Contact.as:JID):void;
function get online():Boolean;
function get show():String;
function get jid():JID;
function set online(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;org/jivesoftware/xiff/data/im;Contact.as:Boolean):void;
function set show(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;org/jivesoftware/xiff/data/im;Contact.as:String):void;
function set displayName(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;org/jivesoftware/xiff/data/im;Contact.as:String):void;
function get displayName():String;
}
}//package org.jivesoftware.xiff.data.im
Section 160
//RosterExtension (org.jivesoftware.xiff.data.im.RosterExtension)
package org.jivesoftware.xiff.data.im {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class RosterExtension extends Extension implements IExtension, ISerializable {
private var myItems:Array;
public static var NS:String = "jabber:iq:roster";
public static var SUBSCRIBE_TYPE_NONE:String = "none";
public static var SUBSCRIBE_TYPE_TO:String = "to";
public static var SUBSCRIBE_TYPE_BOTH:String = "both";
public static var ASK_TYPE_SUBSCRIBE:String = "subscribe";
public static var SUBSCRIBE_TYPE_REMOVE:String = "remove";
public static var ASK_TYPE_UNSUBSCRIBE:String = "unsubscribe";
public static var ELEMENT:String = "query";
public static var SHOW_PENDING:String = "Pending";
public static var ASK_TYPE_NONE:String = "none";
private static var staticDepends:Array = [ExtensionClassRegistry];
public static var SUBSCRIBE_TYPE_FROM:String = "from";
public static var SHOW_UNAVAILABLE:String = "unavailable";
public function RosterExtension(parent:XMLNode=null){
myItems = [];
super(parent);
}
public function serialize(parent:XMLNode):Boolean{
var i:String;
var node:XMLNode = getNode();
for (i in myItems) {
if (!myItems[i].serialize(node)){
return (false);
};
};
if (!exists(getNode().parentNode)){
parent.appendChild(getNode().cloneNode(true));
};
return (true);
}
public function getNS():String{
return (RosterExtension.NS);
}
public function addItem(jid:JID=null, subscription:String="", displayName:String="", groups:Array=null):void{
var group:String;
var item:RosterItem = new RosterItem(getNode());
if (exists(jid)){
item.jid = jid;
};
if (exists(subscription)){
item.subscription = subscription;
};
if (exists(displayName)){
item.name = displayName;
};
if (exists(groups)){
for each (group in groups) {
item.addGroupNamed(group);
};
};
}
public function getItemByJID(jid:JID):RosterItem{
var i:String;
for (i in myItems) {
if (myItems[i].jid == jid.toString()){
return (myItems[i]);
};
};
return (null);
}
public function removeAllItems():void{
var i:String;
for (i in myItems) {
myItems[i].setNode(null);
};
myItems = new Array();
}
public function getAllItems():Array{
return (myItems);
}
public function getElementName():String{
return (RosterExtension.ELEMENT);
}
public function deserialize(node:XMLNode):Boolean{
var i:String;
var _local4:RosterItem;
setNode(node);
removeAllItems();
var children:Array = node.childNodes;
for (i in children) {
switch (children[i].nodeName){
case "item":
_local4 = new RosterItem(getNode());
if (!_local4.deserialize(children[i])){
return (false);
};
myItems.push(_local4);
break;
};
};
return (true);
}
public static function enable():void{
ExtensionClassRegistry.register(RosterExtension);
}
}
}//package org.jivesoftware.xiff.data.im
Section 161
//RosterItem (org.jivesoftware.xiff.data.im.RosterItem)
package org.jivesoftware.xiff.data.im {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class RosterItem extends XMLStanza implements ISerializable {
private var myGroupNodes:Array;
public static var ELEMENT:String = "item";
public function RosterItem(parent:XMLNode=null){
super();
getNode().nodeName = ELEMENT;
myGroupNodes = new Array();
if (exists(parent)){
parent.appendChild(getNode());
};
}
public function serialize(parent:XMLNode):Boolean{
if (!exists(jid)){
trace("Warning: required roster item attributes 'jid' missing");
return (false);
};
if (parent != getNode().parentNode){
parent.appendChild(getNode().cloneNode(true));
};
return (true);
}
public function get askType():String{
return (getNode().attributes.ask);
}
public function get subscription():String{
return (getNode().attributes.subscription);
}
public function get jid():JID{
return (new JID(getNode().attributes.jid));
}
public function deserialize(node:XMLNode):Boolean{
var i:String;
setNode(node);
var children:Array = node.childNodes;
for (i in children) {
switch (children[i].nodeName){
case "group":
myGroupNodes.push(children[i]);
break;
};
};
return (true);
}
public function get groupNames():Array{
var i:String;
var node:XMLNode;
var returnArr:Array = new Array();
for (i in myGroupNodes) {
node = myGroupNodes[i].firstChild;
if (node != null){
returnArr.push(node.nodeValue);
};
};
return (returnArr);
}
public function set jid(newJID:JID):void{
getNode().attributes.jid = newJID.toString();
}
public function get name():String{
return (getNode().attributes.name);
}
public function set askType(newAskType:String):void{
getNode().attributes.ask = newAskType;
}
public function get groupCount():Number{
return (myGroupNodes.length);
}
public function removeAllGroups():void{
var i:String;
for (i in myGroupNodes) {
myGroupNodes[i].removeNode();
};
myGroupNodes = new Array();
}
public function set name(newName:String):void{
getNode().attributes.name = newName;
}
public function get pending():Boolean{
if ((((askType == RosterExtension.ASK_TYPE_SUBSCRIBE)) && ((((subscription == RosterExtension.SUBSCRIBE_TYPE_NONE)) || ((subscription == RosterExtension.SUBSCRIBE_TYPE_FROM)))))){
return (true);
};
return (false);
}
public function set subscription(newSubscription:String):void{
getNode().attributes.subscription = newSubscription;
}
public function addGroupNamed(groupName:String):void{
var node:XMLNode = addTextNode(getNode(), "group", groupName);
myGroupNodes.push(node);
}
public function removeGroupByName(groupName:String):Boolean{
var i:String;
for (i in myGroupNodes) {
if (myGroupNodes[i].nodeValue == groupName){
myGroupNodes[i].removeNode();
myGroupNodes.splice(Number(i), 1);
return (true);
};
};
return (false);
}
}
}//package org.jivesoftware.xiff.data.im
Section 162
//RosterItemVO (org.jivesoftware.xiff.data.im.RosterItemVO)
package org.jivesoftware.xiff.data.im {
import flash.events.*;
import org.jivesoftware.xiff.core.*;
import mx.events.*;
public class RosterItemVO extends EventDispatcher implements Contact {
private var _priority:Number;
private var _status:String;
private var _askType:String;
private var _subscribeType:String;
private var _displayName:String;
private var _jid:JID;
private var _show:String;
private var _online:Boolean;// = false
private var _groups:Array;
private static var allContacts:Object = {};
public function RosterItemVO(newJID:JID):void{
_groups = [];
super();
jid = newJID;
}
public function get show():String{
return (_show);
}
public function get jid():JID{
return (_jid);
}
public function set jid(value:JID):void{
var oldValue:Object = this.jid;
if (oldValue !== value){
this._105221jid = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "jid", oldValue, value));
};
}
private function set _892481550status(newStatus:String):void{
var oldStatus:String = status;
_status = newStatus;
PropertyChangeEvent.createUpdateEvent(this, "status", oldStatus, status);
}
public function get pending():Boolean{
return ((((askType == RosterExtension.ASK_TYPE_SUBSCRIBE)) && ((((subscribeType == RosterExtension.SUBSCRIBE_TYPE_NONE)) || ((subscribeType == RosterExtension.SUBSCRIBE_TYPE_FROM))))));
}
public function set uid(i:String):void{
}
private function set _712664749askType(aT:String):void{
var oldasktype:String = askType;
var oldPending:Boolean = pending;
_askType = aT;
PropertyChangeEvent.createUpdateEvent(this, "askType", oldasktype, askType);
PropertyChangeEvent.createUpdateEvent(this, "pending", oldPending, pending);
dispatchEvent(new Event("changeAskType"));
}
public function set online(value:Boolean):void{
var oldValue:Object = this.online;
if (oldValue !== value){
this._1012222381online = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "online", oldValue, value));
};
}
public function get subscribeType():String{
return (_subscribeType);
}
public function set askType(value:String):void{
var oldValue:Object = this.askType;
if (oldValue !== value){
this._712664749askType = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "askType", oldValue, value));
};
}
public function get priority():Number{
return (_priority);
}
public function set subscribeType(value:String):void{
var oldValue:Object = this.subscribeType;
if (oldValue !== value){
this._1572088740subscribeType = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "subscribeType", oldValue, value));
};
}
private function set _1572088740subscribeType(newSub:String):void{
var oldSub:String = subscribeType;
_subscribeType = newSub;
PropertyChangeEvent.createUpdateEvent(this, "subscribeType", oldSub, subscribeType);
dispatchEvent(new Event("changeSubscription"));
}
public function set priority(value:Number):void{
var oldValue:Object = this.priority;
if (oldValue !== value){
this._1165461084priority = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "priority", oldValue, value));
};
}
public function get uid():String{
return (_jid.toString());
}
public function get askType():String{
return (_askType);
}
private function set _105221jid(j:JID):void{
var oldjid:JID = _jid;
_jid = j;
if (!_displayName){
dispatchEvent(new Event("changeDisplayName"));
};
PropertyChangeEvent.createUpdateEvent(this, "jid", oldjid, j);
}
private function set _1012222381online(newState:Boolean):void{
if (newState == online){
return;
};
var oldOnline:Boolean = online;
_online = newState;
PropertyChangeEvent.createUpdateEvent(this, "online", oldOnline, online);
}
public function get online():Boolean{
return (_online);
}
private function set _3529469show(newShow:String):void{
var oldShow:String = show;
_show = newShow;
PropertyChangeEvent.createUpdateEvent(this, "show", oldShow, show);
}
public function set displayName(name:String):void{
var olddisplayname:String = displayName;
_displayName = name;
PropertyChangeEvent.createUpdateEvent(this, "displayName", olddisplayname, displayName);
dispatchEvent(new Event("changeDisplayName"));
}
public function set status(value:String):void{
var oldValue:Object = this.status;
if (oldValue !== value){
this._892481550status = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "status", oldValue, value));
};
}
override public function toString():String{
return (jid.toString());
}
public function get displayName():String{
return ((_displayName) ? _displayName : _jid.node);
}
public function get status():String{
if (!online){
return ("Offline");
};
return ((_status) ? _status : "Available");
}
public function set show(value:String):void{
var oldValue:Object = this.show;
if (oldValue !== value){
this._3529469show = value;
this.dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "show", oldValue, value));
};
}
private function set _1165461084priority(newPriority:Number):void{
var oldPriority:Number = priority;
_priority = newPriority;
PropertyChangeEvent.createUpdateEvent(this, "priority", oldPriority, priority);
}
public static function get(jid:JID, create:Boolean):RosterItemVO{
var bareJID:String = jid.toBareJID();
var item:RosterItemVO = allContacts[bareJID];
if (((!(item)) && (create))){
item = new RosterItemVO(jid.bareJid);
allContacts[bareJID] = item;
};
return (item);
}
}
}//package org.jivesoftware.xiff.data.im
Section 163
//MUC (org.jivesoftware.xiff.data.muc.MUC)
package org.jivesoftware.xiff.data.muc {
import org.jivesoftware.xiff.data.*;
public class MUC {
public static var ADMIN_AFFILIATION:String = "admin";
public static var OWNER_AFFILIATION:String = "owner";
private static var staticDependencies:Array = [ExtensionClassRegistry, MUCExtension, MUCUserExtension, MUCOwnerExtension, MUCAdminExtension];
public static var PARTICIPANT_ROLE:String = "participant";
public static var VISITOR_ROLE:String = "visitor";
public static var MODERATOR_ROLE:String = "moderator";
public static var NO_AFFILIATION:String = "none";
public static var NO_ROLE:String = "none";
public static var MEMBER_AFFILIATION:String = "member";
public static var OUTCAST_AFFILIATION:String = "outcast";
public function MUC(){
super();
}
public static function enable():void{
ExtensionClassRegistry.register(MUCExtension);
ExtensionClassRegistry.register(MUCUserExtension);
ExtensionClassRegistry.register(MUCOwnerExtension);
ExtensionClassRegistry.register(MUCAdminExtension);
}
}
}//package org.jivesoftware.xiff.data.muc
Section 164
//MUCAdminExtension (org.jivesoftware.xiff.data.muc.MUCAdminExtension)
package org.jivesoftware.xiff.data.muc {
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class MUCAdminExtension extends MUCBaseExtension implements IExtension {
private var myItems:Array;
public static var ELEMENT:String = "query";
public static var NS:String = "http://jabber.org/protocol/muc#admin";
public function MUCAdminExtension(parent:XMLNode=null){
super(parent);
}
public function getElementName():String{
return (MUCAdminExtension.ELEMENT);
}
public function getNS():String{
return (MUCAdminExtension.NS);
}
}
}//package org.jivesoftware.xiff.data.muc
Section 165
//MUCBaseExtension (org.jivesoftware.xiff.data.muc.MUCBaseExtension)
package org.jivesoftware.xiff.data.muc {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class MUCBaseExtension extends Extension implements IExtendable, ISerializable {
private var myItems:Array;
public function MUCBaseExtension(parent:XMLNode=null){
myItems = [];
super(parent);
}
public function getAllItems():Array{
return (myItems);
}
public function serialize(parent:XMLNode):Boolean{
var i:String;
var exts:Array;
var ii:String;
var node:XMLNode = getNode();
for (i in myItems) {
if (!myItems[i].serialize(node)){
return (false);
};
};
exts = getAllExtensions();
for (ii in exts) {
if (!exts[ii].serialize(node)){
return (false);
};
};
if (parent != node.parentNode){
parent.appendChild(node.cloneNode(true));
};
return (true);
}
public function removeAllItems():void{
var i:String;
for (i in myItems) {
myItems[i].setNode(null);
};
myItems = new Array();
}
public function addItem(affiliation:String=null, role:String=null, nick:String=null, jid:JID=null, actor:String=null, reason:String=null):MUCItem{
var item:MUCItem = new MUCItem(getNode());
if (exists(affiliation)){
item.affiliation = affiliation;
};
if (exists(role)){
item.role = role;
};
if (exists(nick)){
item.nick = nick;
};
if (exists(jid)){
item.jid = jid;
};
if (exists(actor)){
item.actor = actor;
};
if (exists(reason)){
item.reason = reason;
};
myItems.push(item);
return (item);
}
public function deserialize(node:XMLNode):Boolean{
var children:Array;
var i:String;
var _local6:MUCItem;
var _local7:Class;
var ext:IExtension;
setNode(node);
removeAllItems();
children = node.childNodes;
for (i in children) {
switch (children[i].nodeName){
case "item":
_local6 = new MUCItem(getNode());
_local6.deserialize(children[i]);
myItems.push(_local6);
break;
default:
_local7 = ExtensionClassRegistry.lookup(children[i].attributes.xmlns);
if (_local7 != null){
ext = new (_local7);
if (ext != null){
if ((ext is ISerializable)){
ISerializable(ext).deserialize(children[i]);
};
addExtension(ext);
};
};
break;
};
};
return (true);
}
}
}//package org.jivesoftware.xiff.data.muc
Section 166
//MUCExtension (org.jivesoftware.xiff.data.muc.MUCExtension)
package org.jivesoftware.xiff.data.muc {
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class MUCExtension extends Extension implements IExtension, ISerializable {
private var myPasswordNode:XMLNode;
private var myHistoryNode:XMLNode;
public static var ELEMENT:String = "x";
public static var NS:String = "http://jabber.org/protocol/muc";
public function MUCExtension(parent:XMLNode=null){
super(parent);
}
public function get since():String{
return (myHistoryNode.attributes.since);
}
public function get seconds():Number{
return (Number(myHistoryNode.attributes.seconds));
}
public function deserialize(node:XMLNode):Boolean{
var i:String;
setNode(node);
var children:Array = node.childNodes;
for (i in children) {
switch (children[i].nodeName){
case "history":
myHistoryNode = children[i];
break;
case "password":
myPasswordNode = children[i];
break;
};
};
return (true);
}
public function get history():Boolean{
return (exists(myHistoryNode));
}
public function addChildNode(childNode:XMLNode):void{
getNode().appendChild(childNode);
}
public function serialize(parent:XMLNode):Boolean{
if (exists(getNode().parentNode)){
return (false);
};
var node:XMLNode = getNode().cloneNode(true);
var extensions:Array = getAllExtensions();
var i:int;
while (i < extensions.length) {
if ((extensions[i] is ISerializable)){
ISerializable(extensions[i]).serialize(node);
};
i++;
};
parent.appendChild(node);
return (true);
}
public function get password():String{
return (myPasswordNode.firstChild.nodeValue);
}
public function set history(val:Boolean):void{
if (val){
myHistoryNode = ensureNode(myHistoryNode, "history");
} else {
myHistoryNode.removeNode();
myHistoryNode = null;
};
}
public function getElementName():String{
return (MUCExtension.ELEMENT);
}
public function set maxchars(val:Number):void{
myHistoryNode = ensureNode(myHistoryNode, "history");
myHistoryNode.attributes.maxchars = val.toString();
}
public function set maxstanzas(val:Number):void{
myHistoryNode = ensureNode(myHistoryNode, "history");
myHistoryNode.attributes.maxstanzas = val.toString();
}
public function set password(val:String):void{
myPasswordNode = replaceTextNode(getNode(), myPasswordNode, "password", val);
}
public function get maxchars():Number{
return (Number(myHistoryNode.attributes.maxchars));
}
public function get maxstanzas():Number{
return (Number(myHistoryNode.attributes.maxstanzas));
}
public function set since(val:String):void{
myHistoryNode = ensureNode(myHistoryNode, "history");
myHistoryNode.attributes.since = val;
}
public function getNS():String{
return (MUCExtension.NS);
}
public function set seconds(val:Number):void{
myHistoryNode = ensureNode(myHistoryNode, "history");
myHistoryNode.attributes.seconds = val.toString();
}
}
}//package org.jivesoftware.xiff.data.muc
Section 167
//MUCItem (org.jivesoftware.xiff.data.muc.MUCItem)
package org.jivesoftware.xiff.data.muc {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class MUCItem extends XMLStanza implements ISerializable {
private var myActorNode:XMLNode;
private var myReasonNode:XMLNode;
public static var ELEMENT:String = "item";
public function MUCItem(parent:XMLNode=null){
super();
getNode().nodeName = ELEMENT;
if (exists(parent)){
parent.appendChild(getNode());
};
}
public function serialize(parent:XMLNode):Boolean{
if (parent != getNode().parentNode){
parent.appendChild(getNode().cloneNode(true));
};
return (true);
}
public function get nick():String{
return (getNode().attributes.nick);
}
public function get jid():JID{
if (getNode().attributes.jid == null){
return (null);
};
return (new JID(getNode().attributes.jid));
}
public function deserialize(node:XMLNode):Boolean{
var i:String;
setNode(node);
var children:Array = node.childNodes;
for (i in children) {
switch (children[i].nodeName){
case "actor":
myActorNode = children[i];
break;
case "reason":
myReasonNode = children[i];
break;
};
};
return (true);
}
public function set reason(val:String):void{
myReasonNode = replaceTextNode(getNode(), myReasonNode, "reason", val);
}
public function set actor(val:String):void{
myActorNode = ensureNode(myActorNode, "actor");
myActorNode.attributes.jid = val;
}
public function set role(val:String):void{
getNode().attributes.role = val;
}
public function set nick(val:String):void{
getNode().attributes.nick = val;
}
public function set affiliation(val:String):void{
getNode().attributes.affiliation = val;
}
public function get affiliation():String{
return (getNode().attributes.affiliation);
}
public function set jid(val:JID):void{
getNode().attributes.jid = val.toString();
}
public function get actor():String{
return (myActorNode.attributes.jid);
}
public function get reason():String{
return (myReasonNode.firstChild.nodeValue);
}
public function get role():String{
return (getNode().attributes.role);
}
}
}//package org.jivesoftware.xiff.data.muc
Section 168
//MUCOwnerExtension (org.jivesoftware.xiff.data.muc.MUCOwnerExtension)
package org.jivesoftware.xiff.data.muc {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class MUCOwnerExtension extends MUCBaseExtension implements IExtension {
private var myDestroyNode:XMLNode;
public static var ELEMENT:String = "query";
public static var NS:String = "http://jabber.org/protocol/muc#owner";
public function MUCOwnerExtension(parent:XMLNode=null){
super(parent);
}
public function getElementName():String{
return (MUCOwnerExtension.ELEMENT);
}
public function destroy(reason:String, alternateJID:JID):void{
var i:String;
myDestroyNode = ensureNode(myDestroyNode, "destroy");
for (i in myDestroyNode.childNodes) {
myDestroyNode.childNodes[i].removeNode();
};
if (exists(reason)){
replaceTextNode(myDestroyNode, undefined, "reason", reason);
};
if (exists(alternateJID)){
myDestroyNode.attributes.jid = alternateJID.toString();
};
}
public function getNS():String{
return (MUCOwnerExtension.NS);
}
override public function serialize(parent:XMLNode):Boolean{
return (super.serialize(parent));
}
override public function deserialize(node:XMLNode):Boolean{
var i:String;
super.deserialize(node);
var children:Array = node.childNodes;
for (i in children) {
switch (children[i].nodeName){
case "destroy":
myDestroyNode = children[i];
break;
};
};
return (true);
}
}
}//package org.jivesoftware.xiff.data.muc
Section 169
//MUCStatus (org.jivesoftware.xiff.data.muc.MUCStatus)
package org.jivesoftware.xiff.data.muc {
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class MUCStatus {
private var node:XMLNode;
private var parent:XMLStanza;
public function MUCStatus(xmlNode:XMLNode, parentStanza:XMLStanza){
super();
node = (xmlNode) ? xmlNode : new XMLNode(1, "status");
parent = parentStanza;
}
public function set code(newCode:Number):void{
node.attributes.code = newCode.toString();
}
public function get message():String{
return (node.firstChild.nodeValue);
}
public function get code():Number{
return (node.attributes.code);
}
public function set message(val:String):void{
node = parent.replaceTextNode(parent.getNode(), node, "status", val);
}
}
}//package org.jivesoftware.xiff.data.muc
Section 170
//MUCUserExtension (org.jivesoftware.xiff.data.muc.MUCUserExtension)
package org.jivesoftware.xiff.data.muc {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class MUCUserExtension extends MUCBaseExtension implements IExtension {
private var myPasswordNode:XMLNode;
private var myActionNode:XMLNode;
private var myStatuses:Array;
public static var DECLINE_TYPE:String = "decline";
public static var NS:String = "http://jabber.org/protocol/muc#user";
public static var OTHER_TYPE:String = "other";
public static var INVITE_TYPE:String = "invite";
public static var ELEMENT:String = "x";
public static var DESTROY_TYPE:String = "destroy";
public function MUCUserExtension(parent:XMLNode=null){
myStatuses = [];
super(parent);
}
public function set statuses(newStatuses:Array):void{
myStatuses = newStatuses;
}
public function get type():String{
if (myActionNode == null){
return (null);
};
return (((myActionNode.nodeName == null)) ? OTHER_TYPE : myActionNode.nodeName);
}
public function get reason():String{
if (myActionNode.firstChild != null){
if (myActionNode.firstChild.firstChild != null){
return (myActionNode.firstChild.firstChild.nodeValue);
};
};
return (null);
}
public function get jid():JID{
return (new JID(myActionNode.attributes.jid));
}
override public function deserialize(node:XMLNode):Boolean{
var i:String;
super.deserialize(node);
var children:Array = node.childNodes;
for (i in children) {
switch (children[i].nodeName){
case DECLINE_TYPE:
myActionNode = children[i];
break;
case DESTROY_TYPE:
myActionNode = children[i];
break;
case INVITE_TYPE:
myActionNode = children[i];
break;
case "status":
myStatuses.push(new MUCStatus(children[i], this));
break;
case "password":
myPasswordNode = children[i];
break;
};
};
return (true);
}
public function invite(to:JID, from:JID, reason:String):void{
updateActionNode(INVITE_TYPE, {to:to.toString(), from:(from) ? from.toString() : null}, reason);
}
public function get password():String{
if (myPasswordNode == null){
return (null);
};
return (myPasswordNode.firstChild.nodeValue);
}
private function updateActionNode(type:String, attrs:Object, reason:String):void{
var i:*;
if (myActionNode != null){
myActionNode.removeNode();
};
myActionNode = XMLFactory.createElement(type);
for (i in attrs) {
if (exists(attrs[i])){
myActionNode.attributes[i] = attrs[i];
};
};
getNode().appendChild(myActionNode);
if (reason.length > 0){
replaceTextNode(myActionNode, undefined, "reason", reason);
};
}
public function getNS():String{
return (MUCUserExtension.NS);
}
public function get statuses():Array{
return (myStatuses);
}
public function get from():JID{
return (new JID(myActionNode.attributes.from));
}
public function set password(val:String):void{
myPasswordNode = replaceTextNode(getNode(), myPasswordNode, "password", val);
}
public function getElementName():String{
return (MUCUserExtension.ELEMENT);
}
public function hasStatusCode(code:Number):Boolean{
var status:MUCStatus;
for each (status in statuses) {
if (status.code == code){
return (true);
};
};
return (false);
}
public function destroy(room:JID, reason:String):void{
updateActionNode(DESTROY_TYPE, {jid:room.toString()}, reason);
}
public function get to():JID{
return (new JID(myActionNode.attributes.to));
}
public function decline(to:JID, from:JID, reason:String):void{
updateActionNode(DECLINE_TYPE, {to:to.toString(), from:(from) ? from.toString() : null}, reason);
}
}
}//package org.jivesoftware.xiff.data.muc
Section 171
//RegisterExtension (org.jivesoftware.xiff.data.register.RegisterExtension)
package org.jivesoftware.xiff.data.register {
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class RegisterExtension extends Extension implements IExtension, ISerializable {
private var myFields:Object;
private var myInstructionsNode:XMLNode;
private var myKeyNode:XMLNode;
private var myRemoveNode:XMLNode;
public static var NS:String = "jabber:iq:register";
private static var staticDepends:Class = ExtensionClassRegistry;
public static var ELEMENT:String = "query";
public function RegisterExtension(parent:XMLNode=null){
super(parent);
myFields = new Object();
}
public function getElementName():String{
return (RegisterExtension.ELEMENT);
}
public function set unregister(val:Boolean):void{
myRemoveNode = replaceTextNode(getNode(), myRemoveNode, "remove", "");
}
public function get state():String{
return (getField("state"));
}
public function get last():String{
return (getField("last"));
}
public function getNS():String{
return (RegisterExtension.NS);
}
public function get email():String{
return (getField("email"));
}
public function get zip():String{
return (getField("zip"));
}
public function get instructions():String{
return (myInstructionsNode.firstChild.nodeValue);
}
public function set state(val:String):void{
setField("state", val);
}
public function get password():String{
return (getField("password"));
}
public function set last(val:String):void{
setField("last", val);
}
public function get text():String{
return (getField("text"));
}
public function get date():String{
return (getField("date"));
}
public function get first():String{
return (getField("first"));
}
public function set username(val:String):void{
setField("username", val);
}
public function set password(val:String):void{
setField("password", val);
}
public function setField(name:String, val:String):void{
myFields[name] = replaceTextNode(getNode(), myFields[name], name, val);
}
public function get unregister():Boolean{
return (exists(myRemoveNode));
}
public function set key(val:String):void{
myKeyNode = replaceTextNode(getNode(), myKeyNode, "key", val);
}
public function set email(val:String):void{
setField("email", val);
}
public function set zip(val:String):void{
setField("zip", val);
}
public function getField(name:String):String{
return (myFields[name].firstChild.nodeValue);
}
public function set nick(val:String):void{
setField("nick", val);
}
public function set instructions(val:String):void{
myInstructionsNode = replaceTextNode(getNode(), myInstructionsNode, "instructions", val);
}
public function get username():String{
return (getField("username"));
}
public function set misc(val:String):void{
setField("misc", val);
}
public function set text(val:String):void{
setField("text", val);
}
public function set phone(val:String):void{
setField("phone", val);
}
public function set city(val:String):void{
setField("city", val);
}
public function set url(val:String):void{
setField("url", val);
}
public function get key():String{
return (myKeyNode.firstChild.nodeValue);
}
public function serialize(parentNode:XMLNode):Boolean{
if (!exists(getNode().parentNode)){
parentNode.appendChild(getNode().cloneNode(true));
};
return (true);
}
public function getRequiredFieldNames():Array{
var i:String;
var fields:Array = new Array();
for (i in myFields) {
fields.push(i);
};
return (fields);
}
public function set address(val:String):void{
setField("address", val);
}
public function get city():String{
return (getField("city"));
}
public function get misc():String{
return (getField("misc"));
}
public function get phone():String{
return (getField("phone"));
}
public function get url():String{
return (getField("url"));
}
public function get address():String{
return (getField("address"));
}
public function set first(val:String):void{
setField("first", val);
}
public function get nick():String{
return (getField("nick"));
}
public function set date(val:String):void{
setField("date", val);
}
public function deserialize(node:XMLNode):Boolean{
var i:String;
setNode(node);
var children:Array = getNode().childNodes;
for (i in children) {
switch (children[i].nodeName){
case "key":
myKeyNode = children[i];
break;
case "instructions":
myInstructionsNode = children[i];
break;
case "remove":
myRemoveNode = children[i];
break;
default:
myFields[children[i].nodeName] = children[i];
break;
};
};
return (true);
}
public static function enable():void{
ExtensionClassRegistry.register(RegisterExtension);
}
}
}//package org.jivesoftware.xiff.data.register
Section 172
//SessionExtension (org.jivesoftware.xiff.data.session.SessionExtension)
package org.jivesoftware.xiff.data.session {
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class SessionExtension extends Extension implements IExtension, ISerializable {
private var jid:String;
public static var NS:String = "urn:ietf:params:xml:ns:xmpp-session";
public static var ELEMENT_NAME:String = "session";
public function SessionExtension(parent:XMLNode=null){
super(parent);
}
public function serialize(parent:XMLNode):Boolean{
var child:XMLNode;
if (!exists(getNode().parentNode)){
child = getNode().cloneNode(true);
parent.appendChild(child);
};
return (true);
}
public function getElementName():String{
return (SessionExtension.ELEMENT_NAME);
}
public function getNS():String{
return (SessionExtension.NS);
}
public function deserialize(node:XMLNode):Boolean{
setNode(node);
return (true);
}
public function getJID():String{
return (jid);
}
public static function enable():void{
ExtensionClassRegistry.register(SessionExtension);
}
}
}//package org.jivesoftware.xiff.data.session
Section 173
//XHTMLExtension (org.jivesoftware.xiff.data.xhtml.XHTMLExtension)
package org.jivesoftware.xiff.data.xhtml {
import flash.xml.*;
import org.jivesoftware.xiff.data.*;
public class XHTMLExtension extends Extension implements IExtension {
public static var NS:String = "http://www.w3.org/1999/xhtml";
private static var staticDepends:Class = ExtensionClassRegistry;
public static var ELEMENT:String = "html";
public function XHTMLExtension(parent:XMLNode=null){
super(parent);
}
public function get body():String{
var i:String;
var html:Array = new Array();
var children:Array = getNode().childNodes;
for (i in children) {
html.push(children[i].toString());
};
html.reverse();
return (html.join());
}
public function set body(theBody:String):void{
var i:String;
var children:Array = getNode().childNodes;
for (i in children) {
children[i].removeNode();
};
getNode().appendChild(new XMLDocument(theBody));
}
public function getElementName():String{
return (_slot1.ELEMENT);
}
public function getNS():String{
return (_slot1.NS);
}
public static function enable():void{
ExtensionClassRegistry.register(_slot1);
}
}
}//package org.jivesoftware.xiff.data.xhtml
Section 174
//Extension (org.jivesoftware.xiff.data.Extension)
package org.jivesoftware.xiff.data {
import flash.xml.*;
public class Extension extends XMLStanza {
public function Extension(parent:XMLNode=null){
super();
getNode().nodeName = IExtension(this).getElementName();
getNode().attributes.xmlns = IExtension(this).getNS();
if (exists(parent)){
parent.appendChild(getNode());
};
}
public function remove():void{
getNode().removeNode();
}
public function toString():String{
return (getNode().toString());
}
}
}//package org.jivesoftware.xiff.data
Section 175
//ExtensionClassRegistry (org.jivesoftware.xiff.data.ExtensionClassRegistry)
package org.jivesoftware.xiff.data {
public class ExtensionClassRegistry {
private static var myClasses:Array = new Array();
public function ExtensionClassRegistry(){
super();
}
public static function register(extensionClass:Class):Boolean{
var extensionInstance:IExtension = new (extensionClass);
if ((extensionInstance is IExtension)){
myClasses[extensionInstance.getNS()] = extensionClass;
return (true);
};
return (false);
}
public static function lookup(ns:String):Class{
return (myClasses[ns]);
}
}
}//package org.jivesoftware.xiff.data
Section 176
//ExtensionContainer (org.jivesoftware.xiff.data.ExtensionContainer)
package org.jivesoftware.xiff.data {
public class ExtensionContainer implements IExtendable {
public var _exts:Object;
public function ExtensionContainer(){
super();
_exts = new Object();
}
public function removeAllExtensions(ns:String):void{
var i:String;
for (i in _exts[ns]) {
_exts[ns][i].ns();
};
_exts[ns] = new Array();
}
public function getAllExtensionsByNS(ns:String):Array{
return (_exts[ns]);
}
public function getExtension(name:String):Extension{
var name = name;
return (getAllExtensions().filter(function (obj:IExtension, idx:int, arr:Array):Boolean{
return ((obj.getElementName() == name));
})[0]);
}
public function removeExtension(ext:IExtension):Boolean{
var i:String;
var extensions:Object = _exts[ext.getNS()];
for (i in extensions) {
if (extensions[i] === ext){
extensions[i].remove();
extensions.splice(Number(i), 1);
return (true);
};
};
return (false);
}
public function addExtension(ext:IExtension):IExtension{
if (_exts[ext.getNS()] == null){
_exts[ext.getNS()] = new Array();
};
_exts[ext.getNS()].push(ext);
return (ext);
}
public function getAllExtensions():Array{
var ns:String;
var exts:Array = new Array();
for (ns in _exts) {
exts = exts.concat(_exts[ns]);
};
return (exts);
}
}
}//package org.jivesoftware.xiff.data
Section 177
//IExtendable (org.jivesoftware.xiff.data.IExtendable)
package org.jivesoftware.xiff.data {
public interface IExtendable {
function removeAllExtensions(org.jivesoftware.xiff.data:String):void;
function getAllExtensionsByNS(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;org/jivesoftware/xiff/data;IExtendable.as:String):Array;
function removeExtension(org.jivesoftware.xiff.data:IExtendable/org.jivesoftware.xiff.data:IExtendable:addExtension:IExtension):Boolean;
function addExtension(:IExtension):IExtension;
function getAllExtensions():Array;
}
}//package org.jivesoftware.xiff.data
Section 178
//IExtension (org.jivesoftware.xiff.data.IExtension)
package org.jivesoftware.xiff.data {
public interface IExtension {
function getElementName():String;
function getNS():String;
}
}//package org.jivesoftware.xiff.data
Section 179
//INodeProxy (org.jivesoftware.xiff.data.INodeProxy)
package org.jivesoftware.xiff.data {
import flash.xml.*;
public interface INodeProxy {
function getNode():XMLNode;
function setNode(/Users/vinsonb/kongregate/trunk/lib/flash/AS3;org/jivesoftware/xiff/data;INodeProxy.as:XMLNode):Boolean;
}
}//package org.jivesoftware.xiff.data
Section 180
//IQ (org.jivesoftware.xiff.data.IQ)
package org.jivesoftware.xiff.data {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
public class IQ extends XMPPStanza implements ISerializable {
private var myCallbackScope:Object;
private var myQueryName:String;
private var myCallback:String;
private var myCallbackFunc:Function;
private var myQueryFields:Array;
public static var ERROR_TYPE:String = "error";
public static var GET_TYPE:String = "get";
public static var SET_TYPE:String = "set";
public static var RESULT_TYPE:String = "result";
public function IQ(recipient:JID=null, iqType:String=null, iqID:String=null, iqCallback:String=null, iqCallbackScope:Object=null, iqCallbackFunc:Function=null){
var id:String = (exists(iqID)) ? iqID : generateID("iq_");
super(recipient, null, iqType, id, "iq");
callbackName = iqCallback;
callbackScope = iqCallbackScope;
callback = iqCallbackFunc;
}
override public function serialize(parentNode:XMLNode):Boolean{
return (super.serialize(parentNode));
}
public function get callback():Function{
return (myCallbackFunc);
}
public function set callback(aFunc:Function):void{
myCallbackFunc = aFunc;
}
public function get callbackName():String{
return (myCallback);
}
public function get callbackScope():Object{
return (myCallbackScope);
}
public function set callbackName(aName:String):void{
myCallback = aName;
}
public function set callbackScope(scope:Object):void{
myCallbackScope = scope;
}
override public function deserialize(xmlNode:XMLNode):Boolean{
return (super.deserialize(xmlNode));
}
}
}//package org.jivesoftware.xiff.data
Section 181
//ISerializable (org.jivesoftware.xiff.data.ISerializable)
package org.jivesoftware.xiff.data {
import flash.xml.*;
public interface ISerializable {
function serialize(:XMLNode):Boolean;
function deserialize(:XMLNode):Boolean;
}
}//package org.jivesoftware.xiff.data
Section 182
//Message (org.jivesoftware.xiff.data.Message)
package org.jivesoftware.xiff.data {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.muc.*;
import org.jivesoftware.xiff.data.xhtml.*;
public class Message extends XMPPStanza implements ISerializable {
private var mySubjectNode:XMLNode;
private var myTimeStampNode:XMLNode;
private var myBodyNode:XMLNode;
private var myThreadNode:XMLNode;
public static var CHAT_TYPE:String = "chat";
public static var HEADLINE_TYPE:String = "headline";
private static var isMessageStaticCalled:Boolean = MessageStaticConstructor();
public static var ERROR_TYPE:String = "error";
public static var NORMAL_TYPE:String = "normal";
private static var staticConstructorDependency:Array = [XMPPStanza, XHTMLExtension, ExtensionClassRegistry];
public static var GROUPCHAT_TYPE:String = "groupchat";
public function Message(recipient:JID=null, msgID:String=null, msgBody:String=null, msgHTMLBody:String=null, msgType:String=null, msgSubject:String=null){
var msgId:String = (exists(msgID)) ? msgID : generateID("m_");
super(recipient, null, msgType, msgId, "message");
body = msgBody;
htmlBody = msgHTMLBody;
subject = msgSubject;
}
public function set time(theTime:Date):void{
}
public function set thread(theThread:String):void{
myThreadNode = replaceTextNode(getNode(), myThreadNode, "thread", theThread);
}
public function set subject(aSubject:String):void{
mySubjectNode = replaceTextNode(getNode(), mySubjectNode, "subject", aSubject);
}
public function get body():String{
if (!exists(myBodyNode)){
return (null);
};
var value = "";
value = myBodyNode.firstChild.nodeValue;
//unresolved jump
var _slot1 = error;
trace(_slot1.getStackTrace());
return (value);
}
public function get thread():String{
if (myThreadNode == null){
return (null);
};
return (myThreadNode.firstChild.nodeValue);
}
public function set body(bodyText:String):void{
myBodyNode = replaceTextNode(getNode(), myBodyNode, "body", bodyText);
}
override public function serialize(parentNode:XMLNode):Boolean{
return (super.serialize(parentNode));
}
public function get htmlBody():String{
var ext:XHTMLExtension;
ext = getAllExtensionsByNS(XHTMLExtension.NS)[0];
return (ext.body);
//unresolved jump
var _slot1 = e;
trace("Error : null trapped. Resuming.");
return (null);
}
public function set htmlBody(bodyHTML:String):void{
var ext:XHTMLExtension;
removeAllExtensions(XHTMLExtension.NS);
if (((exists(bodyHTML)) && ((bodyHTML.length > 0)))){
ext = new XHTMLExtension(getNode());
ext.body = bodyHTML;
addExtension(ext);
};
}
public function get subject():String{
if (mySubjectNode == null){
return (null);
};
return (mySubjectNode.firstChild.nodeValue);
}
public function get time():Date{
if (myTimeStampNode == null){
return (null);
};
var stamp:String = myTimeStampNode.attributes.stamp;
var t:Date = new Date();
t.setUTCFullYear(stamp.slice(0, 4));
t.setUTCMonth((Number(stamp.slice(4, 6)) - 1));
t.setUTCDate(stamp.slice(6, 8));
t.setUTCHours(stamp.slice(9, 11));
t.setUTCMinutes(stamp.slice(12, 14));
t.setUTCSeconds(stamp.slice(15, 17));
return (t);
}
override public function deserialize(xmlNode:XMLNode):Boolean{
var children:Array;
var i:String;
var mucUserExtension:MUCUserExtension;
var isSerialized:Boolean = super.deserialize(xmlNode);
if (isSerialized){
children = xmlNode.childNodes;
for (i in children) {
switch (children[i].nodeName){
case "error":
break;
case "body":
myBodyNode = children[i];
break;
case "subject":
mySubjectNode = children[i];
break;
case "thread":
myThreadNode = children[i];
break;
case "x":
if (children[i].attributes.xmlns == "jabber:x:delay"){
myTimeStampNode = children[i];
};
if (children[i].attributes.xmlns == MUCUserExtension.NS){
mucUserExtension = new MUCUserExtension(getNode());
mucUserExtension.deserialize(children[i]);
addExtension(mucUserExtension);
};
break;
};
};
};
return (isSerialized);
}
public static function MessageStaticConstructor():Boolean{
XHTMLExtension.enable();
return (true);
}
}
}//package org.jivesoftware.xiff.data
Section 183
//Presence (org.jivesoftware.xiff.data.Presence)
package org.jivesoftware.xiff.data {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.muc.*;
public class Presence extends XMPPStanza implements ISerializable {
private var myStatusNode:XMLNode;
private var myShowNode:XMLNode;
private var myPriorityNode:XMLNode;
public static const SHOW_CHAT:String = "chat";
public static const UNSUBSCRIBED_TYPE:String = "unsubscribed";
public static const SHOW_DND:String = "dnd";
public static const UNSUBSCRIBE_TYPE:String = "unsubscribe";
public static const UNAVAILABLE_TYPE:String = "unavailable";
public static const SHOW_XA:String = "xa";
public static const SUBSCRIBE_TYPE:String = "subscribe";
public static const ERROR_TYPE:String = "error";
public static const SHOW_AWAY:String = "away";
public static const PROBE_TYPE:String = "probe";
public static const SUBSCRIBED_TYPE:String = "subscribed";
public function Presence(recipient:JID=null, sender:JID=null, presenceType:String=null, showVal:String=null, statusVal:String=null, priorityVal:Number=0){
super(recipient, sender, presenceType, null, "presence");
show = showVal;
status = statusVal;
priority = priorityVal;
}
public function get role():String{
var userExts:Array = getAllExtensionsByNS(MUCUserExtension.NS);
var item:MUCItem = userExts[0].getAllItems()[0];
return (item.role);
}
override public function deserialize(xmlNode:XMLNode):Boolean{
var children:Array;
var i:String;
var isDeserialized:Boolean = super.deserialize(xmlNode);
if (isDeserialized){
children = xmlNode.childNodes;
for (i in children) {
switch (children[i].nodeName){
case "show":
myShowNode = children[i];
break;
case "status":
myStatusNode = children[i];
break;
case "priority":
myPriorityNode = children[i];
break;
};
};
};
return (isDeserialized);
}
public function set priority(priorityVal:Number):void{
myPriorityNode = replaceTextNode(getNode(), myPriorityNode, "priority", priorityVal.toString());
}
public function get priority():Number{
if (myPriorityNode == null){
return (NaN);
};
var p:Number = Number(myPriorityNode.firstChild.nodeValue);
if (isNaN(p)){
return (NaN);
};
return (p);
}
override public function serialize(parentNode:XMLNode):Boolean{
return (super.serialize(parentNode));
}
public function get status():String{
if ((((myStatusNode == null)) || ((myStatusNode.firstChild == null)))){
return (null);
};
return (myStatusNode.firstChild.nodeValue);
}
public function set show(showVal:String):void{
if (((((((((((!((showVal == SHOW_AWAY))) && (!((showVal == SHOW_CHAT))))) && (!((showVal == SHOW_DND))))) && (!((showVal == SHOW_XA))))) && (!((showVal == null))))) && (!((showVal == ""))))){
throw (new Error((("Invalid show value: " + showVal) + " for presence")));
};
if (((myShowNode) && ((((showVal == null)) || ((showVal == "")))))){
myShowNode.removeNode();
myShowNode = null;
};
myShowNode = replaceTextNode(getNode(), myShowNode, "show", showVal);
}
public function set status(statusVal:String):void{
myStatusNode = replaceTextNode(getNode(), myStatusNode, "status", statusVal);
}
public function get show():String{
if (((!(myShowNode)) || (!(exists(myShowNode.firstChild))))){
return (null);
};
return (myShowNode.firstChild.nodeValue);
}
}
}//package org.jivesoftware.xiff.data
Section 184
//XMLStanza (org.jivesoftware.xiff.data.XMLStanza)
package org.jivesoftware.xiff.data {
import flash.xml.*;
public class XMLStanza extends ExtensionContainer implements INodeProxy, IExtendable {
private var myXML:XMLNode;
public static var XMLFactory:XMLDocument = new XMLDocument();
public function XMLStanza(){
super();
myXML = XMLStanza.XMLFactory.createElement("");
}
public function addTextNode(parent:XMLNode, elementName:String, value:String):XMLNode{
var newNode:XMLNode = XMLStanza.XMLFactory.createElement(elementName);
newNode.appendChild(XMLFactory.createTextNode(value));
parent.appendChild(newNode);
return (newNode);
}
public function setNode(node:XMLNode):Boolean{
var oldParent:XMLNode = myXML.parentNode;
myXML.removeNode();
myXML = node;
if (((exists(myXML)) && (!((oldParent == null))))){
oldParent.appendChild(myXML);
};
return (true);
}
public function ensureNode(node:XMLNode, elementName:String):XMLNode{
if (!exists(node)){
node = XMLStanza.XMLFactory.createElement(elementName);
getNode().appendChild(node);
};
return (node);
}
public function getNode():XMLNode{
return (myXML);
}
public function replaceTextNode(parent:XMLNode, original:XMLNode, elementName:String, value:String):XMLNode{
var newNode:XMLNode;
if (original != null){
original.removeNode();
};
if (exists(value)){
newNode = XMLStanza.XMLFactory.createElement(elementName);
if (value.length > 0){
newNode.appendChild(XMLStanza.XMLFactory.createTextNode(value));
};
parent.appendChild(newNode);
};
return (newNode);
}
public static function exists(val):Boolean{
if (((!((val == null))) && (!((val === undefined))))){
return (true);
};
return (false);
}
}
}//package org.jivesoftware.xiff.data
Section 185
//XMPPStanza (org.jivesoftware.xiff.data.XMPPStanza)
package org.jivesoftware.xiff.data {
import org.jivesoftware.xiff.core.*;
import flash.xml.*;
import org.jivesoftware.xiff.data.id.*;
public dynamic class XMPPStanza extends XMLStanza implements ISerializable, IExtendable {
private var myErrorNode:XMLNode;
private var myErrorConditionNode:XMLNode;
private static var staticDependencies = [IncrementalGenerator, ExtensionContainer];
public static var CLIENT_NS:String = "jabber:client";
private static var isStaticConstructed = XMPPStanzaStaticConstructor();
public function XMPPStanza(recipient:JID, sender:JID, theType:String, theID:String, nName:String){
super();
getNode().nodeName = nName;
to = recipient;
from = sender;
type = theType;
id = theID;
}
public function get type():String{
return (getNode().attributes.type);
}
public function set errorType(aType:String):void{
myErrorNode = ensureNode(myErrorNode, "error");
delete myErrorNode.attributes.type;
if (exists(aType)){
myErrorNode.attributes.type = aType;
};
}
public function set from(sender:JID):void{
delete getNode().attributes.from;
if (exists(sender)){
getNode().attributes.from = sender.toString();
};
}
public function get errorCode():Number{
return (Number(myErrorNode.attributes.code));
}
public function get id():String{
return (getNode().attributes.id);
}
public function get errorMessage():String{
if (exists(errorCondition)){
return (errorCondition.toString());
};
return (myErrorNode.firstChild.nodeValue);
}
public function serialize(parentNode:XMLNode):Boolean{
var ext:ISerializable;
var node:XMLNode = getNode();
var exts:Array = getAllExtensions();
for each (ext in exts) {
ext.serialize(node);
};
if (!exists(node.parentNode)){
node = node.cloneNode(true);
parentNode.appendChild(node);
};
return (true);
}
public function get errorType():String{
return (myErrorNode.attributes.type);
}
public function set errorCondition(aCondition:String):void{
myErrorNode = ensureNode(myErrorNode, "error");
var attributes:Object = myErrorNode.attributes;
var msg:String = errorMessage;
if (exists(aCondition)){
myErrorNode = replaceTextNode(getNode(), myErrorNode, "error", "");
myErrorConditionNode = addTextNode(myErrorNode, aCondition, msg);
} else {
myErrorNode = replaceTextNode(getNode(), myErrorNode, "error", msg);
};
myErrorNode.attributes = attributes;
}
public function get from():JID{
return (new JID(getNode().attributes.from));
}
public function set errorCode(aCode:Number):void{
myErrorNode = ensureNode(myErrorNode, "error");
delete myErrorNode.attributes.code;
if (exists(aCode)){
myErrorNode.attributes.code = aCode;
};
}
public function get errorCondition():String{
if (exists(myErrorConditionNode)){
return (myErrorConditionNode.nodeName);
};
return (null);
}
public function set type(theType:String):void{
delete getNode().attributes.type;
if (exists(theType)){
getNode().attributes.type = theType;
};
}
public function set id(theID:String):void{
delete getNode().attributes.id;
if (exists(theID)){
getNode().attributes.id = theID;
};
}
public function get to():JID{
return (new JID(getNode().attributes.to));
}
public function set to(recipient:JID):void{
delete getNode().attributes.to;
if (exists(recipient)){
getNode().attributes.to = recipient.toString();
};
}
public function set errorMessage(theMsg:String):void{
var attributes:Object;
myErrorNode = ensureNode(myErrorNode, "error");
theMsg = (exists(theMsg)) ? theMsg : "";
if (exists(errorCondition)){
myErrorConditionNode = replaceTextNode(myErrorNode, myErrorConditionNode, errorCondition, theMsg);
} else {
attributes = myErrorNode.attributes;
myErrorNode = replaceTextNode(getNode(), myErrorNode, "error", theMsg);
myErrorNode.attributes = attributes;
};
}
public function deserialize(xmlNode:XMLNode):Boolean{
var i:String;
var nName:String;
var nNamespace:String;
var extClass:Class;
var ext:IExtension;
setNode(xmlNode);
var children:Array = xmlNode.childNodes;
for (i in children) {
nName = children[i].nodeName;
nNamespace = children[i].attributes.xmlns;
nNamespace = (exists(nNamespace)) ? nNamespace : CLIENT_NS;
if (nName == "error"){
myErrorNode = children[i];
if (exists(myErrorNode.firstChild.nodeName)){
myErrorConditionNode = myErrorNode.firstChild;
};
} else {
extClass = ExtensionClassRegistry.lookup(nNamespace);
if (extClass != null){
ext = new (extClass);
ISerializable(ext).deserialize(children[i]);
addExtension(ext);
};
};
};
return (true);
}
public static function generateID(prefix:String):String{
var id:String = IncrementalGenerator.getInstance().getID(prefix);
return (id);
}
public static function setIDGenerator(generator:IIDGenerator):void{
}
private static function XMPPStanzaStaticConstructor():void{
}
}
}//package org.jivesoftware.xiff.data
Section 186
//ChangePasswordSuccessEvent (org.jivesoftware.xiff.events.ChangePasswordSuccessEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
public class ChangePasswordSuccessEvent extends Event {
public static var PASSWORD_SUCCESS:String = "changePasswordSuccess";
public function ChangePasswordSuccessEvent(){
super(_slot1.PASSWORD_SUCCESS, false, false);
}
}
}//package org.jivesoftware.xiff.events
Section 187
//ConnectionSuccessEvent (org.jivesoftware.xiff.events.ConnectionSuccessEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
public class ConnectionSuccessEvent extends Event {
public static var CONNECT_SUCCESS:String = "connection";
public function ConnectionSuccessEvent(){
super(_slot1.CONNECT_SUCCESS, false, false);
}
}
}//package org.jivesoftware.xiff.events
Section 188
//DisconnectionEvent (org.jivesoftware.xiff.events.DisconnectionEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
public class DisconnectionEvent extends Event {
public static var DISCONNECT:String = "disconnection";
public function DisconnectionEvent(){
super(_slot1.DISCONNECT, false, false);
}
}
}//package org.jivesoftware.xiff.events
Section 189
//IncomingDataEvent (org.jivesoftware.xiff.events.IncomingDataEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
import flash.xml.*;
public class IncomingDataEvent extends Event {
private var _data:XMLDocument;
public static var INCOMING_DATA:String = "incomingData";
public function IncomingDataEvent(){
super(IncomingDataEvent.INCOMING_DATA, false, false);
}
public function get data():XMLDocument{
return (_data);
}
public function set data(x:XMLDocument):void{
_data = x;
}
}
}//package org.jivesoftware.xiff.events
Section 190
//IQEvent (org.jivesoftware.xiff.events.IQEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
import org.jivesoftware.xiff.data.*;
public class IQEvent extends Event {
private var _iq:IQ;
private var _data:IExtension;
public function IQEvent(type:String){
super(type, false, false);
}
public function set iq(i:IQ):void{
_iq = i;
}
public function set data(x:IExtension):void{
_data = x;
}
public function get iq():IQ{
return (_iq);
}
public function get data():IExtension{
return (_data);
}
}
}//package org.jivesoftware.xiff.events
Section 191
//LoginEvent (org.jivesoftware.xiff.events.LoginEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
public class LoginEvent extends Event {
public static var LOGIN:String = "login";
public function LoginEvent(){
super(_slot1.LOGIN, false, false);
}
}
}//package org.jivesoftware.xiff.events
Section 192
//MessageEvent (org.jivesoftware.xiff.events.MessageEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
import org.jivesoftware.xiff.data.*;
public class MessageEvent extends Event {
private var _data:Message;
public static var MESSAGE:String = "message";
public function MessageEvent(){
super(MessageEvent.MESSAGE, false, false);
}
public function get data():Message{
return (_data);
}
public function set data(m:Message):void{
_data = m;
}
}
}//package org.jivesoftware.xiff.events
Section 193
//OutgoingDataEvent (org.jivesoftware.xiff.events.OutgoingDataEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
public class OutgoingDataEvent extends Event {
private var _data;
public static var OUTGOING_DATA:String = "outgoingData";
public function OutgoingDataEvent(){
super(_slot1.OUTGOING_DATA, false, false);
}
public function get data(){
return (_data);
}
public function set data(d):void{
_data = d;
}
}
}//package org.jivesoftware.xiff.events
Section 194
//PresenceEvent (org.jivesoftware.xiff.events.PresenceEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
public class PresenceEvent extends Event {
private var _data:Array;
public static var PRESENCE:String = "presence";
public function PresenceEvent(){
super(_slot1.PRESENCE, bubbles, cancelable);
}
public function get data():Array{
return (_data);
}
public function set data(p:Array):void{
_data = p;
}
}
}//package org.jivesoftware.xiff.events
Section 195
//RegistrationFieldsEvent (org.jivesoftware.xiff.events.RegistrationFieldsEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
import org.jivesoftware.xiff.data.register.*;
public class RegistrationFieldsEvent extends Event {
private var _fields:Array;
private var _data:RegisterExtension;
public static var REG_FIELDS:String = "registrationFields";
public function RegistrationFieldsEvent(){
super(RegistrationFieldsEvent.REG_FIELDS, false, false);
}
public function get fields():Array{
return (_fields);
}
public function set fields(a:Array):void{
_fields = a;
}
public function set data(r:RegisterExtension):void{
_data = r;
}
public function get data():RegisterExtension{
return (_data);
}
}
}//package org.jivesoftware.xiff.events
Section 196
//RegistrationSuccessEvent (org.jivesoftware.xiff.events.RegistrationSuccessEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
public class RegistrationSuccessEvent extends Event {
public static var REGISTRATION_SUCCESS:String = "registrationSuccess";
public function RegistrationSuccessEvent(){
super(_slot1.REGISTRATION_SUCCESS, false, false);
}
}
}//package org.jivesoftware.xiff.events
Section 197
//RoomEvent (org.jivesoftware.xiff.events.RoomEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
import org.jivesoftware.xiff.data.*;
public class RoomEvent extends Event {
private var _message:Message;
private var _data;
private var _nickname:String;
private var _errorCode:Number;
private var _from:String;
private var _errorCondition:String;
private var _errorType:String;
private var _reason:String;
private var _subject:String;
private var _errorMessage:String;
public static const AFFILIATIONS:String = "affiliations";
public static const PASSWORD_ERROR:String = "passwordError";
public static const GROUP_MESSAGE:String = "groupMessage";
public static const SUBJECT_CHANGE:String = "subjectChange";
public static const PRIVATE_MESSAGE:String = "privateMessage";
public static const ROOM_JOIN:String = "roomJoin";
public static const USER_BANNED:String = "userBanned";
public static const MAX_USERS_ERROR:String = "maxUsersError";
public static const ADMIN_ERROR:String = "adminError";
public static const USER_KICKED:String = "userKicked";
public static const USER_JOIN:String = "userJoin";
public static const BANNED_ERROR:String = "bannedError";
public static const USER_DEPARTURE:String = "userDeparture";
public static const REGISTRATION_REQ_ERROR:String = "registrationReqError";
public static const USER_CHANGED:String = "userChanged";
public static const NICK_CONFLICT:String = "nickConflict";
public static const ROOM_LEAVE:String = "roomLeave";
public static const CONFIGURE_ROOM:String = "configureForm";
public static const DECLINED:String = "declined";
public static const LOCKED_ERROR:String = "lockedError";
public function RoomEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false){
super(type, bubbles, cancelable);
}
public function get errorCondition():String{
return (_errorCondition);
}
public function set errorType(s:String):void{
_errorType = s;
}
public function set errorMessage(s:String):void{
_errorMessage = s;
}
public function get message():Message{
return (_message);
}
public function get reason():String{
return (_reason);
}
public function get from():String{
return (_from);
}
public function set message(s:Message):void{
_message = s;
}
public function set reason(s:String):void{
_reason = s;
}
public function set data(s):void{
_data = s;
}
public function set from(s:String):void{
_from = s;
}
public function get errorCode():Number{
return (_errorCode);
}
public function set subject(s:String):void{
_subject = s;
}
public function get errorType():String{
return (_errorType);
}
public function set errorCondition(s:String):void{
_errorCondition = s;
}
public function set nickname(s:String):void{
_nickname = s;
}
public function get errorMessage():String{
return (_errorMessage);
}
public function get data(){
return (_data);
}
public function get subject():String{
return (_subject);
}
public function get nickname():String{
return (_nickname);
}
public function set errorCode(s:Number):void{
_errorCode = s;
}
}
}//package org.jivesoftware.xiff.events
Section 198
//XIFFErrorEvent (org.jivesoftware.xiff.events.XIFFErrorEvent)
package org.jivesoftware.xiff.events {
import flash.events.*;
public class XIFFErrorEvent extends Event {
private var _errorType:String;
private var _errorMessage:String;
private var _errorCondition:String;
private var _errorCode:Number;
public static var XIFF_ERROR:String = "error";
public function XIFFErrorEvent(){
super(_slot1.XIFF_ERROR, false, false);
}
public function get errorType():String{
return (_errorType);
}
public function set errorCondition(s:String):void{
_errorCondition = s;
}
public function set errorCode(n:Number):void{
_errorCode = n;
}
public function set errorType(s:String):void{
_errorType = s;
}
public function get errorCondition():String{
return (_errorCondition);
}
public function get errorCode():Number{
return (_errorCode);
}
public function set errorMessage(s:String):void{
_errorMessage = s;
}
public function get errorMessage():String{
return (_errorMessage);
}
}
}//package org.jivesoftware.xiff.events
Section 199
//SerializationException (org.jivesoftware.xiff.exception.SerializationException)
package org.jivesoftware.xiff.exception {
public class SerializationException extends Error {
private static var MSG:String = "Could not properly serialize/deserialize stanza.";
public function SerializationException(){
super(MSG);
}
}
}//package org.jivesoftware.xiff.exception
Section 200
//SocketConn (org.jivesoftware.xiff.util.SocketConn)
package org.jivesoftware.xiff.util {
import flash.events.*;
import com.kongregate.as3.common.util.*;
import flash.utils.*;
import flash.net.*;
import com.wirelust.as3zlib.*;
public class SocketConn extends Socket {
private var compressed:Boolean;
private var totalIncomingUncompressedBytes:uint;// = 0
private var totalIncomingBytes:uint;// = 0
private var deflateStream:ZStream;
private var totalOutgoingUncompressedBytes:uint;// = 0
private var remainingBytes:ByteArray;
private var flashClient:Boolean;// = false
private var inflateStream:ZStream;
private var inputBuffer:ByteArray;
private var totalOutgoingBytes:uint;// = 0
public function SocketConn(host:String=null, port:int=0){
inflateStream = new ZStream();
deflateStream = new ZStream();
remainingBytes = new ByteArray();
inputBuffer = new ByteArray();
super(host, port);
addEventListener(ProgressEvent.SOCKET_DATA, onRead);
}
public function sendString(output:String):void{
if (compressed){
sendCompressedString(output);
} else {
writeUTFBytes(output);
};
flush();
}
public function set compress(_compress:Boolean):void{
compressed = _compress;
}
public function get incomingCompressionRatio():int{
if (compressed){
return (int(((1 - (Number(totalIncomingBytes) / Number(totalIncomingUncompressedBytes))) * 100)));
};
return (0);
}
private function parseNormalInputBuffer():void{
inputBuffer.position = 0;
var s:String = inputBuffer.readUTFBytes(inputBuffer.bytesAvailable);
onSockRead(s);
}
public function get outgoingCompressionRatio():int{
if (compressed){
return (int(((1 - (Number(totalOutgoingBytes) / Number(totalOutgoingUncompressedBytes))) * 100)));
};
return (0);
}
private function readCompressedData():void{
var compressed:ByteArray = new ByteArray();
readBytes(compressed, compressed.position, bytesAvailable);
var uncompressed:ByteArray = inflate(compressed);
inputBuffer.writeBytes(uncompressed);
totalIncomingBytes = (totalIncomingBytes + compressed.length);
totalIncomingUncompressedBytes = (totalIncomingUncompressedBytes + uncompressed.length);
}
private function sendCompressedString(output:String):void{
var uncompressed:ByteArray = new ByteArray();
uncompressed.writeUTFBytes(output);
var compressed:ByteArray = deflate(uncompressed);
writeBytes(compressed, 0, compressed.length);
totalOutgoingBytes = (totalOutgoingBytes + compressed.length);
totalOutgoingUncompressedBytes = (totalOutgoingUncompressedBytes + uncompressed.length);
}
private function onRead(event:ProgressEvent):void{
var incoming:ByteArray;
if (compressed){
readCompressedData();
} else {
if (flashClient){
incoming = new ByteArray();
readBytes(incoming);
inputBuffer.writeBytes(incoming);
} else {
onSockRead(readUTFBytes(bytesAvailable));
return;
};
};
parseInputBuffer();
}
private function resetCompression():void{
if (deflateStream){
deflateStream.deflateEnd();
};
deflateStream = new ZStream();
deflateStream.deflateInitWithIntInt(JZlib.Z_BEST_COMPRESSION, 12);
if (inflateStream){
inflateStream.inflateEnd();
};
inflateStream = new ZStream();
inflateStream.inflateInit();
}
public function inflate(inBuffer:ByteArray):ByteArray{
var outBuffer:ByteArray;
outBuffer = new ByteArray();
inflateStream.next_in = inBuffer;
inflateStream.next_in_index = 0;
inflateStream.avail_in = inBuffer.length;
inflateStream.next_out = outBuffer;
inflateStream.next_out_index = 0;
inflateStream.avail_out = (inBuffer.length * 10);
var retval:int;
do {
retval = inflateStream.inflate(JZlib.Z_SYNC_FLUSH);
switch (retval){
case JZlib.Z_OK:
break;
case JZlib.Z_BUF_ERROR:
inflateStream.avail_out = (inBuffer.length * 10);
break;
default:
Log.error(("Error during decompression: " + retval));
return (null);
};
} while (inflateStream.avail_in > 0);
outBuffer.position = 0;
return (outBuffer);
}
public function set flash(_flash:Boolean):void{
flashClient = _flash;
}
private function onSockRead(s:String):void{
var e:SocketDataEvent = new SocketDataEvent();
e.data = s;
dispatchEvent(e);
}
private function deflate(inBuffer:ByteArray):ByteArray{
var outLen:int = (Math.round((inBuffer.length * 1.135)) + 13);
var outBytes:ByteArray = new ByteArray();
deflateStream.next_in = inBuffer;
deflateStream.next_in_index = 0;
deflateStream.avail_in = inBuffer.length;
deflateStream.next_out = outBytes;
deflateStream.next_out_index = 0;
deflateStream.avail_out = outLen;
var retval:int = deflateStream.deflate(JZlib.Z_SYNC_FLUSH);
if (retval != JZlib.Z_OK){
outBytes = null;
};
return (outBytes);
}
private function parseFlashInputBuffer():void{
var b:int;
inputBuffer.position = 0;
var currentMessage:ByteArray = new ByteArray();
var numBytes:int = inputBuffer.bytesAvailable;
var xml:String = "";
var i:int;
while (i < numBytes) {
b = inputBuffer.readByte();
if ((((b == 0)) && ((currentMessage.length > 0)))){
currentMessage.position = 0;
xml = (xml + currentMessage.readUTFBytes(currentMessage.bytesAvailable));
currentMessage = new ByteArray();
} else {
if (b != 0){
currentMessage.writeByte(b);
};
};
i++;
};
inputBuffer = currentMessage;
if (xml.length > 0){
onSockRead(xml);
};
}
override public function connect(host:String, port:int):void{
inputBuffer = new ByteArray();
resetCompression();
super.connect(host, port);
}
private function parseInputBuffer():void{
if (flashClient){
parseFlashInputBuffer();
} else {
parseNormalInputBuffer();
};
}
}
}//package org.jivesoftware.xiff.util
Section 201
//SocketDataEvent (org.jivesoftware.xiff.util.SocketDataEvent)
package org.jivesoftware.xiff.util {
import flash.events.*;
public class SocketDataEvent extends Event {
private var _data:String;
public static var SOCKET_DATA_RECEIVED:String = "socketDataReceived";
public function SocketDataEvent(){
super(SOCKET_DATA_RECEIVED, false, false);
}
public function get data():String{
return (_data);
}
public function set data(s:String):void{
_data = s;
}
}
}//package org.jivesoftware.xiff.util
Section 202
//_CompiledResourceBundleInfo (_CompiledResourceBundleInfo)
package {
public class _CompiledResourceBundleInfo {
public static function get compiledLocales():Array{
return (["en_US"]);
}
public static function get compiledResourceBundleNames():Array{
return (["collections"]);
}
}
}//package
Section 203
//en_US$collections_properties (en_US$collections_properties)
package {
import mx.resources.*;
public class en_US$collections_properties extends ResourceBundle {
public function en_US$collections_properties(){
super("en_US", "collections");
}
override protected function getContent():Object{
var _local1:Object = {findCondition:"Find criteria must contain all sort fields leading up to '{0}'.", noComparatorSortField:"Cannot determine comparator for SortField with name '{0}'.", outOfBounds:"Index '{0}' specified is out of bounds.", nonUnique:"Non-unique values in items.", incorrectAddition:"Attempt to add an item already in the view.", findRestriction:"Find criteria must contain at least one sort field value.", invalidType:"Incorrect type. Must be of type XML or a XMLList that contains one XML object. ", unknownMode:"Unknown find mode.", invalidIndex:"Invalid index: '{0}'.", invalidRemove:"Cannot remove when current is beforeFirst or afterLast.", unknownProperty:"Unknown Property: '{0}'.", invalidInsert:"Cannot insert when current is beforeFirst.", itemNotFound:"Cannot find when view is not sorted.", bookmarkInvalid:"Bookmark no longer valid.", noComparator:"Cannot determine comparator for '{0}'.", invalidCursor:"Cursor no longer valid.", noItems:"No items to search.", bookmarkNotFound:"Bookmark is not from this view."};
return (_local1);
}
}
}//package