UNPKG

xlsx-style

Version:

Excel (XLSB/XLSX/XLSM/XLS/XML) and ODS spreadsheet parser and writer (extended to enable read/write of cell formats with xlsx files)

1,380 lines (1,308 loc) 426 kB
/* xlsx.js (C) 2013-2015 SheetJS -- http://sheetjs.com */ /* vim: set ts=2: */ /*jshint -W041 */ /*jshint funcscope:true, eqnull:true */ var XLSX = {}; (function make_xlsx(XLSX){ XLSX.version = '0.8.11'; var current_codepage = 1200, current_cptable; if(typeof module !== "undefined" && typeof require !== 'undefined') { if(typeof cptable === 'undefined') cptable = require('./dist/cpexcel'); current_cptable = cptable[current_codepage]; } function reset_cp() { set_cp(1200); } var set_cp = function(cp) { current_codepage = cp; }; function char_codes(data) { var o = []; for(var i = 0, len = data.length; i < len; ++i) o[i] = data.charCodeAt(i); return o; } var debom_xml = function(data) { return data; }; var _getchar = function _gc1(x) { return String.fromCharCode(x); }; if(typeof cptable !== 'undefined') { set_cp = function(cp) { current_codepage = cp; current_cptable = cptable[cp]; }; debom_xml = function(data) { if(data.charCodeAt(0) === 0xFF && data.charCodeAt(1) === 0xFE) { return cptable.utils.decode(1200, char_codes(data.substr(2))); } return data; }; _getchar = function _gc2(x) { if(current_codepage === 1200) return String.fromCharCode(x); return cptable.utils.decode(current_codepage, [x&255,x>>8])[0]; }; } var Base64 = (function make_b64(){ var map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; return { encode: function(input, utf8) { var o = ""; var c1, c2, c3, e1, e2, e3, e4; for(var i = 0; i < input.length; ) { c1 = input.charCodeAt(i++); c2 = input.charCodeAt(i++); c3 = input.charCodeAt(i++); e1 = c1 >> 2; e2 = (c1 & 3) << 4 | c2 >> 4; e3 = (c2 & 15) << 2 | c3 >> 6; e4 = c3 & 63; if (isNaN(c2)) { e3 = e4 = 64; } else if (isNaN(c3)) { e4 = 64; } o += map.charAt(e1) + map.charAt(e2) + map.charAt(e3) + map.charAt(e4); } return o; }, decode: function b64_decode(input, utf8) { var o = ""; var c1, c2, c3; var e1, e2, e3, e4; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); for(var i = 0; i < input.length;) { e1 = map.indexOf(input.charAt(i++)); e2 = map.indexOf(input.charAt(i++)); e3 = map.indexOf(input.charAt(i++)); e4 = map.indexOf(input.charAt(i++)); c1 = e1 << 2 | e2 >> 4; c2 = (e2 & 15) << 4 | e3 >> 2; c3 = (e3 & 3) << 6 | e4; o += String.fromCharCode(c1); if (e3 != 64) { o += String.fromCharCode(c2); } if (e4 != 64) { o += String.fromCharCode(c3); } } return o; } }; })(); var has_buf = (typeof Buffer !== 'undefined'); function new_raw_buf(len) { /* jshint -W056 */ return new (has_buf ? Buffer : Array)(len); /* jshint +W056 */ } function s2a(s) { if(has_buf) return new Buffer(s, "binary"); return s.split("").map(function(x){ return x.charCodeAt(0) & 0xff; }); } var bconcat = function(bufs) { return [].concat.apply([], bufs); }; var chr0 = /\u0000/g, chr1 = /[\u0001-\u0006]/; /* ssf.js (C) 2013-2014 SheetJS -- http://sheetjs.com */ /*jshint -W041 */ var SSF = {}; var make_ssf = function make_ssf(SSF){ SSF.version = '0.8.1'; function _strrev(x) { var o = "", i = x.length-1; while(i>=0) o += x.charAt(i--); return o; } function fill(c,l) { var o = ""; while(o.length < l) o+=c; return o; } function pad0(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;} function pad_(v,d){var t=""+v;return t.length>=d?t:fill(' ',d-t.length)+t;} function rpad_(v,d){var t=""+v; return t.length>=d?t:t+fill(' ',d-t.length);} function pad0r1(v,d){var t=""+Math.round(v); return t.length>=d?t:fill('0',d-t.length)+t;} function pad0r2(v,d){var t=""+v; return t.length>=d?t:fill('0',d-t.length)+t;} var p2_32 = Math.pow(2,32); function pad0r(v,d){if(v>p2_32||v<-p2_32) return pad0r1(v,d); var i = Math.round(v); return pad0r2(i,d); } function isgeneral(s, i) { return s.length >= 7 + i && (s.charCodeAt(i)|32) === 103 && (s.charCodeAt(i+1)|32) === 101 && (s.charCodeAt(i+2)|32) === 110 && (s.charCodeAt(i+3)|32) === 101 && (s.charCodeAt(i+4)|32) === 114 && (s.charCodeAt(i+5)|32) === 97 && (s.charCodeAt(i+6)|32) === 108; } /* Options */ var opts_fmt = [ ["date1904", 0], ["output", ""], ["WTF", false] ]; function fixopts(o){ for(var y = 0; y != opts_fmt.length; ++y) if(o[opts_fmt[y][0]]===undefined) o[opts_fmt[y][0]]=opts_fmt[y][1]; } SSF.opts = opts_fmt; var table_fmt = { 0: 'General', 1: '0', 2: '0.00', 3: '#,##0', 4: '#,##0.00', 9: '0%', 10: '0.00%', 11: '0.00E+00', 12: '# ?/?', 13: '# ??/??', 14: 'm/d/yy', 15: 'd-mmm-yy', 16: 'd-mmm', 17: 'mmm-yy', 18: 'h:mm AM/PM', 19: 'h:mm:ss AM/PM', 20: 'h:mm', 21: 'h:mm:ss', 22: 'm/d/yy h:mm', 37: '#,##0 ;(#,##0)', 38: '#,##0 ;[Red](#,##0)', 39: '#,##0.00;(#,##0.00)', 40: '#,##0.00;[Red](#,##0.00)', 45: 'mm:ss', 46: '[h]:mm:ss', 47: 'mmss.0', 48: '##0.0E+0', 49: '@', 56: '"上午/下午 "hh"時"mm"分"ss"秒 "', 65535: 'General' }; var days = [ ['Sun', 'Sunday'], ['Mon', 'Monday'], ['Tue', 'Tuesday'], ['Wed', 'Wednesday'], ['Thu', 'Thursday'], ['Fri', 'Friday'], ['Sat', 'Saturday'] ]; var months = [ ['J', 'Jan', 'January'], ['F', 'Feb', 'February'], ['M', 'Mar', 'March'], ['A', 'Apr', 'April'], ['M', 'May', 'May'], ['J', 'Jun', 'June'], ['J', 'Jul', 'July'], ['A', 'Aug', 'August'], ['S', 'Sep', 'September'], ['O', 'Oct', 'October'], ['N', 'Nov', 'November'], ['D', 'Dec', 'December'] ]; function frac(x, D, mixed) { var sgn = x < 0 ? -1 : 1; var B = x * sgn; var P_2 = 0, P_1 = 1, P = 0; var Q_2 = 1, Q_1 = 0, Q = 0; var A = Math.floor(B); while(Q_1 < D) { A = Math.floor(B); P = A * P_1 + P_2; Q = A * Q_1 + Q_2; if((B - A) < 0.0000000005) break; B = 1 / (B - A); P_2 = P_1; P_1 = P; Q_2 = Q_1; Q_1 = Q; } if(Q > D) { Q = Q_1; P = P_1; } if(Q > D) { Q = Q_2; P = P_2; } if(!mixed) return [0, sgn * P, Q]; if(Q===0) throw "Unexpected state: "+P+" "+P_1+" "+P_2+" "+Q+" "+Q_1+" "+Q_2; var q = Math.floor(sgn * P/Q); return [q, sgn*P - q*Q, Q]; } function general_fmt_int(v, opts) { return ""+v; } SSF._general_int = general_fmt_int; var general_fmt_num = (function make_general_fmt_num() { var gnr1 = /\.(\d*[1-9])0+$/, gnr2 = /\.0*$/, gnr4 = /\.(\d*[1-9])0+/, gnr5 = /\.0*[Ee]/, gnr6 = /(E[+-])(\d)$/; function gfn2(v) { var w = (v<0?12:11); var o = gfn5(v.toFixed(12)); if(o.length <= w) return o; o = v.toPrecision(10); if(o.length <= w) return o; return v.toExponential(5); } function gfn3(v) { var o = v.toFixed(11).replace(gnr1,".$1"); if(o.length > (v<0?12:11)) o = v.toPrecision(6); return o; } function gfn4(o) { for(var i = 0; i != o.length; ++i) if((o.charCodeAt(i) | 0x20) === 101) return o.replace(gnr4,".$1").replace(gnr5,"E").replace("e","E").replace(gnr6,"$10$2"); return o; } function gfn5(o) { //for(var i = 0; i != o.length; ++i) if(o.charCodeAt(i) === 46) return o.replace(gnr2,"").replace(gnr1,".$1"); //return o; return o.indexOf(".") > -1 ? o.replace(gnr2,"").replace(gnr1,".$1") : o; } return function general_fmt_num(v, opts) { var V = Math.floor(Math.log(Math.abs(v))*Math.LOG10E), o; if(V >= -4 && V <= -1) o = v.toPrecision(10+V); else if(Math.abs(V) <= 9) o = gfn2(v); else if(V === 10) o = v.toFixed(10).substr(0,12); else o = gfn3(v); return gfn5(gfn4(o)); };})(); SSF._general_num = general_fmt_num; function general_fmt(v, opts) { switch(typeof v) { case 'string': return v; case 'boolean': return v ? "TRUE" : "FALSE"; case 'number': return (v|0) === v ? general_fmt_int(v, opts) : general_fmt_num(v, opts); } throw new Error("unsupported value in General format: " + v); } SSF._general = general_fmt; function fix_hijri(date, o) { return 0; } function parse_date_code(v,opts,b2) { if(v > 2958465 || v < 0) return null; var date = (v|0), time = Math.floor(86400 * (v - date)), dow=0; var dout=[]; var out={D:date, T:time, u:86400*(v-date)-time,y:0,m:0,d:0,H:0,M:0,S:0,q:0}; if(Math.abs(out.u) < 1e-6) out.u = 0; fixopts(opts != null ? opts : (opts=[])); if(opts.date1904) date += 1462; if(out.u > 0.999) { out.u = 0; if(++time == 86400) { time = 0; ++date; } } if(date === 60) {dout = b2 ? [1317,10,29] : [1900,2,29]; dow=3;} else if(date === 0) {dout = b2 ? [1317,8,29] : [1900,1,0]; dow=6;} else { if(date > 60) --date; /* 1 = Jan 1 1900 */ var d = new Date(1900,0,1); d.setDate(d.getDate() + date - 1); dout = [d.getFullYear(), d.getMonth()+1,d.getDate()]; dow = d.getDay(); if(date < 60) dow = (dow + 6) % 7; if(b2) dow = fix_hijri(d, dout); } out.y = dout[0]; out.m = dout[1]; out.d = dout[2]; out.S = time % 60; time = Math.floor(time / 60); out.M = time % 60; time = Math.floor(time / 60); out.H = time; out.q = dow; return out; } SSF.parse_date_code = parse_date_code; /*jshint -W086 */ function write_date(type, fmt, val, ss0) { var o="", ss=0, tt=0, y = val.y, out, outl = 0; switch(type) { case 98: /* 'b' buddhist year */ y = val.y + 543; /* falls through */ case 121: /* 'y' year */ switch(fmt.length) { case 1: case 2: out = y % 100; outl = 2; break; default: out = y % 10000; outl = 4; break; } break; case 109: /* 'm' month */ switch(fmt.length) { case 1: case 2: out = val.m; outl = fmt.length; break; case 3: return months[val.m-1][1]; case 5: return months[val.m-1][0]; default: return months[val.m-1][2]; } break; case 100: /* 'd' day */ switch(fmt.length) { case 1: case 2: out = val.d; outl = fmt.length; break; case 3: return days[val.q][0]; default: return days[val.q][1]; } break; case 104: /* 'h' 12-hour */ switch(fmt.length) { case 1: case 2: out = 1+(val.H+11)%12; outl = fmt.length; break; default: throw 'bad hour format: ' + fmt; } break; case 72: /* 'H' 24-hour */ switch(fmt.length) { case 1: case 2: out = val.H; outl = fmt.length; break; default: throw 'bad hour format: ' + fmt; } break; case 77: /* 'M' minutes */ switch(fmt.length) { case 1: case 2: out = val.M; outl = fmt.length; break; default: throw 'bad minute format: ' + fmt; } break; case 115: /* 's' seconds */ if(val.u === 0) switch(fmt) { case 's': case 'ss': return pad0(val.S, fmt.length); case '.0': case '.00': case '.000': } switch(fmt) { case 's': case 'ss': case '.0': case '.00': case '.000': if(ss0 >= 2) tt = ss0 === 3 ? 1000 : 100; else tt = ss0 === 1 ? 10 : 1; ss = Math.round((tt)*(val.S + val.u)); if(ss >= 60*tt) ss = 0; if(fmt === 's') return ss === 0 ? "0" : ""+ss/tt; o = pad0(ss,2 + ss0); if(fmt === 'ss') return o.substr(0,2); return "." + o.substr(2,fmt.length-1); default: throw 'bad second format: ' + fmt; } case 90: /* 'Z' absolute time */ switch(fmt) { case '[h]': case '[hh]': out = val.D*24+val.H; break; case '[m]': case '[mm]': out = (val.D*24+val.H)*60+val.M; break; case '[s]': case '[ss]': out = ((val.D*24+val.H)*60+val.M)*60+Math.round(val.S+val.u); break; default: throw 'bad abstime format: ' + fmt; } outl = fmt.length === 3 ? 1 : 2; break; case 101: /* 'e' era */ out = y; outl = 1; } if(outl > 0) return pad0(out, outl); else return ""; } /*jshint +W086 */ function commaify(s) { if(s.length <= 3) return s; var j = (s.length % 3), o = s.substr(0,j); for(; j!=s.length; j+=3) o+=(o.length > 0 ? "," : "") + s.substr(j,3); return o; } var write_num = (function make_write_num(){ var pct1 = /%/g; function write_num_pct(type, fmt, val){ var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length; return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul); } function write_num_cm(type, fmt, val){ var idx = fmt.length - 1; while(fmt.charCodeAt(idx-1) === 44) --idx; return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx))); } function write_num_exp(fmt, val){ var o; var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1; if(fmt.match(/^#+0.0E\+0$/)) { var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E'); var ee = Math.floor(Math.log(Math.abs(val))*Math.LOG10E)%period; if(ee < 0) ee += period; o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period); if(o.indexOf("e") === -1) { var fakee = Math.floor(Math.log(Math.abs(val))*Math.LOG10E); if(o.indexOf(".") === -1) o = o[0] + "." + o.substr(1) + "E+" + (fakee - o.length+ee); else o += "E+" + (fakee - ee); while(o.substr(0,2) === "0.") { o = o[0] + o.substr(2,period) + "." + o.substr(2+period); o = o.replace(/^0+([1-9])/,"$1").replace(/^0+\./,"0."); } o = o.replace(/\+-/,"-"); } o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; }); } else o = val.toExponential(idx); if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o[o.length-1]; if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e"); return o.replace("e","E"); } var frac1 = /# (\?+)( ?)\/( ?)(\d+)/; function write_num_f1(r, aval, sign) { var den = parseInt(r[4]), rr = Math.round(aval * den), base = Math.floor(rr/den); var myn = (rr - base*den), myd = den; return sign + (base === 0 ? "" : ""+base) + " " + (myn === 0 ? fill(" ", r[1].length + 1 + r[4].length) : pad_(myn,r[1].length) + r[2] + "/" + r[3] + pad0(myd,r[4].length)); } function write_num_f2(r, aval, sign) { return sign + (aval === 0 ? "" : ""+aval) + fill(" ", r[1].length + 2 + r[4].length); } var dec1 = /^#*0*\.(0+)/; var closeparen = /\).*[0#]/; var phone = /\(###\) ###\\?-####/; function hashq(str) { var o = "", cc; for(var i = 0; i != str.length; ++i) switch((cc=str.charCodeAt(i))) { case 35: break; case 63: o+= " "; break; case 48: o+= "0"; break; default: o+= String.fromCharCode(cc); } return o; } function rnd(val, d) { var dd = Math.pow(10,d); return ""+(Math.round(val * dd)/dd); } function dec(val, d) { return Math.round((val-Math.floor(val))*Math.pow(10,d)); } function flr(val) { if(val < 2147483647 && val > -2147483648) return ""+(val >= 0 ? (val|0) : (val-1|0)); return ""+Math.floor(val); } function write_num_flt(type, fmt, val) { if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) { var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,""); if(val >= 0) return write_num_flt('n', ffmt, val); return '(' + write_num_flt('n', ffmt, -val) + ')'; } if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val); if(fmt.indexOf('%') !== -1) return write_num_pct(type, fmt, val); if(fmt.indexOf('E') !== -1) return write_num_exp(fmt, val); if(fmt.charCodeAt(0) === 36) return "$"+write_num_flt(type,fmt.substr(fmt[1]==' '?2:1),val); var o, oo; var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : ""; if(fmt.match(/^00+$/)) return sign + pad0r(aval,fmt.length); if(fmt.match(/^[#?]+$/)) { o = pad0r(val,0); if(o === "0") o = ""; return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o; } if((r = fmt.match(frac1)) !== null) return write_num_f1(r, aval, sign); if(fmt.match(/^#+0+$/) !== null) return sign + pad0r(aval,fmt.length - fmt.indexOf("0")); if((r = fmt.match(dec1)) !== null) { o = rnd(val, r[1].length).replace(/^([^\.]+)$/,"$1."+r[1]).replace(/\.$/,"."+r[1]).replace(/\.(\d*)$/,function($$, $1) { return "." + $1 + fill("0", r[1].length-$1.length); }); return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,"."); } fmt = fmt.replace(/^#+([0.])/, "$1"); if((r = fmt.match(/^(0*)\.(#*)$/)) !== null) { return sign + rnd(aval, r[2].length).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":"."); } if((r = fmt.match(/^#,##0(\.?)$/)) !== null) return sign + commaify(pad0r(aval,0)); if((r = fmt.match(/^#,##0\.([#0]*0)$/)) !== null) { return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(""+(Math.floor(val))) + "." + pad0(dec(val, r[1].length),r[1].length); } if((r = fmt.match(/^#,#*,#0/)) !== null) return write_num_flt(type,fmt.replace(/^#,#*,/,""),val); if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) !== null) { o = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g,""), val)); ri = 0; return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o[ri++]:x==='0'?'0':"";})); } if(fmt.match(phone) !== null) { o = write_num_flt(type, "##########", val); return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6); } var oa = ""; if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) !== null) { ri = Math.min(r[4].length,7); ff = frac(aval, Math.pow(10,ri)-1, false); o = "" + sign; oa = write_num("n", r[1], ff[1]); if(oa[oa.length-1] == " ") oa = oa.substr(0,oa.length-1) + "0"; o += oa + r[2] + "/" + r[3]; oa = rpad_(ff[2],ri); if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa; o += oa; return o; } if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) !== null) { ri = Math.min(Math.max(r[1].length, r[4].length),7); ff = frac(aval, Math.pow(10,ri)-1, true); return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill(" ", 2*ri+1 + r[2].length + r[3].length)); } if((r = fmt.match(/^[#0?]+$/)) !== null) { o = pad0r(val, 0); if(fmt.length <= o.length) return o; return hashq(fmt.substr(0,fmt.length-o.length)) + o; } if((r = fmt.match(/^([#0?]+)\.([#0]+)$/)) !== null) { o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1"); ri = o.indexOf("."); var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres; return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres)); } if((r = fmt.match(/^00,000\.([#0]*0)$/)) !== null) { ri = dec(val, r[1].length); return val < 0 ? "-" + write_num_flt(type, fmt, -val) : commaify(flr(val)).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(ri,r[1].length); } switch(fmt) { case "#,###": var x = commaify(pad0r(aval,0)); return x !== "0" ? sign + x : ""; default: } throw new Error("unsupported format |" + fmt + "|"); } function write_num_cm2(type, fmt, val){ var idx = fmt.length - 1; while(fmt.charCodeAt(idx-1) === 44) --idx; return write_num(type, fmt.substr(0,idx), val / Math.pow(10,3*(fmt.length-idx))); } function write_num_pct2(type, fmt, val){ var sfmt = fmt.replace(pct1,""), mul = fmt.length - sfmt.length; return write_num(type, sfmt, val * Math.pow(10,2*mul)) + fill("%",mul); } function write_num_exp2(fmt, val){ var o; var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1; if(fmt.match(/^#+0.0E\+0$/)) { var period = fmt.indexOf("."); if(period === -1) period=fmt.indexOf('E'); var ee = Math.floor(Math.log(Math.abs(val))*Math.LOG10E)%period; if(ee < 0) ee += period; o = (val/Math.pow(10,ee)).toPrecision(idx+1+(period+ee)%period); if(!o.match(/[Ee]/)) { var fakee = Math.floor(Math.log(Math.abs(val))*Math.LOG10E); if(o.indexOf(".") === -1) o = o[0] + "." + o.substr(1) + "E+" + (fakee - o.length+ee); else o += "E+" + (fakee - ee); o = o.replace(/\+-/,"-"); } o = o.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/,function($$,$1,$2,$3) { return $1 + $2 + $3.substr(0,(period+ee)%period) + "." + $3.substr(ee) + "E"; }); } else o = val.toExponential(idx); if(fmt.match(/E\+00$/) && o.match(/e[+-]\d$/)) o = o.substr(0,o.length-1) + "0" + o[o.length-1]; if(fmt.match(/E\-/) && o.match(/e\+/)) o = o.replace(/e\+/,"e"); return o.replace("e","E"); } function write_num_int(type, fmt, val) { if(type.charCodeAt(0) === 40 && !fmt.match(closeparen)) { var ffmt = fmt.replace(/\( */,"").replace(/ \)/,"").replace(/\)/,""); if(val >= 0) return write_num_int('n', ffmt, val); return '(' + write_num_int('n', ffmt, -val) + ')'; } if(fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val); if(fmt.indexOf('%') !== -1) return write_num_pct2(type, fmt, val); if(fmt.indexOf('E') !== -1) return write_num_exp2(fmt, val); if(fmt.charCodeAt(0) === 36) return "$"+write_num_int(type,fmt.substr(fmt[1]==' '?2:1),val); var o; var r, ri, ff, aval = Math.abs(val), sign = val < 0 ? "-" : ""; if(fmt.match(/^00+$/)) return sign + pad0(aval,fmt.length); if(fmt.match(/^[#?]+$/)) { o = (""+val); if(val === 0) o = ""; return o.length > fmt.length ? o : hashq(fmt.substr(0,fmt.length-o.length)) + o; } if((r = fmt.match(frac1)) !== null) return write_num_f2(r, aval, sign); if(fmt.match(/^#+0+$/) !== null) return sign + pad0(aval,fmt.length - fmt.indexOf("0")); if((r = fmt.match(dec1)) !== null) { o = (""+val).replace(/^([^\.]+)$/,"$1."+r[1]).replace(/\.$/,"."+r[1]).replace(/\.(\d*)$/,function($$, $1) { return "." + $1 + fill("0", r[1].length-$1.length); }); return fmt.indexOf("0.") !== -1 ? o : o.replace(/^0\./,"."); } fmt = fmt.replace(/^#+([0.])/, "$1"); if((r = fmt.match(/^(0*)\.(#*)$/)) !== null) { return sign + (""+aval).replace(/\.(\d*[1-9])0*$/,".$1").replace(/^(-?\d*)$/,"$1.").replace(/^0\./,r[1].length?"0.":"."); } if((r = fmt.match(/^#,##0(\.?)$/)) !== null) return sign + commaify((""+aval)); if((r = fmt.match(/^#,##0\.([#0]*0)$/)) !== null) { return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify((""+val)) + "." + fill('0',r[1].length); } if((r = fmt.match(/^#,#*,#0/)) !== null) return write_num_int(type,fmt.replace(/^#,#*,/,""),val); if((r = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) !== null) { o = _strrev(write_num_int(type, fmt.replace(/[\\-]/g,""), val)); ri = 0; return _strrev(_strrev(fmt.replace(/\\/g,"")).replace(/[0#]/g,function(x){return ri<o.length?o[ri++]:x==='0'?'0':"";})); } if(fmt.match(phone) !== null) { o = write_num_int(type, "##########", val); return "(" + o.substr(0,3) + ") " + o.substr(3, 3) + "-" + o.substr(6); } var oa = ""; if((r = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) !== null) { ri = Math.min(r[4].length,7); ff = frac(aval, Math.pow(10,ri)-1, false); o = "" + sign; oa = write_num("n", r[1], ff[1]); if(oa[oa.length-1] == " ") oa = oa.substr(0,oa.length-1) + "0"; o += oa + r[2] + "/" + r[3]; oa = rpad_(ff[2],ri); if(oa.length < r[4].length) oa = hashq(r[4].substr(r[4].length-oa.length)) + oa; o += oa; return o; } if((r = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) !== null) { ri = Math.min(Math.max(r[1].length, r[4].length),7); ff = frac(aval, Math.pow(10,ri)-1, true); return sign + (ff[0]||(ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1],ri) + r[2] + "/" + r[3] + rpad_(ff[2],ri): fill(" ", 2*ri+1 + r[2].length + r[3].length)); } if((r = fmt.match(/^[#0?]+$/)) !== null) { o = "" + val; if(fmt.length <= o.length) return o; return hashq(fmt.substr(0,fmt.length-o.length)) + o; } if((r = fmt.match(/^([#0]+)\.([#0]+)$/)) !== null) { o = "" + val.toFixed(Math.min(r[2].length,10)).replace(/([^0])0+$/,"$1"); ri = o.indexOf("."); var lres = fmt.indexOf(".") - ri, rres = fmt.length - o.length - lres; return hashq(fmt.substr(0,lres) + o + fmt.substr(fmt.length-rres)); } if((r = fmt.match(/^00,000\.([#0]*0)$/)) !== null) { return val < 0 ? "-" + write_num_int(type, fmt, -val) : commaify(""+val).replace(/^\d,\d{3}$/,"0$&").replace(/^\d*$/,function($$) { return "00," + ($$.length < 3 ? pad0(0,3-$$.length) : "") + $$; }) + "." + pad0(0,r[1].length); } switch(fmt) { case "#,###": var x = commaify(""+aval); return x !== "0" ? sign + x : ""; default: } throw new Error("unsupported format |" + fmt + "|"); } return function write_num(type, fmt, val) { return (val|0) === val ? write_num_int(type, fmt, val) : write_num_flt(type, fmt, val); };})(); function split_fmt(fmt) { var out = []; var in_str = false, cc; for(var i = 0, j = 0; i < fmt.length; ++i) switch((cc=fmt.charCodeAt(i))) { case 34: /* '"' */ in_str = !in_str; break; case 95: case 42: case 92: /* '_' '*' '\\' */ ++i; break; case 59: /* ';' */ out[out.length] = fmt.substr(j,i-j); j = i+1; } out[out.length] = fmt.substr(j); if(in_str === true) throw new Error("Format |" + fmt + "| unterminated string "); return out; } SSF._split = split_fmt; var abstime = /\[[HhMmSs]*\]/; function eval_fmt(fmt, v, opts, flen) { var out = [], o = "", i = 0, c = "", lst='t', q, dt, j, cc; var hr='H'; /* Tokenize */ while(i < fmt.length) { switch((c = fmt[i])) { case 'G': /* General */ if(!isgeneral(fmt, i)) throw new Error('unrecognized character ' + c + ' in ' +fmt); out[out.length] = {t:'G', v:'General'}; i+=7; break; case '"': /* Literal text */ for(o="";(cc=fmt.charCodeAt(++i)) !== 34 && i < fmt.length;) o += String.fromCharCode(cc); out[out.length] = {t:'t', v:o}; ++i; break; case '\\': var w = fmt[++i], t = (w === "(" || w === ")") ? w : 't'; out[out.length] = {t:t, v:w}; ++i; break; case '_': out[out.length] = {t:'t', v:" "}; i+=2; break; case '@': /* Text Placeholder */ out[out.length] = {t:'T', v:v}; ++i; break; case 'B': case 'b': if(fmt[i+1] === "1" || fmt[i+1] === "2") { if(dt==null) { dt=parse_date_code(v, opts, fmt[i+1] === "2"); if(dt==null) return ""; } out[out.length] = {t:'X', v:fmt.substr(i,2)}; lst = c; i+=2; break; } /* falls through */ case 'M': case 'D': case 'Y': case 'H': case 'S': case 'E': c = c.toLowerCase(); /* falls through */ case 'm': case 'd': case 'y': case 'h': case 's': case 'e': case 'g': if(v < 0) return ""; if(dt==null) { dt=parse_date_code(v, opts); if(dt==null) return ""; } o = c; while(++i<fmt.length && fmt[i].toLowerCase() === c) o+=c; if(c === 'm' && lst.toLowerCase() === 'h') c = 'M'; /* m = minute */ if(c === 'h') c = hr; out[out.length] = {t:c, v:o}; lst = c; break; case 'A': q={t:c, v:"A"}; if(dt==null) dt=parse_date_code(v, opts); if(fmt.substr(i, 3) === "A/P") { if(dt!=null) q.v = dt.H >= 12 ? "P" : "A"; q.t = 'T'; hr='h';i+=3;} else if(fmt.substr(i,5) === "AM/PM") { if(dt!=null) q.v = dt.H >= 12 ? "PM" : "AM"; q.t = 'T'; i+=5; hr='h'; } else { q.t = "t"; ++i; } if(dt==null && q.t === 'T') return ""; out[out.length] = q; lst = c; break; case '[': o = c; while(fmt[i++] !== ']' && i < fmt.length) o += fmt[i]; if(o.substr(-1) !== ']') throw 'unterminated "[" block: |' + o + '|'; if(o.match(abstime)) { if(dt==null) { dt=parse_date_code(v, opts); if(dt==null) return ""; } out[out.length] = {t:'Z', v:o.toLowerCase()}; } else { o=""; } break; /* Numbers */ case '.': if(dt != null) { o = c; while((c=fmt[++i]) === "0") o += c; out[out.length] = {t:'s', v:o}; break; } /* falls through */ case '0': case '#': o = c; while("0#?.,E+-%".indexOf(c=fmt[++i]) > -1 || c=='\\' && fmt[i+1] == "-" && "0#".indexOf(fmt[i+2])>-1) o += c; out[out.length] = {t:'n', v:o}; break; case '?': o = c; while(fmt[++i] === c) o+=c; q={t:c, v:o}; out[out.length] = q; lst = c; break; case '*': ++i; if(fmt[i] == ' ' || fmt[i] == '*') ++i; break; // ** case '(': case ')': out[out.length] = {t:(flen===1?'t':c), v:c}; ++i; break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': o = c; while("0123456789".indexOf(fmt[++i]) > -1) o+=fmt[i]; out[out.length] = {t:'D', v:o}; break; case ' ': out[out.length] = {t:c, v:c}; ++i; break; default: if(",$-+/():!^&'~{}<>=€acfijklopqrtuvwxz".indexOf(c) === -1) throw new Error('unrecognized character ' + c + ' in ' + fmt); out[out.length] = {t:'t', v:c}; ++i; break; } } var bt = 0, ss0 = 0, ssm; for(i=out.length-1, lst='t'; i >= 0; --i) { switch(out[i].t) { case 'h': case 'H': out[i].t = hr; lst='h'; if(bt < 1) bt = 1; break; case 's': if((ssm=out[i].v.match(/\.0+$/))) ss0=Math.max(ss0,ssm[0].length-1); if(bt < 3) bt = 3; /* falls through */ case 'd': case 'y': case 'M': case 'e': lst=out[i].t; break; case 'm': if(lst === 's') { out[i].t = 'M'; if(bt < 2) bt = 2; } break; case 'X': if(out[i].v === "B2"); break; case 'Z': if(bt < 1 && out[i].v.match(/[Hh]/)) bt = 1; if(bt < 2 && out[i].v.match(/[Mm]/)) bt = 2; if(bt < 3 && out[i].v.match(/[Ss]/)) bt = 3; } } switch(bt) { case 0: break; case 1: if(dt.u >= 0.5) { dt.u = 0; ++dt.S; } if(dt.S >= 60) { dt.S = 0; ++dt.M; } if(dt.M >= 60) { dt.M = 0; ++dt.H; } break; case 2: if(dt.u >= 0.5) { dt.u = 0; ++dt.S; } if(dt.S >= 60) { dt.S = 0; ++dt.M; } break; } /* replace fields */ var nstr = "", jj; for(i=0; i < out.length; ++i) { switch(out[i].t) { case 't': case 'T': case ' ': case 'D': break; case 'X': out[i] = undefined; break; case 'd': case 'm': case 'y': case 'h': case 'H': case 'M': case 's': case 'e': case 'b': case 'Z': out[i].v = write_date(out[i].t.charCodeAt(0), out[i].v, dt, ss0); out[i].t = 't'; break; case 'n': case '(': case '?': jj = i+1; while(out[jj] != null && ( (c=out[jj].t) === "?" || c === "D" || (c === " " || c === "t") && out[jj+1] != null && (out[jj+1].t === '?' || out[jj+1].t === "t" && out[jj+1].v === '/') || out[i].t === '(' && (c === ' ' || c === 'n' || c === ')') || c === 't' && (out[jj].v === '/' || '$€'.indexOf(out[jj].v) > -1 || out[jj].v === ' ' && out[jj+1] != null && out[jj+1].t == '?') )) { out[i].v += out[jj].v; out[jj] = undefined; ++jj; } nstr += out[i].v; i = jj-1; break; case 'G': out[i].t = 't'; out[i].v = general_fmt(v,opts); break; } } var vv = "", myv, ostr; if(nstr.length > 0) { myv = (v<0&&nstr.charCodeAt(0) === 45 ? -v : v); /* '-' */ ostr = write_num(nstr.charCodeAt(0) === 40 ? '(' : 'n', nstr, myv); /* '(' */ jj=ostr.length-1; var decpt = out.length; for(i=0; i < out.length; ++i) if(out[i] != null && out[i].v.indexOf(".") > -1) { decpt = i; break; } var lasti=out.length; if(decpt === out.length && ostr.indexOf("E") === -1) { for(i=out.length-1; i>= 0;--i) { if(out[i] == null || 'n?('.indexOf(out[i].t) === -1) continue; if(jj>=out[i].v.length-1) { jj -= out[i].v.length; out[i].v = ostr.substr(jj+1, out[i].v.length); } else if(jj < 0) out[i].v = ""; else { out[i].v = ostr.substr(0, jj+1); jj = -1; } out[i].t = 't'; lasti = i; } if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v; } else if(decpt !== out.length && ostr.indexOf("E") === -1) { jj = ostr.indexOf(".")-1; for(i=decpt; i>= 0; --i) { if(out[i] == null || 'n?('.indexOf(out[i].t) === -1) continue; j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")-1:out[i].v.length-1; vv = out[i].v.substr(j+1); for(; j>=0; --j) { if(jj>=0 && (out[i].v[j] === "0" || out[i].v[j] === "#")) vv = ostr[jj--] + vv; } out[i].v = vv; out[i].t = 't'; lasti = i; } if(jj>=0 && lasti<out.length) out[lasti].v = ostr.substr(0,jj+1) + out[lasti].v; jj = ostr.indexOf(".")+1; for(i=decpt; i<out.length; ++i) { if(out[i] == null || 'n?('.indexOf(out[i].t) === -1 && i !== decpt ) continue; j=out[i].v.indexOf(".")>-1&&i===decpt?out[i].v.indexOf(".")+1:0; vv = out[i].v.substr(0,j); for(; j<out[i].v.length; ++j) { if(jj<ostr.length) vv += ostr[jj++]; } out[i].v = vv; out[i].t = 't'; lasti = i; } } } for(i=0; i<out.length; ++i) if(out[i] != null && 'n(?'.indexOf(out[i].t)>-1) { myv = (flen >1 && v < 0 && i>0 && out[i-1].v === "-" ? -v:v); out[i].v = write_num(out[i].t, out[i].v, myv); out[i].t = 't'; } var retval = ""; for(i=0; i !== out.length; ++i) if(out[i] != null) retval += out[i].v; return retval; } SSF._eval = eval_fmt; var cfregex = /\[[=<>]/; var cfregex2 = /\[([=<>]*)(-?\d+\.?\d*)\]/; function chkcond(v, rr) { if(rr == null) return false; var thresh = parseFloat(rr[2]); switch(rr[1]) { case "=": if(v == thresh) return true; break; case ">": if(v > thresh) return true; break; case "<": if(v < thresh) return true; break; case "<>": if(v != thresh) return true; break; case ">=": if(v >= thresh) return true; break; case "<=": if(v <= thresh) return true; break; } return false; } function choose_fmt(f, v) { var fmt = split_fmt(f); var l = fmt.length, lat = fmt[l-1].indexOf("@"); if(l<4 && lat>-1) --l; if(fmt.length > 4) throw "cannot find right format for |" + fmt + "|"; if(typeof v !== "number") return [4, fmt.length === 4 || lat>-1?fmt[fmt.length-1]:"@"]; switch(fmt.length) { case 1: fmt = lat>-1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"]; break; case 2: fmt = lat>-1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"]; break; case 3: fmt = lat>-1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"]; break; case 4: break; } var ff = v > 0 ? fmt[0] : v < 0 ? fmt[1] : fmt[2]; if(fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l, ff]; if(fmt[0].match(cfregex) != null || fmt[1].match(cfregex) != null) { var m1 = fmt[0].match(cfregex2); var m2 = fmt[1].match(cfregex2); return chkcond(v, m1) ? [l, fmt[0]] : chkcond(v, m2) ? [l, fmt[1]] : [l, fmt[m1 != null && m2 != null ? 2 : 1]]; } return [l, ff]; } function format(fmt,v,o) { fixopts(o != null ? o : (o=[])); var sfmt = ""; switch(typeof fmt) { case "string": sfmt = fmt; break; case "number": sfmt = (o.table != null ? o.table : table_fmt)[fmt]; break; } if(isgeneral(sfmt,0)) return general_fmt(v, o); var f = choose_fmt(sfmt, v); if(isgeneral(f[1])) return general_fmt(v, o); if(v === true) v = "TRUE"; else if(v === false) v = "FALSE"; else if(v === "" || v == null) return ""; return eval_fmt(f[1], v, o, f[0]); } SSF._table = table_fmt; SSF.load = function load_entry(fmt, idx) { table_fmt[idx] = fmt; }; SSF.format = format; SSF.get_table = function get_table() { return table_fmt; }; SSF.load_table = function load_table(tbl) { for(var i=0; i!=0x0188; ++i) if(tbl[i] !== undefined) SSF.load(tbl[i], i); }; }; make_ssf(SSF); /* map from xlml named formats to SSF TODO: localize */ var XLMLFormatMap = { "General Number": "General", "General Date": SSF._table[22], "Long Date": "dddd, mmmm dd, yyyy", "Medium Date": SSF._table[15], "Short Date": SSF._table[14], "Long Time": SSF._table[19], "Medium Time": SSF._table[18], "Short Time": SSF._table[20], "Currency": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)', "Fixed": SSF._table[2], "Standard": SSF._table[4], "Percent": SSF._table[10], "Scientific": SSF._table[11], "Yes/No": '"Yes";"Yes";"No";@', "True/False": '"True";"True";"False";@', "On/Off": '"Yes";"Yes";"No";@' }; var DO_NOT_EXPORT_CFB = true; /* cfb.js (C) 2013-2014 SheetJS -- http://sheetjs.com */ /* vim: set ts=2: */ /*jshint eqnull:true */ /* [MS-CFB] v20130118 */ var CFB = (function _CFB(){ var exports = {}; exports.version = '0.10.2'; function parse(file) { var mver = 3; // major version var ssz = 512; // sector size var nmfs = 0; // number of mini FAT sectors var ndfs = 0; // number of DIFAT sectors var dir_start = 0; // first directory sector location var minifat_start = 0; // first mini FAT sector location var difat_start = 0; // first mini FAT sector location var fat_addrs = []; // locations of FAT sectors /* [MS-CFB] 2.2 Compound File Header */ var blob = file.slice(0,512); prep_blob(blob, 0); /* major version */ var mv = check_get_mver(blob); mver = mv[0]; switch(mver) { case 3: ssz = 512; break; case 4: ssz = 4096; break; default: throw "Major Version: Expected 3 or 4 saw " + mver; } /* reprocess header */ if(ssz !== 512) { blob = file.slice(0,ssz); prep_blob(blob, 28 /* blob.l */); } /* Save header for final object */ var header = file.slice(0,ssz); check_shifts(blob, mver); // Number of Directory Sectors var nds = blob.read_shift(4, 'i'); if(mver === 3 && nds !== 0) throw '# Directory Sectors: Expected 0 saw ' + nds; // Number of FAT Sectors //var nfs = blob.read_shift(4, 'i'); blob.l += 4; // First Directory Sector Location dir_start = blob.read_shift(4, 'i'); // Transaction Signature blob.l += 4; // Mini Stream Cutoff Size blob.chk('00100000', 'Mini Stream Cutoff Size: '); // First Mini FAT Sector Location minifat_start = blob.read_shift(4, 'i'); // Number of Mini FAT Sectors nmfs = blob.read_shift(4, 'i'); // First DIFAT sector location difat_start = blob.read_shift(4, 'i'); // Number of DIFAT Sectors ndfs = blob.read_shift(4, 'i'); // Grab FAT Sector Locations for(var q, j = 0; j < 109; ++j) { /* 109 = (512 - blob.l)>>>2; */ q = blob.read_shift(4, 'i'); if(q<0) break; fat_addrs[j] = q; } /** Break the file up into sectors */ var sectors = sectorify(file, ssz); sleuth_fat(difat_start, ndfs, sectors, ssz, fat_addrs); /** Chains */ var sector_list = make_sector_list(sectors, dir_start, fat_addrs, ssz); sector_list[dir_start].name = "!Directory"; if(nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT"; sector_list[fat_addrs[0]].name = "!FAT"; sector_list.fat_addrs = fat_addrs; sector_list.ssz = ssz; /* [MS-CFB] 2.6.1 Compound File Directory Entry */ var files = {}, Paths = [], FileIndex = [], FullPaths = [], FullPathDir = {}; read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex); build_full_paths(FileIndex, FullPathDir, FullPaths, Paths); var root_name = Paths.shift(); Paths.root = root_name; /* [MS-CFB] 2.6.4 (Unicode 3.0.1 case conversion) */ var find_path = make_find_path(FullPaths, Paths, FileIndex, files, root_name); return { raw: {header: header, sectors: sectors}, FileIndex: FileIndex, FullPaths: FullPaths, FullPathDir: FullPathDir, find: find_path }; } // parse /* [MS-CFB] 2.2 Compound File Header -- read up to major version */ function check_get_mver(blob) { // header signature 8 blob.chk(HEADER_SIGNATURE, 'Header Signature: '); // clsid 16 blob.chk(HEADER_CLSID, 'CLSID: '); // minor version 2 var mver = blob.read_shift(2, 'u'); return [blob.read_shift(2,'u'), mver]; } function check_shifts(blob, mver) { var shift = 0x09; // Byte Order blob.chk('feff', 'Byte Order: '); // Sector Shift switch((shift = blob.read_shift(2))) { case 0x09: if(mver !== 3) throw 'MajorVersion/SectorShift Mismatch'; break; case 0x0c: if(mver !== 4) throw 'MajorVersion/SectorShift Mismatch'; break; default: throw 'Sector Shift: Expected 9 or 12 saw ' + shift; } // Mini Sector Shift blob.chk('0600', 'Mini Sector Shift: '); // Reserved blob.chk('000000000000', 'Reserved: '); } /** Break the file up into sectors */ function sectorify(file, ssz) { var nsectors = Math.ceil(file.length/ssz)-1; var sectors = new Array(nsectors); for(var i=1; i < nsectors; ++i) sectors[i-1] = file.slice(i*ssz,(i+1)*ssz); sectors[nsectors-1] = file.slice(nsectors*ssz); return sectors; } /* [MS-CFB] 2.6.4 Red-Black Tree */ function build_full_paths(FI, FPD, FP, Paths) { var i = 0, L = 0, R = 0, C = 0, j = 0, pl = Paths.length; var dad = new Array(pl), q = new Array(pl); for(; i < pl; ++i) { dad[i]=q[i]=i; FP[i]=Paths[i]; } for(; j < q.length; ++j) { i = q[j]; L = FI[i].L; R = FI[i].R; C = FI[i].C; if(dad[i] === i) { if(L !== -1 /*NOSTREAM*/ && dad[L] !== L) dad[i] = dad[L]; if(R !== -1 && dad[R] !== R) dad[i] = dad[R]; } if(C !== -1 /*NOSTREAM*/) dad[C] = i; if(L !== -1) { dad[L] = dad[i]; q.push(L); } if(R !== -1) { dad[R] = dad[i]; q.push(R); } } for(i=1; i !== pl; ++i) if(dad[i] === i) { if(R !== -1 /*NOSTREAM*/ && dad[R] !== R) dad[i] = dad[R]; else if(L !== -1 && dad[L] !== L) dad[i] = dad[L]; } for(i=1; i < pl; ++i) { if(FI[i].type === 0 /* unknown */) continue; j = dad[i]; if(j === 0) FP[i] = FP[0] + "/" + FP[i]; else while(j !== 0) { FP[i] = FP[j] + "/" + FP[i]; j = dad[j]; } dad[i] = 0; } FP[0] += "/"; for(i=1; i < pl; ++i) { if(FI[i].type !== 2 /* stream */) FP[i] += "/"; FPD[FP[i]] = FI[i]; } } /* [MS-CFB] 2.6.4 */ function make_find_path(FullPaths, Paths, FileIndex, files, root_name) { var UCFullPaths = new Array(FullPaths.length); var UCPaths = new Array(Paths.length), i; for(i = 0; i < FullPaths.length; ++i) UCFullPaths[i] = FullPaths[i].toUpperCase().replace(chr0,'').replace(chr1,'!'); for(i = 0; i < Paths.length; ++i) UCPaths[i] = Paths[i].toUpperCase().replace(chr0,'').replace(chr1,'!'); return function find_path(path) { var k; if(path.charCodeAt(0) === 47 /* "/" */) { k=true; path = root_name + path; } else k = path.indexOf("/") !== -1; var UCPath = path.toUpperCase().replace(chr0,'').replace(chr1,'!'); var w = k === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath); if(w === -1) return null; return k === true ? FileIndex[w] : files[Paths[w]]; }; } /** Chase down the rest of the DIFAT chain to build a comprehensive list DIFAT chains by storing the next sector number as the last 32 bytes */ function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) { var q; if(idx === ENDOFCHAIN) { if(cnt !== 0) throw "DIFAT chain shorter than expected"; } else if(idx !== -1 /*FREESECT*/) { var sector = sectors[idx], m = (ssz>>>2)-1; for(var i = 0; i < m; ++i) { if((q = __readInt32LE(sector,i*4)) === ENDOFCHAIN) break; fat_addrs.push(q); } sleuth_fat(__readInt32LE(sector,ssz-4),cnt - 1, sectors, ssz, fat_addrs); } } /** Follow the linked list of sectors for a given starting point */ function get_sector_list(sectors, start, fat_addrs, ssz, chkd) { var sl = sectors.length; var buf, buf_chain; if(!chkd) chkd = new Array(sl); var modulus = ssz - 1, j, jj; buf = []; buf_chain = []; for(j=start; j>=0;) { chkd[j] = true; buf[buf.length] = j; buf_chain.push(sectors[j]); var addr = fat_addrs[Math.floor(j*4/ssz)]; jj = ((j*4) & modulus); if(ssz < 4 + jj) throw "FAT boundary crossed: " + j + " 4 "+ssz; j = __readInt32LE(sectors[addr], jj); } return {nodes: buf, data:__toBuffer([buf_chain])}; } /** Chase down the sector linked lists */ function make_sector_list(sectors, dir_start, fat_addrs, ssz) { var sl = sectors.length, sector_list = new Array(sl); var chkd = new Array(sl), buf, buf_chain; var modulus = ssz - 1, i, j, k, jj; for(i=0; i < sl; ++i) { buf = []; k = (i + dir_start); if(k >= sl) k-=sl; if(chkd[k] === true) continue; buf_chain = []; for(j=k; j>=0;) { chkd[j] = true; buf[buf.length] = j; buf_chain.push(sectors[j]); var addr = fat_addrs[Math.floor(j*4/ssz)]; jj = ((j*4) & modulus); if(ssz < 4 + jj) throw "FAT boundary crossed: " + j + " 4 "+ssz; j = __readInt32LE(sectors[addr], jj); } sector_list[k] = {nodes: buf, data:__toBuffer([buf_chain])}; } return sector_list; } /* [MS-CFB] 2.6.1 Compound File Directory Entry */ function read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex) { var blob; var minifat_store = 0, pl = (Paths.length?2:0); var sector = sector_list[dir_start].data; var i = 0, namelen = 0, name, o, ctime, mtime; for(; i < sector.length; i+= 128) { blob = sector.slice(i, i+128); prep_blob(blob, 64); namelen = blob.read_shift(2); if(namelen === 0) continue; name = __utf16le(blob,0,namelen-pl); Paths.push(name); o = { name: name, type: blob.read_shift(1), color: blob.read_shift(1), L: blob.read_shift(4, 'i'), R: blob.read_shift(4, 'i'), C: blob.read_shift(4, 'i'), clsid: blob.read_shift(16), state: blob.read_shift(4, 'i') }; ctime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2); if(ctime !== 0) { o.ctime = ctime; o.ct = read_date(blob, blob.l-8); } mtime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2); if(mtime !== 0) { o.mtime = mtime; o.mt = read_date(blob, blob.l-8); } o.start = blob.read_shift(4, 'i'); o.size = blob.read_shift(4, 'i'); if(o.type === 5) { /* root */ minifat_store = o.start; if(nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData"; /*minifat_size = o.size;*/ } else if(o.size >= 4096 /* MSCSZ */) { o.storage = 'fat'; if(sector_list[o.start] === undefined) sector_list[o.start] = get_sector_list(sectors, o.start, sector_list.fat_addrs, sector_list.ssz); sector_list[o.start].name = o.name; o.content = sector_list[o.start].data.slice(0,o.size); prep_blob(o.content, 0); } else { o.storage = 'minifat'; if(minifat_store !== ENDOFCHAIN && o.start !== ENDOFCHAIN) { o.content = sector_list[minifat_store].data.slice(o.start*MSSZ,o.start*MSSZ+o.size); prep_blob(o.content, 0); } } files[name] = o; FileIndex.push(o); } } function read_date(blob, offset) { return new Date(( ( (__readUInt32LE(blob,offset+4)/1e7)*Math.pow(2,32)+__readUInt32LE(blob,offset)/1e7 ) - 11644473600)*1000); } var fs; function readFileSync(filename, options) { if(fs === undefined) fs = require('fs'); return parse(fs.readFileSync(filename), options); } function readSync(blob, options) { switch(options !== undefined && options.type !== undefined ? options.type : "base64") { case "file": return readFileSync(blob, options); case "base64": return parse(s2a(Base64.decode(blob)), options); case "binary": return parse(s2a(blob), options); } return parse(blob); } /** CFB Constants */ var MSSZ = 64; /* Mini Sector Size = 1<<6 */ //var MSCSZ = 4096; /* Mini Stream Cutoff Size */ /* 2.1 Compound File Sector Numbers and Types */ var ENDOFCHAIN = -2; /* 2.2 Compound File Header */ var HEADER_SIGNATURE = 'd0cf11e0a1b11ae1'; var HEADER_CLSID = '00000000000000000000000000000000'; var consts = { /* 2.1 Compund File Sector Numbers and Types */ MAXREGSECT: -6, DIFSECT: -4, FATSECT: -3, ENDOFCHAIN: ENDOFCHAIN, FREESECT: -1, /* 2.2 Compound File Header */ HEADER_SIGNATURE: HEADER_SIGNATURE, HEADER_MINOR_VERSION: '3e00', MAXREGSID: -6, NOSTREAM: -1, HEADER_CLSID: HEADER_CLSID, /* 2.6.1 Compound File Directory Entry */ EntryTypes: ['unknown','storage','stream','lockbytes','property','root'] }; exports.read = readSync; exports.parse = parse; exports.utils = { ReadShift: ReadShift, CheckField: CheckField, prep_blob: prep_blob, bconcat: bconcat, consts: consts }; return exports; })(); if(typeof require !== 'undefined' && typeof module !== 'undefined' && typeof DO_NOT_EXPORT_CFB === 'undefined') { module.exports = CFB; } function isval(x) { return x !== undefined && x !== null; } function keys(o) { return Object.keys(o); } function evert_key(obj, key) { var o = [], K = keys(obj); for(var i = 0; i !== K.length; ++i) o[obj[K[i]][key]] = K[i]; return o; } function evert(obj) { var o = [], K = keys(obj); for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = K[i]; return o; } function evert_num(obj) { var o = [], K = keys(obj); for(var i = 0; i !== K.length; ++i) o[obj[K[i]]] = parseInt(K[i],10); return o; } function evert_arr(obj) { var o = [], K = keys(obj); for(var i = 0; i !== K.length; ++i) { if(o[obj[K[i]]] == null) o[obj[K[i]]] = []; o[obj[K[i]]].push(K[i]); } return o; } /* TODO: date1904 logic */ function datenum(v, date1904) { if(date1904) v+=1462; var epoch = Date.parse(v); return (epoch + 2209161600000) / (24 * 60 * 60 * 1000); } function cc2str(arr) { var o = ""; for(var i = 0; i != arr.length; ++i) o += String.fromCharCode(arr[i]); return o; } function getdata(data) { if(!data) return null; if(data.name.substr(-4) === ".bin") { if(data.data) return char_codes(data.data); if(data.asNodeBuffer && has_buf) return data.asNodeBuffer(); if(data._data && data._data.getContent) return Array.prototype.slice.call(data._data.getContent()); } else { if(data.data) return data.name.substr(-4) !== ".bin" ? debom_xml(data.data) : char_codes(data.data); if(data.asNodeBuffer && has_buf) return debom_xml(data.asNodeBuffer().toString('binary')); if(data.asBinary) return debom_xml(data.asBinary()); if(data._data && data._data.getContent) return debom_xml(cc2str(Array.prototype.slice.call(data._data.getContent(),0))); } return null; } function safegetzipfile(zip, file) { var f = file; if(zip.files[f]) return zip.files[f]; f = file.toLowerCase(); if(zip.files[f]) return zip.files[f]; f = f.replace(/\//g,'\\'); if(zip.files[f]) return zip.files[f]; return null; } function getzipfile(zip, file) { var o = safegetzipfile(zip, file); if(o == null) throw new Error("Cannot find file " + file + " in zip"); return o; } function getzipdata(zip, file, safe) { if(!safe) return getdata(getzipfile(zip, file)); if(!file) return null; try { return getzipdata(zip, file); } catch(e) { return null; } } var _fs, jszip; if(typeof JSZip !== 'undefined') jszip = JSZip; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { if(has_buf && typeof jszip === 'undefined') jszip = require('js'+'zip'); if(typeof jszip === 'undefined') jszip = require('./js'+'zip').JSZip; _fs = require('f'+'s'); } } var attregexg=/([\w:]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:'))/g; var tagregex=/<[^>]*>/g; var nsregex=/<\w*:/, nsregex2 = /<(\/?)\w+:/; function parsexmltag(tag, skip_root) { var z = []; var eq = 0, c = 0; for(; eq !== tag.length; ++eq) if((c = tag.charCodeAt(eq)) === 32 || c === 10 || c === 13) break; if(!skip_root) z[0] = tag.substr(0, eq); if(eq === tag.length) return z; var m = tag.match(attregexg), j=0, w="", v="", i=0, q="", cc=""; if(m) for(i = 0; i != m.length; ++i) { cc = m[i]; for(c=0; c != cc.length; ++c) if(cc.charCodeAt(c) === 61) break; q = cc.substr(0,c); v = cc.substring(c+2, cc.length-1); for(j=0;j!=q.length;++j) if(q.charCodeAt(j) === 58) break; if(j===q.length) z[q] = v; else z[(j===5 && q.substr(0,5)==="xmlns"?"xmlns":"")+q.substr(j+1)] = v; } return z; } function strip_ns(x) { return x.replace(nsregex2, "<$1"); } var encodings = { '&quot;': '"', '&apos;': "'", '&gt;': '>', '&lt;': '<', '&amp;': '&' }; var rencoding = evert(encodings); var rencstr = "&<>'\"".split(""); // TODO: CP remap (need to read file version to determine OS) var unescapexml = (function() { var encregex = /&[a-z]*;/g, coderegex = /_x([\da-fA-F]+)_/g; return function unescapexml(text){ var s = text + ''; return s.replace(encregex, function($$) { return encodings[$$]; }).replace(