Xls.php 279 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Reader;
  3. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  4. use PhpOffice\PhpSpreadsheet\Cell\DataType;
  5. use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
  6. use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
  7. use PhpOffice\PhpSpreadsheet\NamedRange;
  8. use PhpOffice\PhpSpreadsheet\RichText\RichText;
  9. use PhpOffice\PhpSpreadsheet\Shared\CodePage;
  10. use PhpOffice\PhpSpreadsheet\Shared\Date;
  11. use PhpOffice\PhpSpreadsheet\Shared\Escher;
  12. use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
  13. use PhpOffice\PhpSpreadsheet\Shared\File;
  14. use PhpOffice\PhpSpreadsheet\Shared\OLE;
  15. use PhpOffice\PhpSpreadsheet\Shared\OLERead;
  16. use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
  17. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  18. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  19. use PhpOffice\PhpSpreadsheet\Style\Borders;
  20. use PhpOffice\PhpSpreadsheet\Style\Font;
  21. use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
  22. use PhpOffice\PhpSpreadsheet\Style\Protection;
  23. use PhpOffice\PhpSpreadsheet\Style\Style;
  24. use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
  25. use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
  26. use PhpOffice\PhpSpreadsheet\Worksheet\SheetView;
  27. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  28. // Original file header of ParseXL (used as the base for this class):
  29. // --------------------------------------------------------------------------------
  30. // Adapted from Excel_Spreadsheet_Reader developed by users bizon153,
  31. // trex005, and mmp11 (SourceForge.net)
  32. // https://sourceforge.net/projects/phpexcelreader/
  33. // Primary changes made by canyoncasa (dvc) for ParseXL 1.00 ...
  34. // Modelled moreso after Perl Excel Parse/Write modules
  35. // Added Parse_Excel_Spreadsheet object
  36. // Reads a whole worksheet or tab as row,column array or as
  37. // associated hash of indexed rows and named column fields
  38. // Added variables for worksheet (tab) indexes and names
  39. // Added an object call for loading individual woorksheets
  40. // Changed default indexing defaults to 0 based arrays
  41. // Fixed date/time and percent formats
  42. // Includes patches found at SourceForge...
  43. // unicode patch by nobody
  44. // unpack("d") machine depedency patch by matchy
  45. // boundsheet utf16 patch by bjaenichen
  46. // Renamed functions for shorter names
  47. // General code cleanup and rigor, including <80 column width
  48. // Included a testcase Excel file and PHP example calls
  49. // Code works for PHP 5.x
  50. // Primary changes made by canyoncasa (dvc) for ParseXL 1.10 ...
  51. // http://sourceforge.net/tracker/index.php?func=detail&aid=1466964&group_id=99160&atid=623334
  52. // Decoding of formula conditions, results, and tokens.
  53. // Support for user-defined named cells added as an array "namedcells"
  54. // Patch code for user-defined named cells supports single cells only.
  55. // NOTE: this patch only works for BIFF8 as BIFF5-7 use a different
  56. // external sheet reference structure
  57. class Xls extends BaseReader
  58. {
  59. // ParseXL definitions
  60. const XLS_BIFF8 = 0x0600;
  61. const XLS_BIFF7 = 0x0500;
  62. const XLS_WORKBOOKGLOBALS = 0x0005;
  63. const XLS_WORKSHEET = 0x0010;
  64. // record identifiers
  65. const XLS_TYPE_FORMULA = 0x0006;
  66. const XLS_TYPE_EOF = 0x000a;
  67. const XLS_TYPE_PROTECT = 0x0012;
  68. const XLS_TYPE_OBJECTPROTECT = 0x0063;
  69. const XLS_TYPE_SCENPROTECT = 0x00dd;
  70. const XLS_TYPE_PASSWORD = 0x0013;
  71. const XLS_TYPE_HEADER = 0x0014;
  72. const XLS_TYPE_FOOTER = 0x0015;
  73. const XLS_TYPE_EXTERNSHEET = 0x0017;
  74. const XLS_TYPE_DEFINEDNAME = 0x0018;
  75. const XLS_TYPE_VERTICALPAGEBREAKS = 0x001a;
  76. const XLS_TYPE_HORIZONTALPAGEBREAKS = 0x001b;
  77. const XLS_TYPE_NOTE = 0x001c;
  78. const XLS_TYPE_SELECTION = 0x001d;
  79. const XLS_TYPE_DATEMODE = 0x0022;
  80. const XLS_TYPE_EXTERNNAME = 0x0023;
  81. const XLS_TYPE_LEFTMARGIN = 0x0026;
  82. const XLS_TYPE_RIGHTMARGIN = 0x0027;
  83. const XLS_TYPE_TOPMARGIN = 0x0028;
  84. const XLS_TYPE_BOTTOMMARGIN = 0x0029;
  85. const XLS_TYPE_PRINTGRIDLINES = 0x002b;
  86. const XLS_TYPE_FILEPASS = 0x002f;
  87. const XLS_TYPE_FONT = 0x0031;
  88. const XLS_TYPE_CONTINUE = 0x003c;
  89. const XLS_TYPE_PANE = 0x0041;
  90. const XLS_TYPE_CODEPAGE = 0x0042;
  91. const XLS_TYPE_DEFCOLWIDTH = 0x0055;
  92. const XLS_TYPE_OBJ = 0x005d;
  93. const XLS_TYPE_COLINFO = 0x007d;
  94. const XLS_TYPE_IMDATA = 0x007f;
  95. const XLS_TYPE_SHEETPR = 0x0081;
  96. const XLS_TYPE_HCENTER = 0x0083;
  97. const XLS_TYPE_VCENTER = 0x0084;
  98. const XLS_TYPE_SHEET = 0x0085;
  99. const XLS_TYPE_PALETTE = 0x0092;
  100. const XLS_TYPE_SCL = 0x00a0;
  101. const XLS_TYPE_PAGESETUP = 0x00a1;
  102. const XLS_TYPE_MULRK = 0x00bd;
  103. const XLS_TYPE_MULBLANK = 0x00be;
  104. const XLS_TYPE_DBCELL = 0x00d7;
  105. const XLS_TYPE_XF = 0x00e0;
  106. const XLS_TYPE_MERGEDCELLS = 0x00e5;
  107. const XLS_TYPE_MSODRAWINGGROUP = 0x00eb;
  108. const XLS_TYPE_MSODRAWING = 0x00ec;
  109. const XLS_TYPE_SST = 0x00fc;
  110. const XLS_TYPE_LABELSST = 0x00fd;
  111. const XLS_TYPE_EXTSST = 0x00ff;
  112. const XLS_TYPE_EXTERNALBOOK = 0x01ae;
  113. const XLS_TYPE_DATAVALIDATIONS = 0x01b2;
  114. const XLS_TYPE_TXO = 0x01b6;
  115. const XLS_TYPE_HYPERLINK = 0x01b8;
  116. const XLS_TYPE_DATAVALIDATION = 0x01be;
  117. const XLS_TYPE_DIMENSION = 0x0200;
  118. const XLS_TYPE_BLANK = 0x0201;
  119. const XLS_TYPE_NUMBER = 0x0203;
  120. const XLS_TYPE_LABEL = 0x0204;
  121. const XLS_TYPE_BOOLERR = 0x0205;
  122. const XLS_TYPE_STRING = 0x0207;
  123. const XLS_TYPE_ROW = 0x0208;
  124. const XLS_TYPE_INDEX = 0x020b;
  125. const XLS_TYPE_ARRAY = 0x0221;
  126. const XLS_TYPE_DEFAULTROWHEIGHT = 0x0225;
  127. const XLS_TYPE_WINDOW2 = 0x023e;
  128. const XLS_TYPE_RK = 0x027e;
  129. const XLS_TYPE_STYLE = 0x0293;
  130. const XLS_TYPE_FORMAT = 0x041e;
  131. const XLS_TYPE_SHAREDFMLA = 0x04bc;
  132. const XLS_TYPE_BOF = 0x0809;
  133. const XLS_TYPE_SHEETPROTECTION = 0x0867;
  134. const XLS_TYPE_RANGEPROTECTION = 0x0868;
  135. const XLS_TYPE_SHEETLAYOUT = 0x0862;
  136. const XLS_TYPE_XFEXT = 0x087d;
  137. const XLS_TYPE_PAGELAYOUTVIEW = 0x088b;
  138. const XLS_TYPE_UNKNOWN = 0xffff;
  139. // Encryption type
  140. const MS_BIFF_CRYPTO_NONE = 0;
  141. const MS_BIFF_CRYPTO_XOR = 1;
  142. const MS_BIFF_CRYPTO_RC4 = 2;
  143. // Size of stream blocks when using RC4 encryption
  144. const REKEY_BLOCK = 0x400;
  145. /**
  146. * Summary Information stream data.
  147. *
  148. * @var string
  149. */
  150. private $summaryInformation;
  151. /**
  152. * Extended Summary Information stream data.
  153. *
  154. * @var string
  155. */
  156. private $documentSummaryInformation;
  157. /**
  158. * Workbook stream data. (Includes workbook globals substream as well as sheet substreams).
  159. *
  160. * @var string
  161. */
  162. private $data;
  163. /**
  164. * Size in bytes of $this->data.
  165. *
  166. * @var int
  167. */
  168. private $dataSize;
  169. /**
  170. * Current position in stream.
  171. *
  172. * @var int
  173. */
  174. private $pos;
  175. /**
  176. * Workbook to be returned by the reader.
  177. *
  178. * @var Spreadsheet
  179. */
  180. private $spreadsheet;
  181. /**
  182. * Worksheet that is currently being built by the reader.
  183. *
  184. * @var Worksheet
  185. */
  186. private $phpSheet;
  187. /**
  188. * BIFF version.
  189. *
  190. * @var int
  191. */
  192. private $version;
  193. /**
  194. * Codepage set in the Excel file being read. Only important for BIFF5 (Excel 5.0 - Excel 95)
  195. * For BIFF8 (Excel 97 - Excel 2003) this will always have the value 'UTF-16LE'.
  196. *
  197. * @var string
  198. */
  199. private $codepage;
  200. /**
  201. * Shared formats.
  202. *
  203. * @var array
  204. */
  205. private $formats;
  206. /**
  207. * Shared fonts.
  208. *
  209. * @var array
  210. */
  211. private $objFonts;
  212. /**
  213. * Color palette.
  214. *
  215. * @var array
  216. */
  217. private $palette;
  218. /**
  219. * Worksheets.
  220. *
  221. * @var array
  222. */
  223. private $sheets;
  224. /**
  225. * External books.
  226. *
  227. * @var array
  228. */
  229. private $externalBooks;
  230. /**
  231. * REF structures. Only applies to BIFF8.
  232. *
  233. * @var array
  234. */
  235. private $ref;
  236. /**
  237. * External names.
  238. *
  239. * @var array
  240. */
  241. private $externalNames;
  242. /**
  243. * Defined names.
  244. *
  245. * @var array
  246. */
  247. private $definedname;
  248. /**
  249. * Shared strings. Only applies to BIFF8.
  250. *
  251. * @var array
  252. */
  253. private $sst;
  254. /**
  255. * Panes are frozen? (in sheet currently being read). See WINDOW2 record.
  256. *
  257. * @var bool
  258. */
  259. private $frozen;
  260. /**
  261. * Fit printout to number of pages? (in sheet currently being read). See SHEETPR record.
  262. *
  263. * @var bool
  264. */
  265. private $isFitToPages;
  266. /**
  267. * Objects. One OBJ record contributes with one entry.
  268. *
  269. * @var array
  270. */
  271. private $objs;
  272. /**
  273. * Text Objects. One TXO record corresponds with one entry.
  274. *
  275. * @var array
  276. */
  277. private $textObjects;
  278. /**
  279. * Cell Annotations (BIFF8).
  280. *
  281. * @var array
  282. */
  283. private $cellNotes;
  284. /**
  285. * The combined MSODRAWINGGROUP data.
  286. *
  287. * @var string
  288. */
  289. private $drawingGroupData;
  290. /**
  291. * The combined MSODRAWING data (per sheet).
  292. *
  293. * @var string
  294. */
  295. private $drawingData;
  296. /**
  297. * Keep track of XF index.
  298. *
  299. * @var int
  300. */
  301. private $xfIndex;
  302. /**
  303. * Mapping of XF index (that is a cell XF) to final index in cellXf collection.
  304. *
  305. * @var array
  306. */
  307. private $mapCellXfIndex;
  308. /**
  309. * Mapping of XF index (that is a style XF) to final index in cellStyleXf collection.
  310. *
  311. * @var array
  312. */
  313. private $mapCellStyleXfIndex;
  314. /**
  315. * The shared formulas in a sheet. One SHAREDFMLA record contributes with one value.
  316. *
  317. * @var array
  318. */
  319. private $sharedFormulas;
  320. /**
  321. * The shared formula parts in a sheet. One FORMULA record contributes with one value if it
  322. * refers to a shared formula.
  323. *
  324. * @var array
  325. */
  326. private $sharedFormulaParts;
  327. /**
  328. * The type of encryption in use.
  329. *
  330. * @var int
  331. */
  332. private $encryption = 0;
  333. /**
  334. * The position in the stream after which contents are encrypted.
  335. *
  336. * @var int
  337. */
  338. private $encryptionStartPos = false;
  339. /**
  340. * The current RC4 decryption object.
  341. *
  342. * @var Xls\RC4
  343. */
  344. private $rc4Key;
  345. /**
  346. * The position in the stream that the RC4 decryption object was left at.
  347. *
  348. * @var int
  349. */
  350. private $rc4Pos = 0;
  351. /**
  352. * The current MD5 context state.
  353. *
  354. * @var string
  355. */
  356. private $md5Ctxt;
  357. /**
  358. * @var int
  359. */
  360. private $textObjRef;
  361. /**
  362. * @var string
  363. */
  364. private $baseCell;
  365. /**
  366. * Create a new Xls Reader instance.
  367. */
  368. public function __construct()
  369. {
  370. $this->readFilter = new DefaultReadFilter();
  371. }
  372. /**
  373. * Can the current IReader read the file?
  374. *
  375. * @param string $pFilename
  376. *
  377. * @return bool
  378. */
  379. public function canRead($pFilename)
  380. {
  381. File::assertFile($pFilename);
  382. try {
  383. // Use ParseXL for the hard work.
  384. $ole = new OLERead();
  385. // get excel data
  386. $ole->read($pFilename);
  387. return true;
  388. } catch (PhpSpreadsheetException $e) {
  389. return false;
  390. }
  391. }
  392. /**
  393. * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object.
  394. *
  395. * @param string $pFilename
  396. *
  397. * @throws Exception
  398. *
  399. * @return array
  400. */
  401. public function listWorksheetNames($pFilename)
  402. {
  403. File::assertFile($pFilename);
  404. $worksheetNames = [];
  405. // Read the OLE file
  406. $this->loadOLE($pFilename);
  407. // total byte size of Excel data (workbook global substream + sheet substreams)
  408. $this->dataSize = strlen($this->data);
  409. $this->pos = 0;
  410. $this->sheets = [];
  411. // Parse Workbook Global Substream
  412. while ($this->pos < $this->dataSize) {
  413. $code = self::getUInt2d($this->data, $this->pos);
  414. switch ($code) {
  415. case self::XLS_TYPE_BOF:
  416. $this->readBof();
  417. break;
  418. case self::XLS_TYPE_SHEET:
  419. $this->readSheet();
  420. break;
  421. case self::XLS_TYPE_EOF:
  422. $this->readDefault();
  423. break 2;
  424. default:
  425. $this->readDefault();
  426. break;
  427. }
  428. }
  429. foreach ($this->sheets as $sheet) {
  430. if ($sheet['sheetType'] != 0x00) {
  431. // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module
  432. continue;
  433. }
  434. $worksheetNames[] = $sheet['name'];
  435. }
  436. return $worksheetNames;
  437. }
  438. /**
  439. * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
  440. *
  441. * @param string $pFilename
  442. *
  443. * @throws Exception
  444. *
  445. * @return array
  446. */
  447. public function listWorksheetInfo($pFilename)
  448. {
  449. File::assertFile($pFilename);
  450. $worksheetInfo = [];
  451. // Read the OLE file
  452. $this->loadOLE($pFilename);
  453. // total byte size of Excel data (workbook global substream + sheet substreams)
  454. $this->dataSize = strlen($this->data);
  455. // initialize
  456. $this->pos = 0;
  457. $this->sheets = [];
  458. // Parse Workbook Global Substream
  459. while ($this->pos < $this->dataSize) {
  460. $code = self::getUInt2d($this->data, $this->pos);
  461. switch ($code) {
  462. case self::XLS_TYPE_BOF:
  463. $this->readBof();
  464. break;
  465. case self::XLS_TYPE_SHEET:
  466. $this->readSheet();
  467. break;
  468. case self::XLS_TYPE_EOF:
  469. $this->readDefault();
  470. break 2;
  471. default:
  472. $this->readDefault();
  473. break;
  474. }
  475. }
  476. // Parse the individual sheets
  477. foreach ($this->sheets as $sheet) {
  478. if ($sheet['sheetType'] != 0x00) {
  479. // 0x00: Worksheet
  480. // 0x02: Chart
  481. // 0x06: Visual Basic module
  482. continue;
  483. }
  484. $tmpInfo = [];
  485. $tmpInfo['worksheetName'] = $sheet['name'];
  486. $tmpInfo['lastColumnLetter'] = 'A';
  487. $tmpInfo['lastColumnIndex'] = 0;
  488. $tmpInfo['totalRows'] = 0;
  489. $tmpInfo['totalColumns'] = 0;
  490. $this->pos = $sheet['offset'];
  491. while ($this->pos <= $this->dataSize - 4) {
  492. $code = self::getUInt2d($this->data, $this->pos);
  493. switch ($code) {
  494. case self::XLS_TYPE_RK:
  495. case self::XLS_TYPE_LABELSST:
  496. case self::XLS_TYPE_NUMBER:
  497. case self::XLS_TYPE_FORMULA:
  498. case self::XLS_TYPE_BOOLERR:
  499. case self::XLS_TYPE_LABEL:
  500. $length = self::getUInt2d($this->data, $this->pos + 2);
  501. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  502. // move stream pointer to next record
  503. $this->pos += 4 + $length;
  504. $rowIndex = self::getUInt2d($recordData, 0) + 1;
  505. $columnIndex = self::getUInt2d($recordData, 2);
  506. $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex);
  507. $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex);
  508. break;
  509. case self::XLS_TYPE_BOF:
  510. $this->readBof();
  511. break;
  512. case self::XLS_TYPE_EOF:
  513. $this->readDefault();
  514. break 2;
  515. default:
  516. $this->readDefault();
  517. break;
  518. }
  519. }
  520. $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
  521. $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1;
  522. $worksheetInfo[] = $tmpInfo;
  523. }
  524. return $worksheetInfo;
  525. }
  526. /**
  527. * Loads PhpSpreadsheet from file.
  528. *
  529. * @param string $pFilename
  530. *
  531. * @throws Exception
  532. *
  533. * @return Spreadsheet
  534. */
  535. public function load($pFilename)
  536. {
  537. // Read the OLE file
  538. $this->loadOLE($pFilename);
  539. // Initialisations
  540. $this->spreadsheet = new Spreadsheet();
  541. $this->spreadsheet->removeSheetByIndex(0); // remove 1st sheet
  542. if (!$this->readDataOnly) {
  543. $this->spreadsheet->removeCellStyleXfByIndex(0); // remove the default style
  544. $this->spreadsheet->removeCellXfByIndex(0); // remove the default style
  545. }
  546. // Read the summary information stream (containing meta data)
  547. $this->readSummaryInformation();
  548. // Read the Additional document summary information stream (containing application-specific meta data)
  549. $this->readDocumentSummaryInformation();
  550. // total byte size of Excel data (workbook global substream + sheet substreams)
  551. $this->dataSize = strlen($this->data);
  552. // initialize
  553. $this->pos = 0;
  554. $this->codepage = 'CP1252';
  555. $this->formats = [];
  556. $this->objFonts = [];
  557. $this->palette = [];
  558. $this->sheets = [];
  559. $this->externalBooks = [];
  560. $this->ref = [];
  561. $this->definedname = [];
  562. $this->sst = [];
  563. $this->drawingGroupData = '';
  564. $this->xfIndex = '';
  565. $this->mapCellXfIndex = [];
  566. $this->mapCellStyleXfIndex = [];
  567. // Parse Workbook Global Substream
  568. while ($this->pos < $this->dataSize) {
  569. $code = self::getUInt2d($this->data, $this->pos);
  570. switch ($code) {
  571. case self::XLS_TYPE_BOF:
  572. $this->readBof();
  573. break;
  574. case self::XLS_TYPE_FILEPASS:
  575. $this->readFilepass();
  576. break;
  577. case self::XLS_TYPE_CODEPAGE:
  578. $this->readCodepage();
  579. break;
  580. case self::XLS_TYPE_DATEMODE:
  581. $this->readDateMode();
  582. break;
  583. case self::XLS_TYPE_FONT:
  584. $this->readFont();
  585. break;
  586. case self::XLS_TYPE_FORMAT:
  587. $this->readFormat();
  588. break;
  589. case self::XLS_TYPE_XF:
  590. $this->readXf();
  591. break;
  592. case self::XLS_TYPE_XFEXT:
  593. $this->readXfExt();
  594. break;
  595. case self::XLS_TYPE_STYLE:
  596. $this->readStyle();
  597. break;
  598. case self::XLS_TYPE_PALETTE:
  599. $this->readPalette();
  600. break;
  601. case self::XLS_TYPE_SHEET:
  602. $this->readSheet();
  603. break;
  604. case self::XLS_TYPE_EXTERNALBOOK:
  605. $this->readExternalBook();
  606. break;
  607. case self::XLS_TYPE_EXTERNNAME:
  608. $this->readExternName();
  609. break;
  610. case self::XLS_TYPE_EXTERNSHEET:
  611. $this->readExternSheet();
  612. break;
  613. case self::XLS_TYPE_DEFINEDNAME:
  614. $this->readDefinedName();
  615. break;
  616. case self::XLS_TYPE_MSODRAWINGGROUP:
  617. $this->readMsoDrawingGroup();
  618. break;
  619. case self::XLS_TYPE_SST:
  620. $this->readSst();
  621. break;
  622. case self::XLS_TYPE_EOF:
  623. $this->readDefault();
  624. break 2;
  625. default:
  626. $this->readDefault();
  627. break;
  628. }
  629. }
  630. // Resolve indexed colors for font, fill, and border colors
  631. // Cannot be resolved already in XF record, because PALETTE record comes afterwards
  632. if (!$this->readDataOnly) {
  633. foreach ($this->objFonts as $objFont) {
  634. if (isset($objFont->colorIndex)) {
  635. $color = Xls\Color::map($objFont->colorIndex, $this->palette, $this->version);
  636. $objFont->getColor()->setRGB($color['rgb']);
  637. }
  638. }
  639. foreach ($this->spreadsheet->getCellXfCollection() as $objStyle) {
  640. // fill start and end color
  641. $fill = $objStyle->getFill();
  642. if (isset($fill->startcolorIndex)) {
  643. $startColor = Xls\Color::map($fill->startcolorIndex, $this->palette, $this->version);
  644. $fill->getStartColor()->setRGB($startColor['rgb']);
  645. }
  646. if (isset($fill->endcolorIndex)) {
  647. $endColor = Xls\Color::map($fill->endcolorIndex, $this->palette, $this->version);
  648. $fill->getEndColor()->setRGB($endColor['rgb']);
  649. }
  650. // border colors
  651. $top = $objStyle->getBorders()->getTop();
  652. $right = $objStyle->getBorders()->getRight();
  653. $bottom = $objStyle->getBorders()->getBottom();
  654. $left = $objStyle->getBorders()->getLeft();
  655. $diagonal = $objStyle->getBorders()->getDiagonal();
  656. if (isset($top->colorIndex)) {
  657. $borderTopColor = Xls\Color::map($top->colorIndex, $this->palette, $this->version);
  658. $top->getColor()->setRGB($borderTopColor['rgb']);
  659. }
  660. if (isset($right->colorIndex)) {
  661. $borderRightColor = Xls\Color::map($right->colorIndex, $this->palette, $this->version);
  662. $right->getColor()->setRGB($borderRightColor['rgb']);
  663. }
  664. if (isset($bottom->colorIndex)) {
  665. $borderBottomColor = Xls\Color::map($bottom->colorIndex, $this->palette, $this->version);
  666. $bottom->getColor()->setRGB($borderBottomColor['rgb']);
  667. }
  668. if (isset($left->colorIndex)) {
  669. $borderLeftColor = Xls\Color::map($left->colorIndex, $this->palette, $this->version);
  670. $left->getColor()->setRGB($borderLeftColor['rgb']);
  671. }
  672. if (isset($diagonal->colorIndex)) {
  673. $borderDiagonalColor = Xls\Color::map($diagonal->colorIndex, $this->palette, $this->version);
  674. $diagonal->getColor()->setRGB($borderDiagonalColor['rgb']);
  675. }
  676. }
  677. }
  678. // treat MSODRAWINGGROUP records, workbook-level Escher
  679. if (!$this->readDataOnly && $this->drawingGroupData) {
  680. $escherWorkbook = new Escher();
  681. $reader = new Xls\Escher($escherWorkbook);
  682. $escherWorkbook = $reader->load($this->drawingGroupData);
  683. }
  684. // Parse the individual sheets
  685. foreach ($this->sheets as $sheet) {
  686. if ($sheet['sheetType'] != 0x00) {
  687. // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module
  688. continue;
  689. }
  690. // check if sheet should be skipped
  691. if (isset($this->loadSheetsOnly) && !in_array($sheet['name'], $this->loadSheetsOnly)) {
  692. continue;
  693. }
  694. // add sheet to PhpSpreadsheet object
  695. $this->phpSheet = $this->spreadsheet->createSheet();
  696. // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula
  697. // cells... during the load, all formulae should be correct, and we're simply bringing the worksheet
  698. // name in line with the formula, not the reverse
  699. $this->phpSheet->setTitle($sheet['name'], false, false);
  700. $this->phpSheet->setSheetState($sheet['sheetState']);
  701. $this->pos = $sheet['offset'];
  702. // Initialize isFitToPages. May change after reading SHEETPR record.
  703. $this->isFitToPages = false;
  704. // Initialize drawingData
  705. $this->drawingData = '';
  706. // Initialize objs
  707. $this->objs = [];
  708. // Initialize shared formula parts
  709. $this->sharedFormulaParts = [];
  710. // Initialize shared formulas
  711. $this->sharedFormulas = [];
  712. // Initialize text objs
  713. $this->textObjects = [];
  714. // Initialize cell annotations
  715. $this->cellNotes = [];
  716. $this->textObjRef = -1;
  717. while ($this->pos <= $this->dataSize - 4) {
  718. $code = self::getUInt2d($this->data, $this->pos);
  719. switch ($code) {
  720. case self::XLS_TYPE_BOF:
  721. $this->readBof();
  722. break;
  723. case self::XLS_TYPE_PRINTGRIDLINES:
  724. $this->readPrintGridlines();
  725. break;
  726. case self::XLS_TYPE_DEFAULTROWHEIGHT:
  727. $this->readDefaultRowHeight();
  728. break;
  729. case self::XLS_TYPE_SHEETPR:
  730. $this->readSheetPr();
  731. break;
  732. case self::XLS_TYPE_HORIZONTALPAGEBREAKS:
  733. $this->readHorizontalPageBreaks();
  734. break;
  735. case self::XLS_TYPE_VERTICALPAGEBREAKS:
  736. $this->readVerticalPageBreaks();
  737. break;
  738. case self::XLS_TYPE_HEADER:
  739. $this->readHeader();
  740. break;
  741. case self::XLS_TYPE_FOOTER:
  742. $this->readFooter();
  743. break;
  744. case self::XLS_TYPE_HCENTER:
  745. $this->readHcenter();
  746. break;
  747. case self::XLS_TYPE_VCENTER:
  748. $this->readVcenter();
  749. break;
  750. case self::XLS_TYPE_LEFTMARGIN:
  751. $this->readLeftMargin();
  752. break;
  753. case self::XLS_TYPE_RIGHTMARGIN:
  754. $this->readRightMargin();
  755. break;
  756. case self::XLS_TYPE_TOPMARGIN:
  757. $this->readTopMargin();
  758. break;
  759. case self::XLS_TYPE_BOTTOMMARGIN:
  760. $this->readBottomMargin();
  761. break;
  762. case self::XLS_TYPE_PAGESETUP:
  763. $this->readPageSetup();
  764. break;
  765. case self::XLS_TYPE_PROTECT:
  766. $this->readProtect();
  767. break;
  768. case self::XLS_TYPE_SCENPROTECT:
  769. $this->readScenProtect();
  770. break;
  771. case self::XLS_TYPE_OBJECTPROTECT:
  772. $this->readObjectProtect();
  773. break;
  774. case self::XLS_TYPE_PASSWORD:
  775. $this->readPassword();
  776. break;
  777. case self::XLS_TYPE_DEFCOLWIDTH:
  778. $this->readDefColWidth();
  779. break;
  780. case self::XLS_TYPE_COLINFO:
  781. $this->readColInfo();
  782. break;
  783. case self::XLS_TYPE_DIMENSION:
  784. $this->readDefault();
  785. break;
  786. case self::XLS_TYPE_ROW:
  787. $this->readRow();
  788. break;
  789. case self::XLS_TYPE_DBCELL:
  790. $this->readDefault();
  791. break;
  792. case self::XLS_TYPE_RK:
  793. $this->readRk();
  794. break;
  795. case self::XLS_TYPE_LABELSST:
  796. $this->readLabelSst();
  797. break;
  798. case self::XLS_TYPE_MULRK:
  799. $this->readMulRk();
  800. break;
  801. case self::XLS_TYPE_NUMBER:
  802. $this->readNumber();
  803. break;
  804. case self::XLS_TYPE_FORMULA:
  805. $this->readFormula();
  806. break;
  807. case self::XLS_TYPE_SHAREDFMLA:
  808. $this->readSharedFmla();
  809. break;
  810. case self::XLS_TYPE_BOOLERR:
  811. $this->readBoolErr();
  812. break;
  813. case self::XLS_TYPE_MULBLANK:
  814. $this->readMulBlank();
  815. break;
  816. case self::XLS_TYPE_LABEL:
  817. $this->readLabel();
  818. break;
  819. case self::XLS_TYPE_BLANK:
  820. $this->readBlank();
  821. break;
  822. case self::XLS_TYPE_MSODRAWING:
  823. $this->readMsoDrawing();
  824. break;
  825. case self::XLS_TYPE_OBJ:
  826. $this->readObj();
  827. break;
  828. case self::XLS_TYPE_WINDOW2:
  829. $this->readWindow2();
  830. break;
  831. case self::XLS_TYPE_PAGELAYOUTVIEW:
  832. $this->readPageLayoutView();
  833. break;
  834. case self::XLS_TYPE_SCL:
  835. $this->readScl();
  836. break;
  837. case self::XLS_TYPE_PANE:
  838. $this->readPane();
  839. break;
  840. case self::XLS_TYPE_SELECTION:
  841. $this->readSelection();
  842. break;
  843. case self::XLS_TYPE_MERGEDCELLS:
  844. $this->readMergedCells();
  845. break;
  846. case self::XLS_TYPE_HYPERLINK:
  847. $this->readHyperLink();
  848. break;
  849. case self::XLS_TYPE_DATAVALIDATIONS:
  850. $this->readDataValidations();
  851. break;
  852. case self::XLS_TYPE_DATAVALIDATION:
  853. $this->readDataValidation();
  854. break;
  855. case self::XLS_TYPE_SHEETLAYOUT:
  856. $this->readSheetLayout();
  857. break;
  858. case self::XLS_TYPE_SHEETPROTECTION:
  859. $this->readSheetProtection();
  860. break;
  861. case self::XLS_TYPE_RANGEPROTECTION:
  862. $this->readRangeProtection();
  863. break;
  864. case self::XLS_TYPE_NOTE:
  865. $this->readNote();
  866. break;
  867. case self::XLS_TYPE_TXO:
  868. $this->readTextObject();
  869. break;
  870. case self::XLS_TYPE_CONTINUE:
  871. $this->readContinue();
  872. break;
  873. case self::XLS_TYPE_EOF:
  874. $this->readDefault();
  875. break 2;
  876. default:
  877. $this->readDefault();
  878. break;
  879. }
  880. }
  881. // treat MSODRAWING records, sheet-level Escher
  882. if (!$this->readDataOnly && $this->drawingData) {
  883. $escherWorksheet = new Escher();
  884. $reader = new Xls\Escher($escherWorksheet);
  885. $escherWorksheet = $reader->load($this->drawingData);
  886. // get all spContainers in one long array, so they can be mapped to OBJ records
  887. $allSpContainers = $escherWorksheet->getDgContainer()->getSpgrContainer()->getAllSpContainers();
  888. }
  889. // treat OBJ records
  890. foreach ($this->objs as $n => $obj) {
  891. // the first shape container never has a corresponding OBJ record, hence $n + 1
  892. if (isset($allSpContainers[$n + 1]) && is_object($allSpContainers[$n + 1])) {
  893. $spContainer = $allSpContainers[$n + 1];
  894. // we skip all spContainers that are a part of a group shape since we cannot yet handle those
  895. if ($spContainer->getNestingLevel() > 1) {
  896. continue;
  897. }
  898. // calculate the width and height of the shape
  899. list($startColumn, $startRow) = Coordinate::coordinateFromString($spContainer->getStartCoordinates());
  900. list($endColumn, $endRow) = Coordinate::coordinateFromString($spContainer->getEndCoordinates());
  901. $startOffsetX = $spContainer->getStartOffsetX();
  902. $startOffsetY = $spContainer->getStartOffsetY();
  903. $endOffsetX = $spContainer->getEndOffsetX();
  904. $endOffsetY = $spContainer->getEndOffsetY();
  905. $width = \PhpOffice\PhpSpreadsheet\Shared\Xls::getDistanceX($this->phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX);
  906. $height = \PhpOffice\PhpSpreadsheet\Shared\Xls::getDistanceY($this->phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY);
  907. // calculate offsetX and offsetY of the shape
  908. $offsetX = $startOffsetX * \PhpOffice\PhpSpreadsheet\Shared\Xls::sizeCol($this->phpSheet, $startColumn) / 1024;
  909. $offsetY = $startOffsetY * \PhpOffice\PhpSpreadsheet\Shared\Xls::sizeRow($this->phpSheet, $startRow) / 256;
  910. switch ($obj['otObjType']) {
  911. case 0x19:
  912. // Note
  913. if (isset($this->cellNotes[$obj['idObjID']])) {
  914. $cellNote = $this->cellNotes[$obj['idObjID']];
  915. if (isset($this->textObjects[$obj['idObjID']])) {
  916. $textObject = $this->textObjects[$obj['idObjID']];
  917. $this->cellNotes[$obj['idObjID']]['objTextData'] = $textObject;
  918. }
  919. }
  920. break;
  921. case 0x08:
  922. // picture
  923. // get index to BSE entry (1-based)
  924. $BSEindex = $spContainer->getOPT(0x0104);
  925. // If there is no BSE Index, we will fail here and other fields are not read.
  926. // Fix by checking here.
  927. // TODO: Why is there no BSE Index? Is this a new Office Version? Password protected field?
  928. // More likely : a uncompatible picture
  929. if (!$BSEindex) {
  930. continue 2;
  931. }
  932. $BSECollection = $escherWorkbook->getDggContainer()->getBstoreContainer()->getBSECollection();
  933. $BSE = $BSECollection[$BSEindex - 1];
  934. $blipType = $BSE->getBlipType();
  935. // need check because some blip types are not supported by Escher reader such as EMF
  936. if ($blip = $BSE->getBlip()) {
  937. $ih = imagecreatefromstring($blip->getData());
  938. $drawing = new MemoryDrawing();
  939. $drawing->setImageResource($ih);
  940. // width, height, offsetX, offsetY
  941. $drawing->setResizeProportional(false);
  942. $drawing->setWidth($width);
  943. $drawing->setHeight($height);
  944. $drawing->setOffsetX($offsetX);
  945. $drawing->setOffsetY($offsetY);
  946. switch ($blipType) {
  947. case BSE::BLIPTYPE_JPEG:
  948. $drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG);
  949. $drawing->setMimeType(MemoryDrawing::MIMETYPE_JPEG);
  950. break;
  951. case BSE::BLIPTYPE_PNG:
  952. $drawing->setRenderingFunction(MemoryDrawing::RENDERING_PNG);
  953. $drawing->setMimeType(MemoryDrawing::MIMETYPE_PNG);
  954. break;
  955. }
  956. $drawing->setWorksheet($this->phpSheet);
  957. $drawing->setCoordinates($spContainer->getStartCoordinates());
  958. }
  959. break;
  960. default:
  961. // other object type
  962. break;
  963. }
  964. }
  965. }
  966. // treat SHAREDFMLA records
  967. if ($this->version == self::XLS_BIFF8) {
  968. foreach ($this->sharedFormulaParts as $cell => $baseCell) {
  969. list($column, $row) = Coordinate::coordinateFromString($cell);
  970. if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($column, $row, $this->phpSheet->getTitle())) {
  971. $formula = $this->getFormulaFromStructure($this->sharedFormulas[$baseCell], $cell);
  972. $this->phpSheet->getCell($cell)->setValueExplicit('=' . $formula, DataType::TYPE_FORMULA);
  973. }
  974. }
  975. }
  976. if (!empty($this->cellNotes)) {
  977. foreach ($this->cellNotes as $note => $noteDetails) {
  978. if (!isset($noteDetails['objTextData'])) {
  979. if (isset($this->textObjects[$note])) {
  980. $textObject = $this->textObjects[$note];
  981. $noteDetails['objTextData'] = $textObject;
  982. } else {
  983. $noteDetails['objTextData']['text'] = '';
  984. }
  985. }
  986. $cellAddress = str_replace('$', '', $noteDetails['cellRef']);
  987. $this->phpSheet->getComment($cellAddress)->setAuthor($noteDetails['author'])->setText($this->parseRichText($noteDetails['objTextData']['text']));
  988. }
  989. }
  990. }
  991. // add the named ranges (defined names)
  992. foreach ($this->definedname as $definedName) {
  993. if ($definedName['isBuiltInName']) {
  994. switch ($definedName['name']) {
  995. case pack('C', 0x06):
  996. // print area
  997. // in general, formula looks like this: Foo!$C$7:$J$66,Bar!$A$1:$IV$2
  998. $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma?
  999. $extractedRanges = [];
  1000. foreach ($ranges as $range) {
  1001. // $range should look like one of these
  1002. // Foo!$C$7:$J$66
  1003. // Bar!$A$1:$IV$2
  1004. $explodes = Worksheet::extractSheetTitle($range, true);
  1005. $sheetName = trim($explodes[0], "'");
  1006. if (count($explodes) == 2) {
  1007. if (strpos($explodes[1], ':') === false) {
  1008. $explodes[1] = $explodes[1] . ':' . $explodes[1];
  1009. }
  1010. $extractedRanges[] = str_replace('$', '', $explodes[1]); // C7:J66
  1011. }
  1012. }
  1013. if ($docSheet = $this->spreadsheet->getSheetByName($sheetName)) {
  1014. $docSheet->getPageSetup()->setPrintArea(implode(',', $extractedRanges)); // C7:J66,A1:IV2
  1015. }
  1016. break;
  1017. case pack('C', 0x07):
  1018. // print titles (repeating rows)
  1019. // Assuming BIFF8, there are 3 cases
  1020. // 1. repeating rows
  1021. // formula looks like this: Sheet!$A$1:$IV$2
  1022. // rows 1-2 repeat
  1023. // 2. repeating columns
  1024. // formula looks like this: Sheet!$A$1:$B$65536
  1025. // columns A-B repeat
  1026. // 3. both repeating rows and repeating columns
  1027. // formula looks like this: Sheet!$A$1:$B$65536,Sheet!$A$1:$IV$2
  1028. $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma?
  1029. foreach ($ranges as $range) {
  1030. // $range should look like this one of these
  1031. // Sheet!$A$1:$B$65536
  1032. // Sheet!$A$1:$IV$2
  1033. if (strpos($range, '!') !== false) {
  1034. $explodes = Worksheet::extractSheetTitle($range, true);
  1035. if ($docSheet = $this->spreadsheet->getSheetByName($explodes[0])) {
  1036. $extractedRange = $explodes[1];
  1037. $extractedRange = str_replace('$', '', $extractedRange);
  1038. $coordinateStrings = explode(':', $extractedRange);
  1039. if (count($coordinateStrings) == 2) {
  1040. list($firstColumn, $firstRow) = Coordinate::coordinateFromString($coordinateStrings[0]);
  1041. list($lastColumn, $lastRow) = Coordinate::coordinateFromString($coordinateStrings[1]);
  1042. if ($firstColumn == 'A' and $lastColumn == 'IV') {
  1043. // then we have repeating rows
  1044. $docSheet->getPageSetup()->setRowsToRepeatAtTop([$firstRow, $lastRow]);
  1045. } elseif ($firstRow == 1 and $lastRow == 65536) {
  1046. // then we have repeating columns
  1047. $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$firstColumn, $lastColumn]);
  1048. }
  1049. }
  1050. }
  1051. }
  1052. }
  1053. break;
  1054. }
  1055. } else {
  1056. // Extract range
  1057. if (strpos($definedName['formula'], '!') !== false) {
  1058. $explodes = Worksheet::extractSheetTitle($definedName['formula'], true);
  1059. if (($docSheet = $this->spreadsheet->getSheetByName($explodes[0])) ||
  1060. ($docSheet = $this->spreadsheet->getSheetByName(trim($explodes[0], "'")))) {
  1061. $extractedRange = $explodes[1];
  1062. $extractedRange = str_replace('$', '', $extractedRange);
  1063. $localOnly = ($definedName['scope'] == 0) ? false : true;
  1064. $scope = ($definedName['scope'] == 0) ? null : $this->spreadsheet->getSheetByName($this->sheets[$definedName['scope'] - 1]['name']);
  1065. $this->spreadsheet->addNamedRange(new NamedRange((string) $definedName['name'], $docSheet, $extractedRange, $localOnly, $scope));
  1066. }
  1067. }
  1068. // Named Value
  1069. // TODO Provide support for named values
  1070. }
  1071. }
  1072. $this->data = null;
  1073. return $this->spreadsheet;
  1074. }
  1075. /**
  1076. * Read record data from stream, decrypting as required.
  1077. *
  1078. * @param string $data Data stream to read from
  1079. * @param int $pos Position to start reading from
  1080. * @param int $len Record data length
  1081. *
  1082. * @return string Record data
  1083. */
  1084. private function readRecordData($data, $pos, $len)
  1085. {
  1086. $data = substr($data, $pos, $len);
  1087. // File not encrypted, or record before encryption start point
  1088. if ($this->encryption == self::MS_BIFF_CRYPTO_NONE || $pos < $this->encryptionStartPos) {
  1089. return $data;
  1090. }
  1091. $recordData = '';
  1092. if ($this->encryption == self::MS_BIFF_CRYPTO_RC4) {
  1093. $oldBlock = floor($this->rc4Pos / self::REKEY_BLOCK);
  1094. $block = floor($pos / self::REKEY_BLOCK);
  1095. $endBlock = floor(($pos + $len) / self::REKEY_BLOCK);
  1096. // Spin an RC4 decryptor to the right spot. If we have a decryptor sitting
  1097. // at a point earlier in the current block, re-use it as we can save some time.
  1098. if ($block != $oldBlock || $pos < $this->rc4Pos || !$this->rc4Key) {
  1099. $this->rc4Key = $this->makeKey($block, $this->md5Ctxt);
  1100. $step = $pos % self::REKEY_BLOCK;
  1101. } else {
  1102. $step = $pos - $this->rc4Pos;
  1103. }
  1104. $this->rc4Key->RC4(str_repeat("\0", $step));
  1105. // Decrypt record data (re-keying at the end of every block)
  1106. while ($block != $endBlock) {
  1107. $step = self::REKEY_BLOCK - ($pos % self::REKEY_BLOCK);
  1108. $recordData .= $this->rc4Key->RC4(substr($data, 0, $step));
  1109. $data = substr($data, $step);
  1110. $pos += $step;
  1111. $len -= $step;
  1112. ++$block;
  1113. $this->rc4Key = $this->makeKey($block, $this->md5Ctxt);
  1114. }
  1115. $recordData .= $this->rc4Key->RC4(substr($data, 0, $len));
  1116. // Keep track of the position of this decryptor.
  1117. // We'll try and re-use it later if we can to speed things up
  1118. $this->rc4Pos = $pos + $len;
  1119. } elseif ($this->encryption == self::MS_BIFF_CRYPTO_XOR) {
  1120. throw new Exception('XOr encryption not supported');
  1121. }
  1122. return $recordData;
  1123. }
  1124. /**
  1125. * Use OLE reader to extract the relevant data streams from the OLE file.
  1126. *
  1127. * @param string $pFilename
  1128. */
  1129. private function loadOLE($pFilename)
  1130. {
  1131. // OLE reader
  1132. $ole = new OLERead();
  1133. // get excel data,
  1134. $ole->read($pFilename);
  1135. // Get workbook data: workbook stream + sheet streams
  1136. $this->data = $ole->getStream($ole->wrkbook);
  1137. // Get summary information data
  1138. $this->summaryInformation = $ole->getStream($ole->summaryInformation);
  1139. // Get additional document summary information data
  1140. $this->documentSummaryInformation = $ole->getStream($ole->documentSummaryInformation);
  1141. }
  1142. /**
  1143. * Read summary information.
  1144. */
  1145. private function readSummaryInformation()
  1146. {
  1147. if (!isset($this->summaryInformation)) {
  1148. return;
  1149. }
  1150. // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
  1151. // offset: 2; size: 2;
  1152. // offset: 4; size: 2; OS version
  1153. // offset: 6; size: 2; OS indicator
  1154. // offset: 8; size: 16
  1155. // offset: 24; size: 4; section count
  1156. $secCount = self::getInt4d($this->summaryInformation, 24);
  1157. // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9
  1158. // offset: 44; size: 4
  1159. $secOffset = self::getInt4d($this->summaryInformation, 44);
  1160. // section header
  1161. // offset: $secOffset; size: 4; section length
  1162. $secLength = self::getInt4d($this->summaryInformation, $secOffset);
  1163. // offset: $secOffset+4; size: 4; property count
  1164. $countProperties = self::getInt4d($this->summaryInformation, $secOffset + 4);
  1165. // initialize code page (used to resolve string values)
  1166. $codePage = 'CP1252';
  1167. // offset: ($secOffset+8); size: var
  1168. // loop through property decarations and properties
  1169. for ($i = 0; $i < $countProperties; ++$i) {
  1170. // offset: ($secOffset+8) + (8 * $i); size: 4; property ID
  1171. $id = self::getInt4d($this->summaryInformation, ($secOffset + 8) + (8 * $i));
  1172. // Use value of property id as appropriate
  1173. // offset: ($secOffset+12) + (8 * $i); size: 4; offset from beginning of section (48)
  1174. $offset = self::getInt4d($this->summaryInformation, ($secOffset + 12) + (8 * $i));
  1175. $type = self::getInt4d($this->summaryInformation, $secOffset + $offset);
  1176. // initialize property value
  1177. $value = null;
  1178. // extract property value based on property type
  1179. switch ($type) {
  1180. case 0x02: // 2 byte signed integer
  1181. $value = self::getUInt2d($this->summaryInformation, $secOffset + 4 + $offset);
  1182. break;
  1183. case 0x03: // 4 byte signed integer
  1184. $value = self::getInt4d($this->summaryInformation, $secOffset + 4 + $offset);
  1185. break;
  1186. case 0x13: // 4 byte unsigned integer
  1187. // not needed yet, fix later if necessary
  1188. break;
  1189. case 0x1E: // null-terminated string prepended by dword string length
  1190. $byteLength = self::getInt4d($this->summaryInformation, $secOffset + 4 + $offset);
  1191. $value = substr($this->summaryInformation, $secOffset + 8 + $offset, $byteLength);
  1192. $value = StringHelper::convertEncoding($value, 'UTF-8', $codePage);
  1193. $value = rtrim($value);
  1194. break;
  1195. case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
  1196. // PHP-time
  1197. $value = OLE::OLE2LocalDate(substr($this->summaryInformation, $secOffset + 4 + $offset, 8));
  1198. break;
  1199. case 0x47: // Clipboard format
  1200. // not needed yet, fix later if necessary
  1201. break;
  1202. }
  1203. switch ($id) {
  1204. case 0x01: // Code Page
  1205. $codePage = CodePage::numberToName($value);
  1206. break;
  1207. case 0x02: // Title
  1208. $this->spreadsheet->getProperties()->setTitle($value);
  1209. break;
  1210. case 0x03: // Subject
  1211. $this->spreadsheet->getProperties()->setSubject($value);
  1212. break;
  1213. case 0x04: // Author (Creator)
  1214. $this->spreadsheet->getProperties()->setCreator($value);
  1215. break;
  1216. case 0x05: // Keywords
  1217. $this->spreadsheet->getProperties()->setKeywords($value);
  1218. break;
  1219. case 0x06: // Comments (Description)
  1220. $this->spreadsheet->getProperties()->setDescription($value);
  1221. break;
  1222. case 0x07: // Template
  1223. // Not supported by PhpSpreadsheet
  1224. break;
  1225. case 0x08: // Last Saved By (LastModifiedBy)
  1226. $this->spreadsheet->getProperties()->setLastModifiedBy($value);
  1227. break;
  1228. case 0x09: // Revision
  1229. // Not supported by PhpSpreadsheet
  1230. break;
  1231. case 0x0A: // Total Editing Time
  1232. // Not supported by PhpSpreadsheet
  1233. break;
  1234. case 0x0B: // Last Printed
  1235. // Not supported by PhpSpreadsheet
  1236. break;
  1237. case 0x0C: // Created Date/Time
  1238. $this->spreadsheet->getProperties()->setCreated($value);
  1239. break;
  1240. case 0x0D: // Modified Date/Time
  1241. $this->spreadsheet->getProperties()->setModified($value);
  1242. break;
  1243. case 0x0E: // Number of Pages
  1244. // Not supported by PhpSpreadsheet
  1245. break;
  1246. case 0x0F: // Number of Words
  1247. // Not supported by PhpSpreadsheet
  1248. break;
  1249. case 0x10: // Number of Characters
  1250. // Not supported by PhpSpreadsheet
  1251. break;
  1252. case 0x11: // Thumbnail
  1253. // Not supported by PhpSpreadsheet
  1254. break;
  1255. case 0x12: // Name of creating application
  1256. // Not supported by PhpSpreadsheet
  1257. break;
  1258. case 0x13: // Security
  1259. // Not supported by PhpSpreadsheet
  1260. break;
  1261. }
  1262. }
  1263. }
  1264. /**
  1265. * Read additional document summary information.
  1266. */
  1267. private function readDocumentSummaryInformation()
  1268. {
  1269. if (!isset($this->documentSummaryInformation)) {
  1270. return;
  1271. }
  1272. // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark)
  1273. // offset: 2; size: 2;
  1274. // offset: 4; size: 2; OS version
  1275. // offset: 6; size: 2; OS indicator
  1276. // offset: 8; size: 16
  1277. // offset: 24; size: 4; section count
  1278. $secCount = self::getInt4d($this->documentSummaryInformation, 24);
  1279. // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae
  1280. // offset: 44; size: 4; first section offset
  1281. $secOffset = self::getInt4d($this->documentSummaryInformation, 44);
  1282. // section header
  1283. // offset: $secOffset; size: 4; section length
  1284. $secLength = self::getInt4d($this->documentSummaryInformation, $secOffset);
  1285. // offset: $secOffset+4; size: 4; property count
  1286. $countProperties = self::getInt4d($this->documentSummaryInformation, $secOffset + 4);
  1287. // initialize code page (used to resolve string values)
  1288. $codePage = 'CP1252';
  1289. // offset: ($secOffset+8); size: var
  1290. // loop through property decarations and properties
  1291. for ($i = 0; $i < $countProperties; ++$i) {
  1292. // offset: ($secOffset+8) + (8 * $i); size: 4; property ID
  1293. $id = self::getInt4d($this->documentSummaryInformation, ($secOffset + 8) + (8 * $i));
  1294. // Use value of property id as appropriate
  1295. // offset: 60 + 8 * $i; size: 4; offset from beginning of section (48)
  1296. $offset = self::getInt4d($this->documentSummaryInformation, ($secOffset + 12) + (8 * $i));
  1297. $type = self::getInt4d($this->documentSummaryInformation, $secOffset + $offset);
  1298. // initialize property value
  1299. $value = null;
  1300. // extract property value based on property type
  1301. switch ($type) {
  1302. case 0x02: // 2 byte signed integer
  1303. $value = self::getUInt2d($this->documentSummaryInformation, $secOffset + 4 + $offset);
  1304. break;
  1305. case 0x03: // 4 byte signed integer
  1306. $value = self::getInt4d($this->documentSummaryInformation, $secOffset + 4 + $offset);
  1307. break;
  1308. case 0x0B: // Boolean
  1309. $value = self::getUInt2d($this->documentSummaryInformation, $secOffset + 4 + $offset);
  1310. $value = ($value == 0 ? false : true);
  1311. break;
  1312. case 0x13: // 4 byte unsigned integer
  1313. // not needed yet, fix later if necessary
  1314. break;
  1315. case 0x1E: // null-terminated string prepended by dword string length
  1316. $byteLength = self::getInt4d($this->documentSummaryInformation, $secOffset + 4 + $offset);
  1317. $value = substr($this->documentSummaryInformation, $secOffset + 8 + $offset, $byteLength);
  1318. $value = StringHelper::convertEncoding($value, 'UTF-8', $codePage);
  1319. $value = rtrim($value);
  1320. break;
  1321. case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601)
  1322. // PHP-Time
  1323. $value = OLE::OLE2LocalDate(substr($this->documentSummaryInformation, $secOffset + 4 + $offset, 8));
  1324. break;
  1325. case 0x47: // Clipboard format
  1326. // not needed yet, fix later if necessary
  1327. break;
  1328. }
  1329. switch ($id) {
  1330. case 0x01: // Code Page
  1331. $codePage = CodePage::numberToName($value);
  1332. break;
  1333. case 0x02: // Category
  1334. $this->spreadsheet->getProperties()->setCategory($value);
  1335. break;
  1336. case 0x03: // Presentation Target
  1337. // Not supported by PhpSpreadsheet
  1338. break;
  1339. case 0x04: // Bytes
  1340. // Not supported by PhpSpreadsheet
  1341. break;
  1342. case 0x05: // Lines
  1343. // Not supported by PhpSpreadsheet
  1344. break;
  1345. case 0x06: // Paragraphs
  1346. // Not supported by PhpSpreadsheet
  1347. break;
  1348. case 0x07: // Slides
  1349. // Not supported by PhpSpreadsheet
  1350. break;
  1351. case 0x08: // Notes
  1352. // Not supported by PhpSpreadsheet
  1353. break;
  1354. case 0x09: // Hidden Slides
  1355. // Not supported by PhpSpreadsheet
  1356. break;
  1357. case 0x0A: // MM Clips
  1358. // Not supported by PhpSpreadsheet
  1359. break;
  1360. case 0x0B: // Scale Crop
  1361. // Not supported by PhpSpreadsheet
  1362. break;
  1363. case 0x0C: // Heading Pairs
  1364. // Not supported by PhpSpreadsheet
  1365. break;
  1366. case 0x0D: // Titles of Parts
  1367. // Not supported by PhpSpreadsheet
  1368. break;
  1369. case 0x0E: // Manager
  1370. $this->spreadsheet->getProperties()->setManager($value);
  1371. break;
  1372. case 0x0F: // Company
  1373. $this->spreadsheet->getProperties()->setCompany($value);
  1374. break;
  1375. case 0x10: // Links up-to-date
  1376. // Not supported by PhpSpreadsheet
  1377. break;
  1378. }
  1379. }
  1380. }
  1381. /**
  1382. * Reads a general type of BIFF record. Does nothing except for moving stream pointer forward to next record.
  1383. */
  1384. private function readDefault()
  1385. {
  1386. $length = self::getUInt2d($this->data, $this->pos + 2);
  1387. // move stream pointer to next record
  1388. $this->pos += 4 + $length;
  1389. }
  1390. /**
  1391. * The NOTE record specifies a comment associated with a particular cell. In Excel 95 (BIFF7) and earlier versions,
  1392. * this record stores a note (cell note). This feature was significantly enhanced in Excel 97.
  1393. */
  1394. private function readNote()
  1395. {
  1396. $length = self::getUInt2d($this->data, $this->pos + 2);
  1397. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  1398. // move stream pointer to next record
  1399. $this->pos += 4 + $length;
  1400. if ($this->readDataOnly) {
  1401. return;
  1402. }
  1403. $cellAddress = $this->readBIFF8CellAddress(substr($recordData, 0, 4));
  1404. if ($this->version == self::XLS_BIFF8) {
  1405. $noteObjID = self::getUInt2d($recordData, 6);
  1406. $noteAuthor = self::readUnicodeStringLong(substr($recordData, 8));
  1407. $noteAuthor = $noteAuthor['value'];
  1408. $this->cellNotes[$noteObjID] = [
  1409. 'cellRef' => $cellAddress,
  1410. 'objectID' => $noteObjID,
  1411. 'author' => $noteAuthor,
  1412. ];
  1413. } else {
  1414. $extension = false;
  1415. if ($cellAddress == '$B$65536') {
  1416. // If the address row is -1 and the column is 0, (which translates as $B$65536) then this is a continuation
  1417. // note from the previous cell annotation. We're not yet handling this, so annotations longer than the
  1418. // max 2048 bytes will probably throw a wobbly.
  1419. $row = self::getUInt2d($recordData, 0);
  1420. $extension = true;
  1421. $cellAddress = array_pop(array_keys($this->phpSheet->getComments()));
  1422. }
  1423. $cellAddress = str_replace('$', '', $cellAddress);
  1424. $noteLength = self::getUInt2d($recordData, 4);
  1425. $noteText = trim(substr($recordData, 6));
  1426. if ($extension) {
  1427. // Concatenate this extension with the currently set comment for the cell
  1428. $comment = $this->phpSheet->getComment($cellAddress);
  1429. $commentText = $comment->getText()->getPlainText();
  1430. $comment->setText($this->parseRichText($commentText . $noteText));
  1431. } else {
  1432. // Set comment for the cell
  1433. $this->phpSheet->getComment($cellAddress)->setText($this->parseRichText($noteText));
  1434. // ->setAuthor($author)
  1435. }
  1436. }
  1437. }
  1438. /**
  1439. * The TEXT Object record contains the text associated with a cell annotation.
  1440. */
  1441. private function readTextObject()
  1442. {
  1443. $length = self::getUInt2d($this->data, $this->pos + 2);
  1444. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  1445. // move stream pointer to next record
  1446. $this->pos += 4 + $length;
  1447. if ($this->readDataOnly) {
  1448. return;
  1449. }
  1450. // recordData consists of an array of subrecords looking like this:
  1451. // grbit: 2 bytes; Option Flags
  1452. // rot: 2 bytes; rotation
  1453. // cchText: 2 bytes; length of the text (in the first continue record)
  1454. // cbRuns: 2 bytes; length of the formatting (in the second continue record)
  1455. // followed by the continuation records containing the actual text and formatting
  1456. $grbitOpts = self::getUInt2d($recordData, 0);
  1457. $rot = self::getUInt2d($recordData, 2);
  1458. $cchText = self::getUInt2d($recordData, 10);
  1459. $cbRuns = self::getUInt2d($recordData, 12);
  1460. $text = $this->getSplicedRecordData();
  1461. $textByte = $text['spliceOffsets'][1] - $text['spliceOffsets'][0] - 1;
  1462. $textStr = substr($text['recordData'], $text['spliceOffsets'][0] + 1, $textByte);
  1463. // get 1 byte
  1464. $is16Bit = ord($text['recordData'][0]);
  1465. // it is possible to use a compressed format,
  1466. // which omits the high bytes of all characters, if they are all zero
  1467. if (($is16Bit & 0x01) === 0) {
  1468. $textStr = StringHelper::ConvertEncoding($textStr, 'UTF-8', 'ISO-8859-1');
  1469. } else {
  1470. $textStr = $this->decodeCodepage($textStr);
  1471. }
  1472. $this->textObjects[$this->textObjRef] = [
  1473. 'text' => $textStr,
  1474. 'format' => substr($text['recordData'], $text['spliceOffsets'][1], $cbRuns),
  1475. 'alignment' => $grbitOpts,
  1476. 'rotation' => $rot,
  1477. ];
  1478. }
  1479. /**
  1480. * Read BOF.
  1481. */
  1482. private function readBof()
  1483. {
  1484. $length = self::getUInt2d($this->data, $this->pos + 2);
  1485. $recordData = substr($this->data, $this->pos + 4, $length);
  1486. // move stream pointer to next record
  1487. $this->pos += 4 + $length;
  1488. // offset: 2; size: 2; type of the following data
  1489. $substreamType = self::getUInt2d($recordData, 2);
  1490. switch ($substreamType) {
  1491. case self::XLS_WORKBOOKGLOBALS:
  1492. $version = self::getUInt2d($recordData, 0);
  1493. if (($version != self::XLS_BIFF8) && ($version != self::XLS_BIFF7)) {
  1494. throw new Exception('Cannot read this Excel file. Version is too old.');
  1495. }
  1496. $this->version = $version;
  1497. break;
  1498. case self::XLS_WORKSHEET:
  1499. // do not use this version information for anything
  1500. // it is unreliable (OpenOffice doc, 5.8), use only version information from the global stream
  1501. break;
  1502. default:
  1503. // substream, e.g. chart
  1504. // just skip the entire substream
  1505. do {
  1506. $code = self::getUInt2d($this->data, $this->pos);
  1507. $this->readDefault();
  1508. } while ($code != self::XLS_TYPE_EOF && $this->pos < $this->dataSize);
  1509. break;
  1510. }
  1511. }
  1512. /**
  1513. * FILEPASS.
  1514. *
  1515. * This record is part of the File Protection Block. It
  1516. * contains information about the read/write password of the
  1517. * file. All record contents following this record will be
  1518. * encrypted.
  1519. *
  1520. * -- "OpenOffice.org's Documentation of the Microsoft
  1521. * Excel File Format"
  1522. *
  1523. * The decryption functions and objects used from here on in
  1524. * are based on the source of Spreadsheet-ParseExcel:
  1525. * https://metacpan.org/release/Spreadsheet-ParseExcel
  1526. */
  1527. private function readFilepass()
  1528. {
  1529. $length = self::getUInt2d($this->data, $this->pos + 2);
  1530. if ($length != 54) {
  1531. throw new Exception('Unexpected file pass record length');
  1532. }
  1533. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  1534. // move stream pointer to next record
  1535. $this->pos += 4 + $length;
  1536. if (!$this->verifyPassword('VelvetSweatshop', substr($recordData, 6, 16), substr($recordData, 22, 16), substr($recordData, 38, 16), $this->md5Ctxt)) {
  1537. throw new Exception('Decryption password incorrect');
  1538. }
  1539. $this->encryption = self::MS_BIFF_CRYPTO_RC4;
  1540. // Decryption required from the record after next onwards
  1541. $this->encryptionStartPos = $this->pos + self::getUInt2d($this->data, $this->pos + 2);
  1542. }
  1543. /**
  1544. * Make an RC4 decryptor for the given block.
  1545. *
  1546. * @param int $block Block for which to create decrypto
  1547. * @param string $valContext MD5 context state
  1548. *
  1549. * @return Xls\RC4
  1550. */
  1551. private function makeKey($block, $valContext)
  1552. {
  1553. $pwarray = str_repeat("\0", 64);
  1554. for ($i = 0; $i < 5; ++$i) {
  1555. $pwarray[$i] = $valContext[$i];
  1556. }
  1557. $pwarray[5] = chr($block & 0xff);
  1558. $pwarray[6] = chr(($block >> 8) & 0xff);
  1559. $pwarray[7] = chr(($block >> 16) & 0xff);
  1560. $pwarray[8] = chr(($block >> 24) & 0xff);
  1561. $pwarray[9] = "\x80";
  1562. $pwarray[56] = "\x48";
  1563. $md5 = new Xls\MD5();
  1564. $md5->add($pwarray);
  1565. $s = $md5->getContext();
  1566. return new Xls\RC4($s);
  1567. }
  1568. /**
  1569. * Verify RC4 file password.
  1570. *
  1571. * @param string $password Password to check
  1572. * @param string $docid Document id
  1573. * @param string $salt_data Salt data
  1574. * @param string $hashedsalt_data Hashed salt data
  1575. * @param string $valContext Set to the MD5 context of the value
  1576. *
  1577. * @return bool Success
  1578. */
  1579. private function verifyPassword($password, $docid, $salt_data, $hashedsalt_data, &$valContext)
  1580. {
  1581. $pwarray = str_repeat("\0", 64);
  1582. $iMax = strlen($password);
  1583. for ($i = 0; $i < $iMax; ++$i) {
  1584. $o = ord(substr($password, $i, 1));
  1585. $pwarray[2 * $i] = chr($o & 0xff);
  1586. $pwarray[2 * $i + 1] = chr(($o >> 8) & 0xff);
  1587. }
  1588. $pwarray[2 * $i] = chr(0x80);
  1589. $pwarray[56] = chr(($i << 4) & 0xff);
  1590. $md5 = new Xls\MD5();
  1591. $md5->add($pwarray);
  1592. $mdContext1 = $md5->getContext();
  1593. $offset = 0;
  1594. $keyoffset = 0;
  1595. $tocopy = 5;
  1596. $md5->reset();
  1597. while ($offset != 16) {
  1598. if ((64 - $offset) < 5) {
  1599. $tocopy = 64 - $offset;
  1600. }
  1601. for ($i = 0; $i <= $tocopy; ++$i) {
  1602. $pwarray[$offset + $i] = $mdContext1[$keyoffset + $i];
  1603. }
  1604. $offset += $tocopy;
  1605. if ($offset == 64) {
  1606. $md5->add($pwarray);
  1607. $keyoffset = $tocopy;
  1608. $tocopy = 5 - $tocopy;
  1609. $offset = 0;
  1610. continue;
  1611. }
  1612. $keyoffset = 0;
  1613. $tocopy = 5;
  1614. for ($i = 0; $i < 16; ++$i) {
  1615. $pwarray[$offset + $i] = $docid[$i];
  1616. }
  1617. $offset += 16;
  1618. }
  1619. $pwarray[16] = "\x80";
  1620. for ($i = 0; $i < 47; ++$i) {
  1621. $pwarray[17 + $i] = "\0";
  1622. }
  1623. $pwarray[56] = "\x80";
  1624. $pwarray[57] = "\x0a";
  1625. $md5->add($pwarray);
  1626. $valContext = $md5->getContext();
  1627. $key = $this->makeKey(0, $valContext);
  1628. $salt = $key->RC4($salt_data);
  1629. $hashedsalt = $key->RC4($hashedsalt_data);
  1630. $salt .= "\x80" . str_repeat("\0", 47);
  1631. $salt[56] = "\x80";
  1632. $md5->reset();
  1633. $md5->add($salt);
  1634. $mdContext2 = $md5->getContext();
  1635. return $mdContext2 == $hashedsalt;
  1636. }
  1637. /**
  1638. * CODEPAGE.
  1639. *
  1640. * This record stores the text encoding used to write byte
  1641. * strings, stored as MS Windows code page identifier.
  1642. *
  1643. * -- "OpenOffice.org's Documentation of the Microsoft
  1644. * Excel File Format"
  1645. */
  1646. private function readCodepage()
  1647. {
  1648. $length = self::getUInt2d($this->data, $this->pos + 2);
  1649. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  1650. // move stream pointer to next record
  1651. $this->pos += 4 + $length;
  1652. // offset: 0; size: 2; code page identifier
  1653. $codepage = self::getUInt2d($recordData, 0);
  1654. $this->codepage = CodePage::numberToName($codepage);
  1655. }
  1656. /**
  1657. * DATEMODE.
  1658. *
  1659. * This record specifies the base date for displaying date
  1660. * values. All dates are stored as count of days past this
  1661. * base date. In BIFF2-BIFF4 this record is part of the
  1662. * Calculation Settings Block. In BIFF5-BIFF8 it is
  1663. * stored in the Workbook Globals Substream.
  1664. *
  1665. * -- "OpenOffice.org's Documentation of the Microsoft
  1666. * Excel File Format"
  1667. */
  1668. private function readDateMode()
  1669. {
  1670. $length = self::getUInt2d($this->data, $this->pos + 2);
  1671. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  1672. // move stream pointer to next record
  1673. $this->pos += 4 + $length;
  1674. // offset: 0; size: 2; 0 = base 1900, 1 = base 1904
  1675. Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
  1676. if (ord($recordData[0]) == 1) {
  1677. Date::setExcelCalendar(Date::CALENDAR_MAC_1904);
  1678. }
  1679. }
  1680. /**
  1681. * Read a FONT record.
  1682. */
  1683. private function readFont()
  1684. {
  1685. $length = self::getUInt2d($this->data, $this->pos + 2);
  1686. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  1687. // move stream pointer to next record
  1688. $this->pos += 4 + $length;
  1689. if (!$this->readDataOnly) {
  1690. $objFont = new Font();
  1691. // offset: 0; size: 2; height of the font (in twips = 1/20 of a point)
  1692. $size = self::getUInt2d($recordData, 0);
  1693. $objFont->setSize($size / 20);
  1694. // offset: 2; size: 2; option flags
  1695. // bit: 0; mask 0x0001; bold (redundant in BIFF5-BIFF8)
  1696. // bit: 1; mask 0x0002; italic
  1697. $isItalic = (0x0002 & self::getUInt2d($recordData, 2)) >> 1;
  1698. if ($isItalic) {
  1699. $objFont->setItalic(true);
  1700. }
  1701. // bit: 2; mask 0x0004; underlined (redundant in BIFF5-BIFF8)
  1702. // bit: 3; mask 0x0008; strikethrough
  1703. $isStrike = (0x0008 & self::getUInt2d($recordData, 2)) >> 3;
  1704. if ($isStrike) {
  1705. $objFont->setStrikethrough(true);
  1706. }
  1707. // offset: 4; size: 2; colour index
  1708. $colorIndex = self::getUInt2d($recordData, 4);
  1709. $objFont->colorIndex = $colorIndex;
  1710. // offset: 6; size: 2; font weight
  1711. $weight = self::getUInt2d($recordData, 6);
  1712. switch ($weight) {
  1713. case 0x02BC:
  1714. $objFont->setBold(true);
  1715. break;
  1716. }
  1717. // offset: 8; size: 2; escapement type
  1718. $escapement = self::getUInt2d($recordData, 8);
  1719. switch ($escapement) {
  1720. case 0x0001:
  1721. $objFont->setSuperscript(true);
  1722. break;
  1723. case 0x0002:
  1724. $objFont->setSubscript(true);
  1725. break;
  1726. }
  1727. // offset: 10; size: 1; underline type
  1728. $underlineType = ord($recordData[10]);
  1729. switch ($underlineType) {
  1730. case 0x00:
  1731. break; // no underline
  1732. case 0x01:
  1733. $objFont->setUnderline(Font::UNDERLINE_SINGLE);
  1734. break;
  1735. case 0x02:
  1736. $objFont->setUnderline(Font::UNDERLINE_DOUBLE);
  1737. break;
  1738. case 0x21:
  1739. $objFont->setUnderline(Font::UNDERLINE_SINGLEACCOUNTING);
  1740. break;
  1741. case 0x22:
  1742. $objFont->setUnderline(Font::UNDERLINE_DOUBLEACCOUNTING);
  1743. break;
  1744. }
  1745. // offset: 11; size: 1; font family
  1746. // offset: 12; size: 1; character set
  1747. // offset: 13; size: 1; not used
  1748. // offset: 14; size: var; font name
  1749. if ($this->version == self::XLS_BIFF8) {
  1750. $string = self::readUnicodeStringShort(substr($recordData, 14));
  1751. } else {
  1752. $string = $this->readByteStringShort(substr($recordData, 14));
  1753. }
  1754. $objFont->setName($string['value']);
  1755. $this->objFonts[] = $objFont;
  1756. }
  1757. }
  1758. /**
  1759. * FORMAT.
  1760. *
  1761. * This record contains information about a number format.
  1762. * All FORMAT records occur together in a sequential list.
  1763. *
  1764. * In BIFF2-BIFF4 other records referencing a FORMAT record
  1765. * contain a zero-based index into this list. From BIFF5 on
  1766. * the FORMAT record contains the index itself that will be
  1767. * used by other records.
  1768. *
  1769. * -- "OpenOffice.org's Documentation of the Microsoft
  1770. * Excel File Format"
  1771. */
  1772. private function readFormat()
  1773. {
  1774. $length = self::getUInt2d($this->data, $this->pos + 2);
  1775. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  1776. // move stream pointer to next record
  1777. $this->pos += 4 + $length;
  1778. if (!$this->readDataOnly) {
  1779. $indexCode = self::getUInt2d($recordData, 0);
  1780. if ($this->version == self::XLS_BIFF8) {
  1781. $string = self::readUnicodeStringLong(substr($recordData, 2));
  1782. } else {
  1783. // BIFF7
  1784. $string = $this->readByteStringShort(substr($recordData, 2));
  1785. }
  1786. $formatString = $string['value'];
  1787. $this->formats[$indexCode] = $formatString;
  1788. }
  1789. }
  1790. /**
  1791. * XF - Extended Format.
  1792. *
  1793. * This record contains formatting information for cells, rows, columns or styles.
  1794. * According to https://support.microsoft.com/en-us/help/147732 there are always at least 15 cell style XF
  1795. * and 1 cell XF.
  1796. * Inspection of Excel files generated by MS Office Excel shows that XF records 0-14 are cell style XF
  1797. * and XF record 15 is a cell XF
  1798. * We only read the first cell style XF and skip the remaining cell style XF records
  1799. * We read all cell XF records.
  1800. *
  1801. * -- "OpenOffice.org's Documentation of the Microsoft
  1802. * Excel File Format"
  1803. */
  1804. private function readXf()
  1805. {
  1806. $length = self::getUInt2d($this->data, $this->pos + 2);
  1807. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  1808. // move stream pointer to next record
  1809. $this->pos += 4 + $length;
  1810. $objStyle = new Style();
  1811. if (!$this->readDataOnly) {
  1812. // offset: 0; size: 2; Index to FONT record
  1813. if (self::getUInt2d($recordData, 0) < 4) {
  1814. $fontIndex = self::getUInt2d($recordData, 0);
  1815. } else {
  1816. // this has to do with that index 4 is omitted in all BIFF versions for some strange reason
  1817. // check the OpenOffice documentation of the FONT record
  1818. $fontIndex = self::getUInt2d($recordData, 0) - 1;
  1819. }
  1820. $objStyle->setFont($this->objFonts[$fontIndex]);
  1821. // offset: 2; size: 2; Index to FORMAT record
  1822. $numberFormatIndex = self::getUInt2d($recordData, 2);
  1823. if (isset($this->formats[$numberFormatIndex])) {
  1824. // then we have user-defined format code
  1825. $numberFormat = ['formatCode' => $this->formats[$numberFormatIndex]];
  1826. } elseif (($code = NumberFormat::builtInFormatCode($numberFormatIndex)) !== '') {
  1827. // then we have built-in format code
  1828. $numberFormat = ['formatCode' => $code];
  1829. } else {
  1830. // we set the general format code
  1831. $numberFormat = ['formatCode' => 'General'];
  1832. }
  1833. $objStyle->getNumberFormat()->setFormatCode($numberFormat['formatCode']);
  1834. // offset: 4; size: 2; XF type, cell protection, and parent style XF
  1835. // bit 2-0; mask 0x0007; XF_TYPE_PROT
  1836. $xfTypeProt = self::getUInt2d($recordData, 4);
  1837. // bit 0; mask 0x01; 1 = cell is locked
  1838. $isLocked = (0x01 & $xfTypeProt) >> 0;
  1839. $objStyle->getProtection()->setLocked($isLocked ? Protection::PROTECTION_INHERIT : Protection::PROTECTION_UNPROTECTED);
  1840. // bit 1; mask 0x02; 1 = Formula is hidden
  1841. $isHidden = (0x02 & $xfTypeProt) >> 1;
  1842. $objStyle->getProtection()->setHidden($isHidden ? Protection::PROTECTION_PROTECTED : Protection::PROTECTION_UNPROTECTED);
  1843. // bit 2; mask 0x04; 0 = Cell XF, 1 = Cell Style XF
  1844. $isCellStyleXf = (0x04 & $xfTypeProt) >> 2;
  1845. // offset: 6; size: 1; Alignment and text break
  1846. // bit 2-0, mask 0x07; horizontal alignment
  1847. $horAlign = (0x07 & ord($recordData[6])) >> 0;
  1848. switch ($horAlign) {
  1849. case 0:
  1850. $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_GENERAL);
  1851. break;
  1852. case 1:
  1853. $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  1854. break;
  1855. case 2:
  1856. $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  1857. break;
  1858. case 3:
  1859. $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  1860. break;
  1861. case 4:
  1862. $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_FILL);
  1863. break;
  1864. case 5:
  1865. $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_JUSTIFY);
  1866. break;
  1867. case 6:
  1868. $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER_CONTINUOUS);
  1869. break;
  1870. }
  1871. // bit 3, mask 0x08; wrap text
  1872. $wrapText = (0x08 & ord($recordData[6])) >> 3;
  1873. switch ($wrapText) {
  1874. case 0:
  1875. $objStyle->getAlignment()->setWrapText(false);
  1876. break;
  1877. case 1:
  1878. $objStyle->getAlignment()->setWrapText(true);
  1879. break;
  1880. }
  1881. // bit 6-4, mask 0x70; vertical alignment
  1882. $vertAlign = (0x70 & ord($recordData[6])) >> 4;
  1883. switch ($vertAlign) {
  1884. case 0:
  1885. $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_TOP);
  1886. break;
  1887. case 1:
  1888. $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  1889. break;
  1890. case 2:
  1891. $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_BOTTOM);
  1892. break;
  1893. case 3:
  1894. $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_JUSTIFY);
  1895. break;
  1896. }
  1897. if ($this->version == self::XLS_BIFF8) {
  1898. // offset: 7; size: 1; XF_ROTATION: Text rotation angle
  1899. $angle = ord($recordData[7]);
  1900. $rotation = 0;
  1901. if ($angle <= 90) {
  1902. $rotation = $angle;
  1903. } elseif ($angle <= 180) {
  1904. $rotation = 90 - $angle;
  1905. } elseif ($angle == 255) {
  1906. $rotation = -165;
  1907. }
  1908. $objStyle->getAlignment()->setTextRotation($rotation);
  1909. // offset: 8; size: 1; Indentation, shrink to cell size, and text direction
  1910. // bit: 3-0; mask: 0x0F; indent level
  1911. $indent = (0x0F & ord($recordData[8])) >> 0;
  1912. $objStyle->getAlignment()->setIndent($indent);
  1913. // bit: 4; mask: 0x10; 1 = shrink content to fit into cell
  1914. $shrinkToFit = (0x10 & ord($recordData[8])) >> 4;
  1915. switch ($shrinkToFit) {
  1916. case 0:
  1917. $objStyle->getAlignment()->setShrinkToFit(false);
  1918. break;
  1919. case 1:
  1920. $objStyle->getAlignment()->setShrinkToFit(true);
  1921. break;
  1922. }
  1923. // offset: 9; size: 1; Flags used for attribute groups
  1924. // offset: 10; size: 4; Cell border lines and background area
  1925. // bit: 3-0; mask: 0x0000000F; left style
  1926. if ($bordersLeftStyle = Xls\Style\Border::lookup((0x0000000F & self::getInt4d($recordData, 10)) >> 0)) {
  1927. $objStyle->getBorders()->getLeft()->setBorderStyle($bordersLeftStyle);
  1928. }
  1929. // bit: 7-4; mask: 0x000000F0; right style
  1930. if ($bordersRightStyle = Xls\Style\Border::lookup((0x000000F0 & self::getInt4d($recordData, 10)) >> 4)) {
  1931. $objStyle->getBorders()->getRight()->setBorderStyle($bordersRightStyle);
  1932. }
  1933. // bit: 11-8; mask: 0x00000F00; top style
  1934. if ($bordersTopStyle = Xls\Style\Border::lookup((0x00000F00 & self::getInt4d($recordData, 10)) >> 8)) {
  1935. $objStyle->getBorders()->getTop()->setBorderStyle($bordersTopStyle);
  1936. }
  1937. // bit: 15-12; mask: 0x0000F000; bottom style
  1938. if ($bordersBottomStyle = Xls\Style\Border::lookup((0x0000F000 & self::getInt4d($recordData, 10)) >> 12)) {
  1939. $objStyle->getBorders()->getBottom()->setBorderStyle($bordersBottomStyle);
  1940. }
  1941. // bit: 22-16; mask: 0x007F0000; left color
  1942. $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & self::getInt4d($recordData, 10)) >> 16;
  1943. // bit: 29-23; mask: 0x3F800000; right color
  1944. $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & self::getInt4d($recordData, 10)) >> 23;
  1945. // bit: 30; mask: 0x40000000; 1 = diagonal line from top left to right bottom
  1946. $diagonalDown = (0x40000000 & self::getInt4d($recordData, 10)) >> 30 ? true : false;
  1947. // bit: 31; mask: 0x80000000; 1 = diagonal line from bottom left to top right
  1948. $diagonalUp = (0x80000000 & self::getInt4d($recordData, 10)) >> 31 ? true : false;
  1949. if ($diagonalUp == false && $diagonalDown == false) {
  1950. $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE);
  1951. } elseif ($diagonalUp == true && $diagonalDown == false) {
  1952. $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP);
  1953. } elseif ($diagonalUp == false && $diagonalDown == true) {
  1954. $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN);
  1955. } elseif ($diagonalUp == true && $diagonalDown == true) {
  1956. $objStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH);
  1957. }
  1958. // offset: 14; size: 4;
  1959. // bit: 6-0; mask: 0x0000007F; top color
  1960. $objStyle->getBorders()->getTop()->colorIndex = (0x0000007F & self::getInt4d($recordData, 14)) >> 0;
  1961. // bit: 13-7; mask: 0x00003F80; bottom color
  1962. $objStyle->getBorders()->getBottom()->colorIndex = (0x00003F80 & self::getInt4d($recordData, 14)) >> 7;
  1963. // bit: 20-14; mask: 0x001FC000; diagonal color
  1964. $objStyle->getBorders()->getDiagonal()->colorIndex = (0x001FC000 & self::getInt4d($recordData, 14)) >> 14;
  1965. // bit: 24-21; mask: 0x01E00000; diagonal style
  1966. if ($bordersDiagonalStyle = Xls\Style\Border::lookup((0x01E00000 & self::getInt4d($recordData, 14)) >> 21)) {
  1967. $objStyle->getBorders()->getDiagonal()->setBorderStyle($bordersDiagonalStyle);
  1968. }
  1969. // bit: 31-26; mask: 0xFC000000 fill pattern
  1970. if ($fillType = Xls\Style\FillPattern::lookup((0xFC000000 & self::getInt4d($recordData, 14)) >> 26)) {
  1971. $objStyle->getFill()->setFillType($fillType);
  1972. }
  1973. // offset: 18; size: 2; pattern and background colour
  1974. // bit: 6-0; mask: 0x007F; color index for pattern color
  1975. $objStyle->getFill()->startcolorIndex = (0x007F & self::getUInt2d($recordData, 18)) >> 0;
  1976. // bit: 13-7; mask: 0x3F80; color index for pattern background
  1977. $objStyle->getFill()->endcolorIndex = (0x3F80 & self::getUInt2d($recordData, 18)) >> 7;
  1978. } else {
  1979. // BIFF5
  1980. // offset: 7; size: 1; Text orientation and flags
  1981. $orientationAndFlags = ord($recordData[7]);
  1982. // bit: 1-0; mask: 0x03; XF_ORIENTATION: Text orientation
  1983. $xfOrientation = (0x03 & $orientationAndFlags) >> 0;
  1984. switch ($xfOrientation) {
  1985. case 0:
  1986. $objStyle->getAlignment()->setTextRotation(0);
  1987. break;
  1988. case 1:
  1989. $objStyle->getAlignment()->setTextRotation(-165);
  1990. break;
  1991. case 2:
  1992. $objStyle->getAlignment()->setTextRotation(90);
  1993. break;
  1994. case 3:
  1995. $objStyle->getAlignment()->setTextRotation(-90);
  1996. break;
  1997. }
  1998. // offset: 8; size: 4; cell border lines and background area
  1999. $borderAndBackground = self::getInt4d($recordData, 8);
  2000. // bit: 6-0; mask: 0x0000007F; color index for pattern color
  2001. $objStyle->getFill()->startcolorIndex = (0x0000007F & $borderAndBackground) >> 0;
  2002. // bit: 13-7; mask: 0x00003F80; color index for pattern background
  2003. $objStyle->getFill()->endcolorIndex = (0x00003F80 & $borderAndBackground) >> 7;
  2004. // bit: 21-16; mask: 0x003F0000; fill pattern
  2005. $objStyle->getFill()->setFillType(Xls\Style\FillPattern::lookup((0x003F0000 & $borderAndBackground) >> 16));
  2006. // bit: 24-22; mask: 0x01C00000; bottom line style
  2007. $objStyle->getBorders()->getBottom()->setBorderStyle(Xls\Style\Border::lookup((0x01C00000 & $borderAndBackground) >> 22));
  2008. // bit: 31-25; mask: 0xFE000000; bottom line color
  2009. $objStyle->getBorders()->getBottom()->colorIndex = (0xFE000000 & $borderAndBackground) >> 25;
  2010. // offset: 12; size: 4; cell border lines
  2011. $borderLines = self::getInt4d($recordData, 12);
  2012. // bit: 2-0; mask: 0x00000007; top line style
  2013. $objStyle->getBorders()->getTop()->setBorderStyle(Xls\Style\Border::lookup((0x00000007 & $borderLines) >> 0));
  2014. // bit: 5-3; mask: 0x00000038; left line style
  2015. $objStyle->getBorders()->getLeft()->setBorderStyle(Xls\Style\Border::lookup((0x00000038 & $borderLines) >> 3));
  2016. // bit: 8-6; mask: 0x000001C0; right line style
  2017. $objStyle->getBorders()->getRight()->setBorderStyle(Xls\Style\Border::lookup((0x000001C0 & $borderLines) >> 6));
  2018. // bit: 15-9; mask: 0x0000FE00; top line color index
  2019. $objStyle->getBorders()->getTop()->colorIndex = (0x0000FE00 & $borderLines) >> 9;
  2020. // bit: 22-16; mask: 0x007F0000; left line color index
  2021. $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & $borderLines) >> 16;
  2022. // bit: 29-23; mask: 0x3F800000; right line color index
  2023. $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & $borderLines) >> 23;
  2024. }
  2025. // add cellStyleXf or cellXf and update mapping
  2026. if ($isCellStyleXf) {
  2027. // we only read one style XF record which is always the first
  2028. if ($this->xfIndex == 0) {
  2029. $this->spreadsheet->addCellStyleXf($objStyle);
  2030. $this->mapCellStyleXfIndex[$this->xfIndex] = 0;
  2031. }
  2032. } else {
  2033. // we read all cell XF records
  2034. $this->spreadsheet->addCellXf($objStyle);
  2035. $this->mapCellXfIndex[$this->xfIndex] = count($this->spreadsheet->getCellXfCollection()) - 1;
  2036. }
  2037. // update XF index for when we read next record
  2038. ++$this->xfIndex;
  2039. }
  2040. }
  2041. private function readXfExt()
  2042. {
  2043. $length = self::getUInt2d($this->data, $this->pos + 2);
  2044. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2045. // move stream pointer to next record
  2046. $this->pos += 4 + $length;
  2047. if (!$this->readDataOnly) {
  2048. // offset: 0; size: 2; 0x087D = repeated header
  2049. // offset: 2; size: 2
  2050. // offset: 4; size: 8; not used
  2051. // offset: 12; size: 2; record version
  2052. // offset: 14; size: 2; index to XF record which this record modifies
  2053. $ixfe = self::getUInt2d($recordData, 14);
  2054. // offset: 16; size: 2; not used
  2055. // offset: 18; size: 2; number of extension properties that follow
  2056. $cexts = self::getUInt2d($recordData, 18);
  2057. // start reading the actual extension data
  2058. $offset = 20;
  2059. while ($offset < $length) {
  2060. // extension type
  2061. $extType = self::getUInt2d($recordData, $offset);
  2062. // extension length
  2063. $cb = self::getUInt2d($recordData, $offset + 2);
  2064. // extension data
  2065. $extData = substr($recordData, $offset + 4, $cb);
  2066. switch ($extType) {
  2067. case 4: // fill start color
  2068. $xclfType = self::getUInt2d($extData, 0); // color type
  2069. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  2070. if ($xclfType == 2) {
  2071. $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
  2072. // modify the relevant style property
  2073. if (isset($this->mapCellXfIndex[$ixfe])) {
  2074. $fill = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill();
  2075. $fill->getStartColor()->setRGB($rgb);
  2076. unset($fill->startcolorIndex); // normal color index does not apply, discard
  2077. }
  2078. }
  2079. break;
  2080. case 5: // fill end color
  2081. $xclfType = self::getUInt2d($extData, 0); // color type
  2082. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  2083. if ($xclfType == 2) {
  2084. $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
  2085. // modify the relevant style property
  2086. if (isset($this->mapCellXfIndex[$ixfe])) {
  2087. $fill = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill();
  2088. $fill->getEndColor()->setRGB($rgb);
  2089. unset($fill->endcolorIndex); // normal color index does not apply, discard
  2090. }
  2091. }
  2092. break;
  2093. case 7: // border color top
  2094. $xclfType = self::getUInt2d($extData, 0); // color type
  2095. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  2096. if ($xclfType == 2) {
  2097. $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
  2098. // modify the relevant style property
  2099. if (isset($this->mapCellXfIndex[$ixfe])) {
  2100. $top = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getTop();
  2101. $top->getColor()->setRGB($rgb);
  2102. unset($top->colorIndex); // normal color index does not apply, discard
  2103. }
  2104. }
  2105. break;
  2106. case 8: // border color bottom
  2107. $xclfType = self::getUInt2d($extData, 0); // color type
  2108. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  2109. if ($xclfType == 2) {
  2110. $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
  2111. // modify the relevant style property
  2112. if (isset($this->mapCellXfIndex[$ixfe])) {
  2113. $bottom = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getBottom();
  2114. $bottom->getColor()->setRGB($rgb);
  2115. unset($bottom->colorIndex); // normal color index does not apply, discard
  2116. }
  2117. }
  2118. break;
  2119. case 9: // border color left
  2120. $xclfType = self::getUInt2d($extData, 0); // color type
  2121. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  2122. if ($xclfType == 2) {
  2123. $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
  2124. // modify the relevant style property
  2125. if (isset($this->mapCellXfIndex[$ixfe])) {
  2126. $left = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getLeft();
  2127. $left->getColor()->setRGB($rgb);
  2128. unset($left->colorIndex); // normal color index does not apply, discard
  2129. }
  2130. }
  2131. break;
  2132. case 10: // border color right
  2133. $xclfType = self::getUInt2d($extData, 0); // color type
  2134. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  2135. if ($xclfType == 2) {
  2136. $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
  2137. // modify the relevant style property
  2138. if (isset($this->mapCellXfIndex[$ixfe])) {
  2139. $right = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getRight();
  2140. $right->getColor()->setRGB($rgb);
  2141. unset($right->colorIndex); // normal color index does not apply, discard
  2142. }
  2143. }
  2144. break;
  2145. case 11: // border color diagonal
  2146. $xclfType = self::getUInt2d($extData, 0); // color type
  2147. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  2148. if ($xclfType == 2) {
  2149. $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
  2150. // modify the relevant style property
  2151. if (isset($this->mapCellXfIndex[$ixfe])) {
  2152. $diagonal = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getDiagonal();
  2153. $diagonal->getColor()->setRGB($rgb);
  2154. unset($diagonal->colorIndex); // normal color index does not apply, discard
  2155. }
  2156. }
  2157. break;
  2158. case 13: // font color
  2159. $xclfType = self::getUInt2d($extData, 0); // color type
  2160. $xclrValue = substr($extData, 4, 4); // color value (value based on color type)
  2161. if ($xclfType == 2) {
  2162. $rgb = sprintf('%02X%02X%02X', ord($xclrValue[0]), ord($xclrValue[1]), ord($xclrValue[2]));
  2163. // modify the relevant style property
  2164. if (isset($this->mapCellXfIndex[$ixfe])) {
  2165. $font = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFont();
  2166. $font->getColor()->setRGB($rgb);
  2167. unset($font->colorIndex); // normal color index does not apply, discard
  2168. }
  2169. }
  2170. break;
  2171. }
  2172. $offset += $cb;
  2173. }
  2174. }
  2175. }
  2176. /**
  2177. * Read STYLE record.
  2178. */
  2179. private function readStyle()
  2180. {
  2181. $length = self::getUInt2d($this->data, $this->pos + 2);
  2182. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2183. // move stream pointer to next record
  2184. $this->pos += 4 + $length;
  2185. if (!$this->readDataOnly) {
  2186. // offset: 0; size: 2; index to XF record and flag for built-in style
  2187. $ixfe = self::getUInt2d($recordData, 0);
  2188. // bit: 11-0; mask 0x0FFF; index to XF record
  2189. $xfIndex = (0x0FFF & $ixfe) >> 0;
  2190. // bit: 15; mask 0x8000; 0 = user-defined style, 1 = built-in style
  2191. $isBuiltIn = (bool) ((0x8000 & $ixfe) >> 15);
  2192. if ($isBuiltIn) {
  2193. // offset: 2; size: 1; identifier for built-in style
  2194. $builtInId = ord($recordData[2]);
  2195. switch ($builtInId) {
  2196. case 0x00:
  2197. // currently, we are not using this for anything
  2198. break;
  2199. default:
  2200. break;
  2201. }
  2202. }
  2203. // user-defined; not supported by PhpSpreadsheet
  2204. }
  2205. }
  2206. /**
  2207. * Read PALETTE record.
  2208. */
  2209. private function readPalette()
  2210. {
  2211. $length = self::getUInt2d($this->data, $this->pos + 2);
  2212. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2213. // move stream pointer to next record
  2214. $this->pos += 4 + $length;
  2215. if (!$this->readDataOnly) {
  2216. // offset: 0; size: 2; number of following colors
  2217. $nm = self::getUInt2d($recordData, 0);
  2218. // list of RGB colors
  2219. for ($i = 0; $i < $nm; ++$i) {
  2220. $rgb = substr($recordData, 2 + 4 * $i, 4);
  2221. $this->palette[] = self::readRGB($rgb);
  2222. }
  2223. }
  2224. }
  2225. /**
  2226. * SHEET.
  2227. *
  2228. * This record is located in the Workbook Globals
  2229. * Substream and represents a sheet inside the workbook.
  2230. * One SHEET record is written for each sheet. It stores the
  2231. * sheet name and a stream offset to the BOF record of the
  2232. * respective Sheet Substream within the Workbook Stream.
  2233. *
  2234. * -- "OpenOffice.org's Documentation of the Microsoft
  2235. * Excel File Format"
  2236. */
  2237. private function readSheet()
  2238. {
  2239. $length = self::getUInt2d($this->data, $this->pos + 2);
  2240. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2241. // offset: 0; size: 4; absolute stream position of the BOF record of the sheet
  2242. // NOTE: not encrypted
  2243. $rec_offset = self::getInt4d($this->data, $this->pos + 4);
  2244. // move stream pointer to next record
  2245. $this->pos += 4 + $length;
  2246. // offset: 4; size: 1; sheet state
  2247. switch (ord($recordData[4])) {
  2248. case 0x00:
  2249. $sheetState = Worksheet::SHEETSTATE_VISIBLE;
  2250. break;
  2251. case 0x01:
  2252. $sheetState = Worksheet::SHEETSTATE_HIDDEN;
  2253. break;
  2254. case 0x02:
  2255. $sheetState = Worksheet::SHEETSTATE_VERYHIDDEN;
  2256. break;
  2257. default:
  2258. $sheetState = Worksheet::SHEETSTATE_VISIBLE;
  2259. break;
  2260. }
  2261. // offset: 5; size: 1; sheet type
  2262. $sheetType = ord($recordData[5]);
  2263. // offset: 6; size: var; sheet name
  2264. if ($this->version == self::XLS_BIFF8) {
  2265. $string = self::readUnicodeStringShort(substr($recordData, 6));
  2266. $rec_name = $string['value'];
  2267. } elseif ($this->version == self::XLS_BIFF7) {
  2268. $string = $this->readByteStringShort(substr($recordData, 6));
  2269. $rec_name = $string['value'];
  2270. }
  2271. $this->sheets[] = [
  2272. 'name' => $rec_name,
  2273. 'offset' => $rec_offset,
  2274. 'sheetState' => $sheetState,
  2275. 'sheetType' => $sheetType,
  2276. ];
  2277. }
  2278. /**
  2279. * Read EXTERNALBOOK record.
  2280. */
  2281. private function readExternalBook()
  2282. {
  2283. $length = self::getUInt2d($this->data, $this->pos + 2);
  2284. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2285. // move stream pointer to next record
  2286. $this->pos += 4 + $length;
  2287. // offset within record data
  2288. $offset = 0;
  2289. // there are 4 types of records
  2290. if (strlen($recordData) > 4) {
  2291. // external reference
  2292. // offset: 0; size: 2; number of sheet names ($nm)
  2293. $nm = self::getUInt2d($recordData, 0);
  2294. $offset += 2;
  2295. // offset: 2; size: var; encoded URL without sheet name (Unicode string, 16-bit length)
  2296. $encodedUrlString = self::readUnicodeStringLong(substr($recordData, 2));
  2297. $offset += $encodedUrlString['size'];
  2298. // offset: var; size: var; list of $nm sheet names (Unicode strings, 16-bit length)
  2299. $externalSheetNames = [];
  2300. for ($i = 0; $i < $nm; ++$i) {
  2301. $externalSheetNameString = self::readUnicodeStringLong(substr($recordData, $offset));
  2302. $externalSheetNames[] = $externalSheetNameString['value'];
  2303. $offset += $externalSheetNameString['size'];
  2304. }
  2305. // store the record data
  2306. $this->externalBooks[] = [
  2307. 'type' => 'external',
  2308. 'encodedUrl' => $encodedUrlString['value'],
  2309. 'externalSheetNames' => $externalSheetNames,
  2310. ];
  2311. } elseif (substr($recordData, 2, 2) == pack('CC', 0x01, 0x04)) {
  2312. // internal reference
  2313. // offset: 0; size: 2; number of sheet in this document
  2314. // offset: 2; size: 2; 0x01 0x04
  2315. $this->externalBooks[] = [
  2316. 'type' => 'internal',
  2317. ];
  2318. } elseif (substr($recordData, 0, 4) == pack('vCC', 0x0001, 0x01, 0x3A)) {
  2319. // add-in function
  2320. // offset: 0; size: 2; 0x0001
  2321. $this->externalBooks[] = [
  2322. 'type' => 'addInFunction',
  2323. ];
  2324. } elseif (substr($recordData, 0, 2) == pack('v', 0x0000)) {
  2325. // DDE links, OLE links
  2326. // offset: 0; size: 2; 0x0000
  2327. // offset: 2; size: var; encoded source document name
  2328. $this->externalBooks[] = [
  2329. 'type' => 'DDEorOLE',
  2330. ];
  2331. }
  2332. }
  2333. /**
  2334. * Read EXTERNNAME record.
  2335. */
  2336. private function readExternName()
  2337. {
  2338. $length = self::getUInt2d($this->data, $this->pos + 2);
  2339. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2340. // move stream pointer to next record
  2341. $this->pos += 4 + $length;
  2342. // external sheet references provided for named cells
  2343. if ($this->version == self::XLS_BIFF8) {
  2344. // offset: 0; size: 2; options
  2345. $options = self::getUInt2d($recordData, 0);
  2346. // offset: 2; size: 2;
  2347. // offset: 4; size: 2; not used
  2348. // offset: 6; size: var
  2349. $nameString = self::readUnicodeStringShort(substr($recordData, 6));
  2350. // offset: var; size: var; formula data
  2351. $offset = 6 + $nameString['size'];
  2352. $formula = $this->getFormulaFromStructure(substr($recordData, $offset));
  2353. $this->externalNames[] = [
  2354. 'name' => $nameString['value'],
  2355. 'formula' => $formula,
  2356. ];
  2357. }
  2358. }
  2359. /**
  2360. * Read EXTERNSHEET record.
  2361. */
  2362. private function readExternSheet()
  2363. {
  2364. $length = self::getUInt2d($this->data, $this->pos + 2);
  2365. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2366. // move stream pointer to next record
  2367. $this->pos += 4 + $length;
  2368. // external sheet references provided for named cells
  2369. if ($this->version == self::XLS_BIFF8) {
  2370. // offset: 0; size: 2; number of following ref structures
  2371. $nm = self::getUInt2d($recordData, 0);
  2372. for ($i = 0; $i < $nm; ++$i) {
  2373. $this->ref[] = [
  2374. // offset: 2 + 6 * $i; index to EXTERNALBOOK record
  2375. 'externalBookIndex' => self::getUInt2d($recordData, 2 + 6 * $i),
  2376. // offset: 4 + 6 * $i; index to first sheet in EXTERNALBOOK record
  2377. 'firstSheetIndex' => self::getUInt2d($recordData, 4 + 6 * $i),
  2378. // offset: 6 + 6 * $i; index to last sheet in EXTERNALBOOK record
  2379. 'lastSheetIndex' => self::getUInt2d($recordData, 6 + 6 * $i),
  2380. ];
  2381. }
  2382. }
  2383. }
  2384. /**
  2385. * DEFINEDNAME.
  2386. *
  2387. * This record is part of a Link Table. It contains the name
  2388. * and the token array of an internal defined name. Token
  2389. * arrays of defined names contain tokens with aberrant
  2390. * token classes.
  2391. *
  2392. * -- "OpenOffice.org's Documentation of the Microsoft
  2393. * Excel File Format"
  2394. */
  2395. private function readDefinedName()
  2396. {
  2397. $length = self::getUInt2d($this->data, $this->pos + 2);
  2398. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2399. // move stream pointer to next record
  2400. $this->pos += 4 + $length;
  2401. if ($this->version == self::XLS_BIFF8) {
  2402. // retrieves named cells
  2403. // offset: 0; size: 2; option flags
  2404. $opts = self::getUInt2d($recordData, 0);
  2405. // bit: 5; mask: 0x0020; 0 = user-defined name, 1 = built-in-name
  2406. $isBuiltInName = (0x0020 & $opts) >> 5;
  2407. // offset: 2; size: 1; keyboard shortcut
  2408. // offset: 3; size: 1; length of the name (character count)
  2409. $nlen = ord($recordData[3]);
  2410. // offset: 4; size: 2; size of the formula data (it can happen that this is zero)
  2411. // note: there can also be additional data, this is not included in $flen
  2412. $flen = self::getUInt2d($recordData, 4);
  2413. // offset: 8; size: 2; 0=Global name, otherwise index to sheet (1-based)
  2414. $scope = self::getUInt2d($recordData, 8);
  2415. // offset: 14; size: var; Name (Unicode string without length field)
  2416. $string = self::readUnicodeString(substr($recordData, 14), $nlen);
  2417. // offset: var; size: $flen; formula data
  2418. $offset = 14 + $string['size'];
  2419. $formulaStructure = pack('v', $flen) . substr($recordData, $offset);
  2420. try {
  2421. $formula = $this->getFormulaFromStructure($formulaStructure);
  2422. } catch (PhpSpreadsheetException $e) {
  2423. $formula = '';
  2424. }
  2425. $this->definedname[] = [
  2426. 'isBuiltInName' => $isBuiltInName,
  2427. 'name' => $string['value'],
  2428. 'formula' => $formula,
  2429. 'scope' => $scope,
  2430. ];
  2431. }
  2432. }
  2433. /**
  2434. * Read MSODRAWINGGROUP record.
  2435. */
  2436. private function readMsoDrawingGroup()
  2437. {
  2438. $length = self::getUInt2d($this->data, $this->pos + 2);
  2439. // get spliced record data
  2440. $splicedRecordData = $this->getSplicedRecordData();
  2441. $recordData = $splicedRecordData['recordData'];
  2442. $this->drawingGroupData .= $recordData;
  2443. }
  2444. /**
  2445. * SST - Shared String Table.
  2446. *
  2447. * This record contains a list of all strings used anywhere
  2448. * in the workbook. Each string occurs only once. The
  2449. * workbook uses indexes into the list to reference the
  2450. * strings.
  2451. *
  2452. * -- "OpenOffice.org's Documentation of the Microsoft
  2453. * Excel File Format"
  2454. */
  2455. private function readSst()
  2456. {
  2457. // offset within (spliced) record data
  2458. $pos = 0;
  2459. // get spliced record data
  2460. $splicedRecordData = $this->getSplicedRecordData();
  2461. $recordData = $splicedRecordData['recordData'];
  2462. $spliceOffsets = $splicedRecordData['spliceOffsets'];
  2463. // offset: 0; size: 4; total number of strings in the workbook
  2464. $pos += 4;
  2465. // offset: 4; size: 4; number of following strings ($nm)
  2466. $nm = self::getInt4d($recordData, 4);
  2467. $pos += 4;
  2468. // loop through the Unicode strings (16-bit length)
  2469. for ($i = 0; $i < $nm; ++$i) {
  2470. // number of characters in the Unicode string
  2471. $numChars = self::getUInt2d($recordData, $pos);
  2472. $pos += 2;
  2473. // option flags
  2474. $optionFlags = ord($recordData[$pos]);
  2475. ++$pos;
  2476. // bit: 0; mask: 0x01; 0 = compressed; 1 = uncompressed
  2477. $isCompressed = (($optionFlags & 0x01) == 0);
  2478. // bit: 2; mask: 0x02; 0 = ordinary; 1 = Asian phonetic
  2479. $hasAsian = (($optionFlags & 0x04) != 0);
  2480. // bit: 3; mask: 0x03; 0 = ordinary; 1 = Rich-Text
  2481. $hasRichText = (($optionFlags & 0x08) != 0);
  2482. if ($hasRichText) {
  2483. // number of Rich-Text formatting runs
  2484. $formattingRuns = self::getUInt2d($recordData, $pos);
  2485. $pos += 2;
  2486. }
  2487. if ($hasAsian) {
  2488. // size of Asian phonetic setting
  2489. $extendedRunLength = self::getInt4d($recordData, $pos);
  2490. $pos += 4;
  2491. }
  2492. // expected byte length of character array if not split
  2493. $len = ($isCompressed) ? $numChars : $numChars * 2;
  2494. // look up limit position
  2495. foreach ($spliceOffsets as $spliceOffset) {
  2496. // it can happen that the string is empty, therefore we need
  2497. // <= and not just <
  2498. if ($pos <= $spliceOffset) {
  2499. $limitpos = $spliceOffset;
  2500. break;
  2501. }
  2502. }
  2503. if ($pos + $len <= $limitpos) {
  2504. // character array is not split between records
  2505. $retstr = substr($recordData, $pos, $len);
  2506. $pos += $len;
  2507. } else {
  2508. // character array is split between records
  2509. // first part of character array
  2510. $retstr = substr($recordData, $pos, $limitpos - $pos);
  2511. $bytesRead = $limitpos - $pos;
  2512. // remaining characters in Unicode string
  2513. $charsLeft = $numChars - (($isCompressed) ? $bytesRead : ($bytesRead / 2));
  2514. $pos = $limitpos;
  2515. // keep reading the characters
  2516. while ($charsLeft > 0) {
  2517. // look up next limit position, in case the string span more than one continue record
  2518. foreach ($spliceOffsets as $spliceOffset) {
  2519. if ($pos < $spliceOffset) {
  2520. $limitpos = $spliceOffset;
  2521. break;
  2522. }
  2523. }
  2524. // repeated option flags
  2525. // OpenOffice.org documentation 5.21
  2526. $option = ord($recordData[$pos]);
  2527. ++$pos;
  2528. if ($isCompressed && ($option == 0)) {
  2529. // 1st fragment compressed
  2530. // this fragment compressed
  2531. $len = min($charsLeft, $limitpos - $pos);
  2532. $retstr .= substr($recordData, $pos, $len);
  2533. $charsLeft -= $len;
  2534. $isCompressed = true;
  2535. } elseif (!$isCompressed && ($option != 0)) {
  2536. // 1st fragment uncompressed
  2537. // this fragment uncompressed
  2538. $len = min($charsLeft * 2, $limitpos - $pos);
  2539. $retstr .= substr($recordData, $pos, $len);
  2540. $charsLeft -= $len / 2;
  2541. $isCompressed = false;
  2542. } elseif (!$isCompressed && ($option == 0)) {
  2543. // 1st fragment uncompressed
  2544. // this fragment compressed
  2545. $len = min($charsLeft, $limitpos - $pos);
  2546. for ($j = 0; $j < $len; ++$j) {
  2547. $retstr .= $recordData[$pos + $j]
  2548. . chr(0);
  2549. }
  2550. $charsLeft -= $len;
  2551. $isCompressed = false;
  2552. } else {
  2553. // 1st fragment compressed
  2554. // this fragment uncompressed
  2555. $newstr = '';
  2556. $jMax = strlen($retstr);
  2557. for ($j = 0; $j < $jMax; ++$j) {
  2558. $newstr .= $retstr[$j] . chr(0);
  2559. }
  2560. $retstr = $newstr;
  2561. $len = min($charsLeft * 2, $limitpos - $pos);
  2562. $retstr .= substr($recordData, $pos, $len);
  2563. $charsLeft -= $len / 2;
  2564. $isCompressed = false;
  2565. }
  2566. $pos += $len;
  2567. }
  2568. }
  2569. // convert to UTF-8
  2570. $retstr = self::encodeUTF16($retstr, $isCompressed);
  2571. // read additional Rich-Text information, if any
  2572. $fmtRuns = [];
  2573. if ($hasRichText) {
  2574. // list of formatting runs
  2575. for ($j = 0; $j < $formattingRuns; ++$j) {
  2576. // first formatted character; zero-based
  2577. $charPos = self::getUInt2d($recordData, $pos + $j * 4);
  2578. // index to font record
  2579. $fontIndex = self::getUInt2d($recordData, $pos + 2 + $j * 4);
  2580. $fmtRuns[] = [
  2581. 'charPos' => $charPos,
  2582. 'fontIndex' => $fontIndex,
  2583. ];
  2584. }
  2585. $pos += 4 * $formattingRuns;
  2586. }
  2587. // read additional Asian phonetics information, if any
  2588. if ($hasAsian) {
  2589. // For Asian phonetic settings, we skip the extended string data
  2590. $pos += $extendedRunLength;
  2591. }
  2592. // store the shared sting
  2593. $this->sst[] = [
  2594. 'value' => $retstr,
  2595. 'fmtRuns' => $fmtRuns,
  2596. ];
  2597. }
  2598. // getSplicedRecordData() takes care of moving current position in data stream
  2599. }
  2600. /**
  2601. * Read PRINTGRIDLINES record.
  2602. */
  2603. private function readPrintGridlines()
  2604. {
  2605. $length = self::getUInt2d($this->data, $this->pos + 2);
  2606. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2607. // move stream pointer to next record
  2608. $this->pos += 4 + $length;
  2609. if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) {
  2610. // offset: 0; size: 2; 0 = do not print sheet grid lines; 1 = print sheet gridlines
  2611. $printGridlines = (bool) self::getUInt2d($recordData, 0);
  2612. $this->phpSheet->setPrintGridlines($printGridlines);
  2613. }
  2614. }
  2615. /**
  2616. * Read DEFAULTROWHEIGHT record.
  2617. */
  2618. private function readDefaultRowHeight()
  2619. {
  2620. $length = self::getUInt2d($this->data, $this->pos + 2);
  2621. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2622. // move stream pointer to next record
  2623. $this->pos += 4 + $length;
  2624. // offset: 0; size: 2; option flags
  2625. // offset: 2; size: 2; default height for unused rows, (twips 1/20 point)
  2626. $height = self::getUInt2d($recordData, 2);
  2627. $this->phpSheet->getDefaultRowDimension()->setRowHeight($height / 20);
  2628. }
  2629. /**
  2630. * Read SHEETPR record.
  2631. */
  2632. private function readSheetPr()
  2633. {
  2634. $length = self::getUInt2d($this->data, $this->pos + 2);
  2635. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2636. // move stream pointer to next record
  2637. $this->pos += 4 + $length;
  2638. // offset: 0; size: 2
  2639. // bit: 6; mask: 0x0040; 0 = outline buttons above outline group
  2640. $isSummaryBelow = (0x0040 & self::getUInt2d($recordData, 0)) >> 6;
  2641. $this->phpSheet->setShowSummaryBelow($isSummaryBelow);
  2642. // bit: 7; mask: 0x0080; 0 = outline buttons left of outline group
  2643. $isSummaryRight = (0x0080 & self::getUInt2d($recordData, 0)) >> 7;
  2644. $this->phpSheet->setShowSummaryRight($isSummaryRight);
  2645. // bit: 8; mask: 0x100; 0 = scale printout in percent, 1 = fit printout to number of pages
  2646. // this corresponds to radio button setting in page setup dialog in Excel
  2647. $this->isFitToPages = (bool) ((0x0100 & self::getUInt2d($recordData, 0)) >> 8);
  2648. }
  2649. /**
  2650. * Read HORIZONTALPAGEBREAKS record.
  2651. */
  2652. private function readHorizontalPageBreaks()
  2653. {
  2654. $length = self::getUInt2d($this->data, $this->pos + 2);
  2655. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2656. // move stream pointer to next record
  2657. $this->pos += 4 + $length;
  2658. if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) {
  2659. // offset: 0; size: 2; number of the following row index structures
  2660. $nm = self::getUInt2d($recordData, 0);
  2661. // offset: 2; size: 6 * $nm; list of $nm row index structures
  2662. for ($i = 0; $i < $nm; ++$i) {
  2663. $r = self::getUInt2d($recordData, 2 + 6 * $i);
  2664. $cf = self::getUInt2d($recordData, 2 + 6 * $i + 2);
  2665. $cl = self::getUInt2d($recordData, 2 + 6 * $i + 4);
  2666. // not sure why two column indexes are necessary?
  2667. $this->phpSheet->setBreakByColumnAndRow($cf + 1, $r, Worksheet::BREAK_ROW);
  2668. }
  2669. }
  2670. }
  2671. /**
  2672. * Read VERTICALPAGEBREAKS record.
  2673. */
  2674. private function readVerticalPageBreaks()
  2675. {
  2676. $length = self::getUInt2d($this->data, $this->pos + 2);
  2677. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2678. // move stream pointer to next record
  2679. $this->pos += 4 + $length;
  2680. if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) {
  2681. // offset: 0; size: 2; number of the following column index structures
  2682. $nm = self::getUInt2d($recordData, 0);
  2683. // offset: 2; size: 6 * $nm; list of $nm row index structures
  2684. for ($i = 0; $i < $nm; ++$i) {
  2685. $c = self::getUInt2d($recordData, 2 + 6 * $i);
  2686. $rf = self::getUInt2d($recordData, 2 + 6 * $i + 2);
  2687. $rl = self::getUInt2d($recordData, 2 + 6 * $i + 4);
  2688. // not sure why two row indexes are necessary?
  2689. $this->phpSheet->setBreakByColumnAndRow($c + 1, $rf, Worksheet::BREAK_COLUMN);
  2690. }
  2691. }
  2692. }
  2693. /**
  2694. * Read HEADER record.
  2695. */
  2696. private function readHeader()
  2697. {
  2698. $length = self::getUInt2d($this->data, $this->pos + 2);
  2699. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2700. // move stream pointer to next record
  2701. $this->pos += 4 + $length;
  2702. if (!$this->readDataOnly) {
  2703. // offset: 0; size: var
  2704. // realized that $recordData can be empty even when record exists
  2705. if ($recordData) {
  2706. if ($this->version == self::XLS_BIFF8) {
  2707. $string = self::readUnicodeStringLong($recordData);
  2708. } else {
  2709. $string = $this->readByteStringShort($recordData);
  2710. }
  2711. $this->phpSheet->getHeaderFooter()->setOddHeader($string['value']);
  2712. $this->phpSheet->getHeaderFooter()->setEvenHeader($string['value']);
  2713. }
  2714. }
  2715. }
  2716. /**
  2717. * Read FOOTER record.
  2718. */
  2719. private function readFooter()
  2720. {
  2721. $length = self::getUInt2d($this->data, $this->pos + 2);
  2722. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2723. // move stream pointer to next record
  2724. $this->pos += 4 + $length;
  2725. if (!$this->readDataOnly) {
  2726. // offset: 0; size: var
  2727. // realized that $recordData can be empty even when record exists
  2728. if ($recordData) {
  2729. if ($this->version == self::XLS_BIFF8) {
  2730. $string = self::readUnicodeStringLong($recordData);
  2731. } else {
  2732. $string = $this->readByteStringShort($recordData);
  2733. }
  2734. $this->phpSheet->getHeaderFooter()->setOddFooter($string['value']);
  2735. $this->phpSheet->getHeaderFooter()->setEvenFooter($string['value']);
  2736. }
  2737. }
  2738. }
  2739. /**
  2740. * Read HCENTER record.
  2741. */
  2742. private function readHcenter()
  2743. {
  2744. $length = self::getUInt2d($this->data, $this->pos + 2);
  2745. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2746. // move stream pointer to next record
  2747. $this->pos += 4 + $length;
  2748. if (!$this->readDataOnly) {
  2749. // offset: 0; size: 2; 0 = print sheet left aligned, 1 = print sheet centered horizontally
  2750. $isHorizontalCentered = (bool) self::getUInt2d($recordData, 0);
  2751. $this->phpSheet->getPageSetup()->setHorizontalCentered($isHorizontalCentered);
  2752. }
  2753. }
  2754. /**
  2755. * Read VCENTER record.
  2756. */
  2757. private function readVcenter()
  2758. {
  2759. $length = self::getUInt2d($this->data, $this->pos + 2);
  2760. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2761. // move stream pointer to next record
  2762. $this->pos += 4 + $length;
  2763. if (!$this->readDataOnly) {
  2764. // offset: 0; size: 2; 0 = print sheet aligned at top page border, 1 = print sheet vertically centered
  2765. $isVerticalCentered = (bool) self::getUInt2d($recordData, 0);
  2766. $this->phpSheet->getPageSetup()->setVerticalCentered($isVerticalCentered);
  2767. }
  2768. }
  2769. /**
  2770. * Read LEFTMARGIN record.
  2771. */
  2772. private function readLeftMargin()
  2773. {
  2774. $length = self::getUInt2d($this->data, $this->pos + 2);
  2775. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2776. // move stream pointer to next record
  2777. $this->pos += 4 + $length;
  2778. if (!$this->readDataOnly) {
  2779. // offset: 0; size: 8
  2780. $this->phpSheet->getPageMargins()->setLeft(self::extractNumber($recordData));
  2781. }
  2782. }
  2783. /**
  2784. * Read RIGHTMARGIN record.
  2785. */
  2786. private function readRightMargin()
  2787. {
  2788. $length = self::getUInt2d($this->data, $this->pos + 2);
  2789. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2790. // move stream pointer to next record
  2791. $this->pos += 4 + $length;
  2792. if (!$this->readDataOnly) {
  2793. // offset: 0; size: 8
  2794. $this->phpSheet->getPageMargins()->setRight(self::extractNumber($recordData));
  2795. }
  2796. }
  2797. /**
  2798. * Read TOPMARGIN record.
  2799. */
  2800. private function readTopMargin()
  2801. {
  2802. $length = self::getUInt2d($this->data, $this->pos + 2);
  2803. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2804. // move stream pointer to next record
  2805. $this->pos += 4 + $length;
  2806. if (!$this->readDataOnly) {
  2807. // offset: 0; size: 8
  2808. $this->phpSheet->getPageMargins()->setTop(self::extractNumber($recordData));
  2809. }
  2810. }
  2811. /**
  2812. * Read BOTTOMMARGIN record.
  2813. */
  2814. private function readBottomMargin()
  2815. {
  2816. $length = self::getUInt2d($this->data, $this->pos + 2);
  2817. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2818. // move stream pointer to next record
  2819. $this->pos += 4 + $length;
  2820. if (!$this->readDataOnly) {
  2821. // offset: 0; size: 8
  2822. $this->phpSheet->getPageMargins()->setBottom(self::extractNumber($recordData));
  2823. }
  2824. }
  2825. /**
  2826. * Read PAGESETUP record.
  2827. */
  2828. private function readPageSetup()
  2829. {
  2830. $length = self::getUInt2d($this->data, $this->pos + 2);
  2831. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2832. // move stream pointer to next record
  2833. $this->pos += 4 + $length;
  2834. if (!$this->readDataOnly) {
  2835. // offset: 0; size: 2; paper size
  2836. $paperSize = self::getUInt2d($recordData, 0);
  2837. // offset: 2; size: 2; scaling factor
  2838. $scale = self::getUInt2d($recordData, 2);
  2839. // offset: 6; size: 2; fit worksheet width to this number of pages, 0 = use as many as needed
  2840. $fitToWidth = self::getUInt2d($recordData, 6);
  2841. // offset: 8; size: 2; fit worksheet height to this number of pages, 0 = use as many as needed
  2842. $fitToHeight = self::getUInt2d($recordData, 8);
  2843. // offset: 10; size: 2; option flags
  2844. // bit: 1; mask: 0x0002; 0=landscape, 1=portrait
  2845. $isPortrait = (0x0002 & self::getUInt2d($recordData, 10)) >> 1;
  2846. // bit: 2; mask: 0x0004; 1= paper size, scaling factor, paper orient. not init
  2847. // when this bit is set, do not use flags for those properties
  2848. $isNotInit = (0x0004 & self::getUInt2d($recordData, 10)) >> 2;
  2849. if (!$isNotInit) {
  2850. $this->phpSheet->getPageSetup()->setPaperSize($paperSize);
  2851. switch ($isPortrait) {
  2852. case 0:
  2853. $this->phpSheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
  2854. break;
  2855. case 1:
  2856. $this->phpSheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_PORTRAIT);
  2857. break;
  2858. }
  2859. $this->phpSheet->getPageSetup()->setScale($scale, false);
  2860. $this->phpSheet->getPageSetup()->setFitToPage((bool) $this->isFitToPages);
  2861. $this->phpSheet->getPageSetup()->setFitToWidth($fitToWidth, false);
  2862. $this->phpSheet->getPageSetup()->setFitToHeight($fitToHeight, false);
  2863. }
  2864. // offset: 16; size: 8; header margin (IEEE 754 floating-point value)
  2865. $marginHeader = self::extractNumber(substr($recordData, 16, 8));
  2866. $this->phpSheet->getPageMargins()->setHeader($marginHeader);
  2867. // offset: 24; size: 8; footer margin (IEEE 754 floating-point value)
  2868. $marginFooter = self::extractNumber(substr($recordData, 24, 8));
  2869. $this->phpSheet->getPageMargins()->setFooter($marginFooter);
  2870. }
  2871. }
  2872. /**
  2873. * PROTECT - Sheet protection (BIFF2 through BIFF8)
  2874. * if this record is omitted, then it also means no sheet protection.
  2875. */
  2876. private function readProtect()
  2877. {
  2878. $length = self::getUInt2d($this->data, $this->pos + 2);
  2879. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2880. // move stream pointer to next record
  2881. $this->pos += 4 + $length;
  2882. if ($this->readDataOnly) {
  2883. return;
  2884. }
  2885. // offset: 0; size: 2;
  2886. // bit 0, mask 0x01; 1 = sheet is protected
  2887. $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0;
  2888. $this->phpSheet->getProtection()->setSheet((bool) $bool);
  2889. }
  2890. /**
  2891. * SCENPROTECT.
  2892. */
  2893. private function readScenProtect()
  2894. {
  2895. $length = self::getUInt2d($this->data, $this->pos + 2);
  2896. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2897. // move stream pointer to next record
  2898. $this->pos += 4 + $length;
  2899. if ($this->readDataOnly) {
  2900. return;
  2901. }
  2902. // offset: 0; size: 2;
  2903. // bit: 0, mask 0x01; 1 = scenarios are protected
  2904. $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0;
  2905. $this->phpSheet->getProtection()->setScenarios((bool) $bool);
  2906. }
  2907. /**
  2908. * OBJECTPROTECT.
  2909. */
  2910. private function readObjectProtect()
  2911. {
  2912. $length = self::getUInt2d($this->data, $this->pos + 2);
  2913. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2914. // move stream pointer to next record
  2915. $this->pos += 4 + $length;
  2916. if ($this->readDataOnly) {
  2917. return;
  2918. }
  2919. // offset: 0; size: 2;
  2920. // bit: 0, mask 0x01; 1 = objects are protected
  2921. $bool = (0x01 & self::getUInt2d($recordData, 0)) >> 0;
  2922. $this->phpSheet->getProtection()->setObjects((bool) $bool);
  2923. }
  2924. /**
  2925. * PASSWORD - Sheet protection (hashed) password (BIFF2 through BIFF8).
  2926. */
  2927. private function readPassword()
  2928. {
  2929. $length = self::getUInt2d($this->data, $this->pos + 2);
  2930. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2931. // move stream pointer to next record
  2932. $this->pos += 4 + $length;
  2933. if (!$this->readDataOnly) {
  2934. // offset: 0; size: 2; 16-bit hash value of password
  2935. $password = strtoupper(dechex(self::getUInt2d($recordData, 0))); // the hashed password
  2936. $this->phpSheet->getProtection()->setPassword($password, true);
  2937. }
  2938. }
  2939. /**
  2940. * Read DEFCOLWIDTH record.
  2941. */
  2942. private function readDefColWidth()
  2943. {
  2944. $length = self::getUInt2d($this->data, $this->pos + 2);
  2945. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2946. // move stream pointer to next record
  2947. $this->pos += 4 + $length;
  2948. // offset: 0; size: 2; default column width
  2949. $width = self::getUInt2d($recordData, 0);
  2950. if ($width != 8) {
  2951. $this->phpSheet->getDefaultColumnDimension()->setWidth($width);
  2952. }
  2953. }
  2954. /**
  2955. * Read COLINFO record.
  2956. */
  2957. private function readColInfo()
  2958. {
  2959. $length = self::getUInt2d($this->data, $this->pos + 2);
  2960. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  2961. // move stream pointer to next record
  2962. $this->pos += 4 + $length;
  2963. if (!$this->readDataOnly) {
  2964. // offset: 0; size: 2; index to first column in range
  2965. $firstColumnIndex = self::getUInt2d($recordData, 0);
  2966. // offset: 2; size: 2; index to last column in range
  2967. $lastColumnIndex = self::getUInt2d($recordData, 2);
  2968. // offset: 4; size: 2; width of the column in 1/256 of the width of the zero character
  2969. $width = self::getUInt2d($recordData, 4);
  2970. // offset: 6; size: 2; index to XF record for default column formatting
  2971. $xfIndex = self::getUInt2d($recordData, 6);
  2972. // offset: 8; size: 2; option flags
  2973. // bit: 0; mask: 0x0001; 1= columns are hidden
  2974. $isHidden = (0x0001 & self::getUInt2d($recordData, 8)) >> 0;
  2975. // bit: 10-8; mask: 0x0700; outline level of the columns (0 = no outline)
  2976. $level = (0x0700 & self::getUInt2d($recordData, 8)) >> 8;
  2977. // bit: 12; mask: 0x1000; 1 = collapsed
  2978. $isCollapsed = (0x1000 & self::getUInt2d($recordData, 8)) >> 12;
  2979. // offset: 10; size: 2; not used
  2980. for ($i = $firstColumnIndex + 1; $i <= $lastColumnIndex + 1; ++$i) {
  2981. if ($lastColumnIndex == 255 || $lastColumnIndex == 256) {
  2982. $this->phpSheet->getDefaultColumnDimension()->setWidth($width / 256);
  2983. break;
  2984. }
  2985. $this->phpSheet->getColumnDimensionByColumn($i)->setWidth($width / 256);
  2986. $this->phpSheet->getColumnDimensionByColumn($i)->setVisible(!$isHidden);
  2987. $this->phpSheet->getColumnDimensionByColumn($i)->setOutlineLevel($level);
  2988. $this->phpSheet->getColumnDimensionByColumn($i)->setCollapsed($isCollapsed);
  2989. $this->phpSheet->getColumnDimensionByColumn($i)->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  2990. }
  2991. }
  2992. }
  2993. /**
  2994. * ROW.
  2995. *
  2996. * This record contains the properties of a single row in a
  2997. * sheet. Rows and cells in a sheet are divided into blocks
  2998. * of 32 rows.
  2999. *
  3000. * -- "OpenOffice.org's Documentation of the Microsoft
  3001. * Excel File Format"
  3002. */
  3003. private function readRow()
  3004. {
  3005. $length = self::getUInt2d($this->data, $this->pos + 2);
  3006. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3007. // move stream pointer to next record
  3008. $this->pos += 4 + $length;
  3009. if (!$this->readDataOnly) {
  3010. // offset: 0; size: 2; index of this row
  3011. $r = self::getUInt2d($recordData, 0);
  3012. // offset: 2; size: 2; index to column of the first cell which is described by a cell record
  3013. // offset: 4; size: 2; index to column of the last cell which is described by a cell record, increased by 1
  3014. // offset: 6; size: 2;
  3015. // bit: 14-0; mask: 0x7FFF; height of the row, in twips = 1/20 of a point
  3016. $height = (0x7FFF & self::getUInt2d($recordData, 6)) >> 0;
  3017. // bit: 15: mask: 0x8000; 0 = row has custom height; 1= row has default height
  3018. $useDefaultHeight = (0x8000 & self::getUInt2d($recordData, 6)) >> 15;
  3019. if (!$useDefaultHeight) {
  3020. $this->phpSheet->getRowDimension($r + 1)->setRowHeight($height / 20);
  3021. }
  3022. // offset: 8; size: 2; not used
  3023. // offset: 10; size: 2; not used in BIFF5-BIFF8
  3024. // offset: 12; size: 4; option flags and default row formatting
  3025. // bit: 2-0: mask: 0x00000007; outline level of the row
  3026. $level = (0x00000007 & self::getInt4d($recordData, 12)) >> 0;
  3027. $this->phpSheet->getRowDimension($r + 1)->setOutlineLevel($level);
  3028. // bit: 4; mask: 0x00000010; 1 = outline group start or ends here... and is collapsed
  3029. $isCollapsed = (0x00000010 & self::getInt4d($recordData, 12)) >> 4;
  3030. $this->phpSheet->getRowDimension($r + 1)->setCollapsed($isCollapsed);
  3031. // bit: 5; mask: 0x00000020; 1 = row is hidden
  3032. $isHidden = (0x00000020 & self::getInt4d($recordData, 12)) >> 5;
  3033. $this->phpSheet->getRowDimension($r + 1)->setVisible(!$isHidden);
  3034. // bit: 7; mask: 0x00000080; 1 = row has explicit format
  3035. $hasExplicitFormat = (0x00000080 & self::getInt4d($recordData, 12)) >> 7;
  3036. // bit: 27-16; mask: 0x0FFF0000; only applies when hasExplicitFormat = 1; index to XF record
  3037. $xfIndex = (0x0FFF0000 & self::getInt4d($recordData, 12)) >> 16;
  3038. if ($hasExplicitFormat && isset($this->mapCellXfIndex[$xfIndex])) {
  3039. $this->phpSheet->getRowDimension($r + 1)->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  3040. }
  3041. }
  3042. }
  3043. /**
  3044. * Read RK record
  3045. * This record represents a cell that contains an RK value
  3046. * (encoded integer or floating-point value). If a
  3047. * floating-point value cannot be encoded to an RK value,
  3048. * a NUMBER record will be written. This record replaces the
  3049. * record INTEGER written in BIFF2.
  3050. *
  3051. * -- "OpenOffice.org's Documentation of the Microsoft
  3052. * Excel File Format"
  3053. */
  3054. private function readRk()
  3055. {
  3056. $length = self::getUInt2d($this->data, $this->pos + 2);
  3057. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3058. // move stream pointer to next record
  3059. $this->pos += 4 + $length;
  3060. // offset: 0; size: 2; index to row
  3061. $row = self::getUInt2d($recordData, 0);
  3062. // offset: 2; size: 2; index to column
  3063. $column = self::getUInt2d($recordData, 2);
  3064. $columnString = Coordinate::stringFromColumnIndex($column + 1);
  3065. // Read cell?
  3066. if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
  3067. // offset: 4; size: 2; index to XF record
  3068. $xfIndex = self::getUInt2d($recordData, 4);
  3069. // offset: 6; size: 4; RK value
  3070. $rknum = self::getInt4d($recordData, 6);
  3071. $numValue = self::getIEEE754($rknum);
  3072. $cell = $this->phpSheet->getCell($columnString . ($row + 1));
  3073. if (!$this->readDataOnly) {
  3074. // add style information
  3075. $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  3076. }
  3077. // add cell
  3078. $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC);
  3079. }
  3080. }
  3081. /**
  3082. * Read LABELSST record
  3083. * This record represents a cell that contains a string. It
  3084. * replaces the LABEL record and RSTRING record used in
  3085. * BIFF2-BIFF5.
  3086. *
  3087. * -- "OpenOffice.org's Documentation of the Microsoft
  3088. * Excel File Format"
  3089. */
  3090. private function readLabelSst()
  3091. {
  3092. $length = self::getUInt2d($this->data, $this->pos + 2);
  3093. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3094. // move stream pointer to next record
  3095. $this->pos += 4 + $length;
  3096. // offset: 0; size: 2; index to row
  3097. $row = self::getUInt2d($recordData, 0);
  3098. // offset: 2; size: 2; index to column
  3099. $column = self::getUInt2d($recordData, 2);
  3100. $columnString = Coordinate::stringFromColumnIndex($column + 1);
  3101. $emptyCell = true;
  3102. // Read cell?
  3103. if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
  3104. // offset: 4; size: 2; index to XF record
  3105. $xfIndex = self::getUInt2d($recordData, 4);
  3106. // offset: 6; size: 4; index to SST record
  3107. $index = self::getInt4d($recordData, 6);
  3108. // add cell
  3109. if (($fmtRuns = $this->sst[$index]['fmtRuns']) && !$this->readDataOnly) {
  3110. // then we should treat as rich text
  3111. $richText = new RichText();
  3112. $charPos = 0;
  3113. $sstCount = count($this->sst[$index]['fmtRuns']);
  3114. for ($i = 0; $i <= $sstCount; ++$i) {
  3115. if (isset($fmtRuns[$i])) {
  3116. $text = StringHelper::substring($this->sst[$index]['value'], $charPos, $fmtRuns[$i]['charPos'] - $charPos);
  3117. $charPos = $fmtRuns[$i]['charPos'];
  3118. } else {
  3119. $text = StringHelper::substring($this->sst[$index]['value'], $charPos, StringHelper::countCharacters($this->sst[$index]['value']));
  3120. }
  3121. if (StringHelper::countCharacters($text) > 0) {
  3122. if ($i == 0) { // first text run, no style
  3123. $richText->createText($text);
  3124. } else {
  3125. $textRun = $richText->createTextRun($text);
  3126. if (isset($fmtRuns[$i - 1])) {
  3127. if ($fmtRuns[$i - 1]['fontIndex'] < 4) {
  3128. $fontIndex = $fmtRuns[$i - 1]['fontIndex'];
  3129. } else {
  3130. // this has to do with that index 4 is omitted in all BIFF versions for some strange reason
  3131. // check the OpenOffice documentation of the FONT record
  3132. $fontIndex = $fmtRuns[$i - 1]['fontIndex'] - 1;
  3133. }
  3134. $textRun->setFont(clone $this->objFonts[$fontIndex]);
  3135. }
  3136. }
  3137. }
  3138. }
  3139. if ($this->readEmptyCells || trim($richText->getPlainText()) !== '') {
  3140. $cell = $this->phpSheet->getCell($columnString . ($row + 1));
  3141. $cell->setValueExplicit($richText, DataType::TYPE_STRING);
  3142. $emptyCell = false;
  3143. }
  3144. } else {
  3145. if ($this->readEmptyCells || trim($this->sst[$index]['value']) !== '') {
  3146. $cell = $this->phpSheet->getCell($columnString . ($row + 1));
  3147. $cell->setValueExplicit($this->sst[$index]['value'], DataType::TYPE_STRING);
  3148. $emptyCell = false;
  3149. }
  3150. }
  3151. if (!$this->readDataOnly && !$emptyCell) {
  3152. // add style information
  3153. $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  3154. }
  3155. }
  3156. }
  3157. /**
  3158. * Read MULRK record
  3159. * This record represents a cell range containing RK value
  3160. * cells. All cells are located in the same row.
  3161. *
  3162. * -- "OpenOffice.org's Documentation of the Microsoft
  3163. * Excel File Format"
  3164. */
  3165. private function readMulRk()
  3166. {
  3167. $length = self::getUInt2d($this->data, $this->pos + 2);
  3168. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3169. // move stream pointer to next record
  3170. $this->pos += 4 + $length;
  3171. // offset: 0; size: 2; index to row
  3172. $row = self::getUInt2d($recordData, 0);
  3173. // offset: 2; size: 2; index to first column
  3174. $colFirst = self::getUInt2d($recordData, 2);
  3175. // offset: var; size: 2; index to last column
  3176. $colLast = self::getUInt2d($recordData, $length - 2);
  3177. $columns = $colLast - $colFirst + 1;
  3178. // offset within record data
  3179. $offset = 4;
  3180. for ($i = 1; $i <= $columns; ++$i) {
  3181. $columnString = Coordinate::stringFromColumnIndex($colFirst + $i);
  3182. // Read cell?
  3183. if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
  3184. // offset: var; size: 2; index to XF record
  3185. $xfIndex = self::getUInt2d($recordData, $offset);
  3186. // offset: var; size: 4; RK value
  3187. $numValue = self::getIEEE754(self::getInt4d($recordData, $offset + 2));
  3188. $cell = $this->phpSheet->getCell($columnString . ($row + 1));
  3189. if (!$this->readDataOnly) {
  3190. // add style
  3191. $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  3192. }
  3193. // add cell value
  3194. $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC);
  3195. }
  3196. $offset += 6;
  3197. }
  3198. }
  3199. /**
  3200. * Read NUMBER record
  3201. * This record represents a cell that contains a
  3202. * floating-point value.
  3203. *
  3204. * -- "OpenOffice.org's Documentation of the Microsoft
  3205. * Excel File Format"
  3206. */
  3207. private function readNumber()
  3208. {
  3209. $length = self::getUInt2d($this->data, $this->pos + 2);
  3210. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3211. // move stream pointer to next record
  3212. $this->pos += 4 + $length;
  3213. // offset: 0; size: 2; index to row
  3214. $row = self::getUInt2d($recordData, 0);
  3215. // offset: 2; size 2; index to column
  3216. $column = self::getUInt2d($recordData, 2);
  3217. $columnString = Coordinate::stringFromColumnIndex($column + 1);
  3218. // Read cell?
  3219. if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
  3220. // offset 4; size: 2; index to XF record
  3221. $xfIndex = self::getUInt2d($recordData, 4);
  3222. $numValue = self::extractNumber(substr($recordData, 6, 8));
  3223. $cell = $this->phpSheet->getCell($columnString . ($row + 1));
  3224. if (!$this->readDataOnly) {
  3225. // add cell style
  3226. $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  3227. }
  3228. // add cell value
  3229. $cell->setValueExplicit($numValue, DataType::TYPE_NUMERIC);
  3230. }
  3231. }
  3232. /**
  3233. * Read FORMULA record + perhaps a following STRING record if formula result is a string
  3234. * This record contains the token array and the result of a
  3235. * formula cell.
  3236. *
  3237. * -- "OpenOffice.org's Documentation of the Microsoft
  3238. * Excel File Format"
  3239. */
  3240. private function readFormula()
  3241. {
  3242. $length = self::getUInt2d($this->data, $this->pos + 2);
  3243. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3244. // move stream pointer to next record
  3245. $this->pos += 4 + $length;
  3246. // offset: 0; size: 2; row index
  3247. $row = self::getUInt2d($recordData, 0);
  3248. // offset: 2; size: 2; col index
  3249. $column = self::getUInt2d($recordData, 2);
  3250. $columnString = Coordinate::stringFromColumnIndex($column + 1);
  3251. // offset: 20: size: variable; formula structure
  3252. $formulaStructure = substr($recordData, 20);
  3253. // offset: 14: size: 2; option flags, recalculate always, recalculate on open etc.
  3254. $options = self::getUInt2d($recordData, 14);
  3255. // bit: 0; mask: 0x0001; 1 = recalculate always
  3256. // bit: 1; mask: 0x0002; 1 = calculate on open
  3257. // bit: 2; mask: 0x0008; 1 = part of a shared formula
  3258. $isPartOfSharedFormula = (bool) (0x0008 & $options);
  3259. // WARNING:
  3260. // We can apparently not rely on $isPartOfSharedFormula. Even when $isPartOfSharedFormula = true
  3261. // the formula data may be ordinary formula data, therefore we need to check
  3262. // explicitly for the tExp token (0x01)
  3263. $isPartOfSharedFormula = $isPartOfSharedFormula && ord($formulaStructure[2]) == 0x01;
  3264. if ($isPartOfSharedFormula) {
  3265. // part of shared formula which means there will be a formula with a tExp token and nothing else
  3266. // get the base cell, grab tExp token
  3267. $baseRow = self::getUInt2d($formulaStructure, 3);
  3268. $baseCol = self::getUInt2d($formulaStructure, 5);
  3269. $this->baseCell = Coordinate::stringFromColumnIndex($baseCol + 1) . ($baseRow + 1);
  3270. }
  3271. // Read cell?
  3272. if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
  3273. if ($isPartOfSharedFormula) {
  3274. // formula is added to this cell after the sheet has been read
  3275. $this->sharedFormulaParts[$columnString . ($row + 1)] = $this->baseCell;
  3276. }
  3277. // offset: 16: size: 4; not used
  3278. // offset: 4; size: 2; XF index
  3279. $xfIndex = self::getUInt2d($recordData, 4);
  3280. // offset: 6; size: 8; result of the formula
  3281. if ((ord($recordData[6]) == 0) && (ord($recordData[12]) == 255) && (ord($recordData[13]) == 255)) {
  3282. // String formula. Result follows in appended STRING record
  3283. $dataType = DataType::TYPE_STRING;
  3284. // read possible SHAREDFMLA record
  3285. $code = self::getUInt2d($this->data, $this->pos);
  3286. if ($code == self::XLS_TYPE_SHAREDFMLA) {
  3287. $this->readSharedFmla();
  3288. }
  3289. // read STRING record
  3290. $value = $this->readString();
  3291. } elseif ((ord($recordData[6]) == 1)
  3292. && (ord($recordData[12]) == 255)
  3293. && (ord($recordData[13]) == 255)) {
  3294. // Boolean formula. Result is in +2; 0=false, 1=true
  3295. $dataType = DataType::TYPE_BOOL;
  3296. $value = (bool) ord($recordData[8]);
  3297. } elseif ((ord($recordData[6]) == 2)
  3298. && (ord($recordData[12]) == 255)
  3299. && (ord($recordData[13]) == 255)) {
  3300. // Error formula. Error code is in +2
  3301. $dataType = DataType::TYPE_ERROR;
  3302. $value = Xls\ErrorCode::lookup(ord($recordData[8]));
  3303. } elseif ((ord($recordData[6]) == 3)
  3304. && (ord($recordData[12]) == 255)
  3305. && (ord($recordData[13]) == 255)) {
  3306. // Formula result is a null string
  3307. $dataType = DataType::TYPE_NULL;
  3308. $value = '';
  3309. } else {
  3310. // forumla result is a number, first 14 bytes like _NUMBER record
  3311. $dataType = DataType::TYPE_NUMERIC;
  3312. $value = self::extractNumber(substr($recordData, 6, 8));
  3313. }
  3314. $cell = $this->phpSheet->getCell($columnString . ($row + 1));
  3315. if (!$this->readDataOnly) {
  3316. // add cell style
  3317. $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  3318. }
  3319. // store the formula
  3320. if (!$isPartOfSharedFormula) {
  3321. // not part of shared formula
  3322. // add cell value. If we can read formula, populate with formula, otherwise just used cached value
  3323. try {
  3324. if ($this->version != self::XLS_BIFF8) {
  3325. throw new Exception('Not BIFF8. Can only read BIFF8 formulas');
  3326. }
  3327. $formula = $this->getFormulaFromStructure($formulaStructure); // get formula in human language
  3328. $cell->setValueExplicit('=' . $formula, DataType::TYPE_FORMULA);
  3329. } catch (PhpSpreadsheetException $e) {
  3330. $cell->setValueExplicit($value, $dataType);
  3331. }
  3332. } else {
  3333. if ($this->version == self::XLS_BIFF8) {
  3334. // do nothing at this point, formula id added later in the code
  3335. } else {
  3336. $cell->setValueExplicit($value, $dataType);
  3337. }
  3338. }
  3339. // store the cached calculated value
  3340. $cell->setCalculatedValue($value);
  3341. }
  3342. }
  3343. /**
  3344. * Read a SHAREDFMLA record. This function just stores the binary shared formula in the reader,
  3345. * which usually contains relative references.
  3346. * These will be used to construct the formula in each shared formula part after the sheet is read.
  3347. */
  3348. private function readSharedFmla()
  3349. {
  3350. $length = self::getUInt2d($this->data, $this->pos + 2);
  3351. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3352. // move stream pointer to next record
  3353. $this->pos += 4 + $length;
  3354. // offset: 0, size: 6; cell range address of the area used by the shared formula, not used for anything
  3355. $cellRange = substr($recordData, 0, 6);
  3356. $cellRange = $this->readBIFF5CellRangeAddressFixed($cellRange); // note: even BIFF8 uses BIFF5 syntax
  3357. // offset: 6, size: 1; not used
  3358. // offset: 7, size: 1; number of existing FORMULA records for this shared formula
  3359. $no = ord($recordData[7]);
  3360. // offset: 8, size: var; Binary token array of the shared formula
  3361. $formula = substr($recordData, 8);
  3362. // at this point we only store the shared formula for later use
  3363. $this->sharedFormulas[$this->baseCell] = $formula;
  3364. }
  3365. /**
  3366. * Read a STRING record from current stream position and advance the stream pointer to next record
  3367. * This record is used for storing result from FORMULA record when it is a string, and
  3368. * it occurs directly after the FORMULA record.
  3369. *
  3370. * @return string The string contents as UTF-8
  3371. */
  3372. private function readString()
  3373. {
  3374. $length = self::getUInt2d($this->data, $this->pos + 2);
  3375. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3376. // move stream pointer to next record
  3377. $this->pos += 4 + $length;
  3378. if ($this->version == self::XLS_BIFF8) {
  3379. $string = self::readUnicodeStringLong($recordData);
  3380. $value = $string['value'];
  3381. } else {
  3382. $string = $this->readByteStringLong($recordData);
  3383. $value = $string['value'];
  3384. }
  3385. return $value;
  3386. }
  3387. /**
  3388. * Read BOOLERR record
  3389. * This record represents a Boolean value or error value
  3390. * cell.
  3391. *
  3392. * -- "OpenOffice.org's Documentation of the Microsoft
  3393. * Excel File Format"
  3394. */
  3395. private function readBoolErr()
  3396. {
  3397. $length = self::getUInt2d($this->data, $this->pos + 2);
  3398. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3399. // move stream pointer to next record
  3400. $this->pos += 4 + $length;
  3401. // offset: 0; size: 2; row index
  3402. $row = self::getUInt2d($recordData, 0);
  3403. // offset: 2; size: 2; column index
  3404. $column = self::getUInt2d($recordData, 2);
  3405. $columnString = Coordinate::stringFromColumnIndex($column + 1);
  3406. // Read cell?
  3407. if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
  3408. // offset: 4; size: 2; index to XF record
  3409. $xfIndex = self::getUInt2d($recordData, 4);
  3410. // offset: 6; size: 1; the boolean value or error value
  3411. $boolErr = ord($recordData[6]);
  3412. // offset: 7; size: 1; 0=boolean; 1=error
  3413. $isError = ord($recordData[7]);
  3414. $cell = $this->phpSheet->getCell($columnString . ($row + 1));
  3415. switch ($isError) {
  3416. case 0: // boolean
  3417. $value = (bool) $boolErr;
  3418. // add cell value
  3419. $cell->setValueExplicit($value, DataType::TYPE_BOOL);
  3420. break;
  3421. case 1: // error type
  3422. $value = Xls\ErrorCode::lookup($boolErr);
  3423. // add cell value
  3424. $cell->setValueExplicit($value, DataType::TYPE_ERROR);
  3425. break;
  3426. }
  3427. if (!$this->readDataOnly) {
  3428. // add cell style
  3429. $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  3430. }
  3431. }
  3432. }
  3433. /**
  3434. * Read MULBLANK record
  3435. * This record represents a cell range of empty cells. All
  3436. * cells are located in the same row.
  3437. *
  3438. * -- "OpenOffice.org's Documentation of the Microsoft
  3439. * Excel File Format"
  3440. */
  3441. private function readMulBlank()
  3442. {
  3443. $length = self::getUInt2d($this->data, $this->pos + 2);
  3444. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3445. // move stream pointer to next record
  3446. $this->pos += 4 + $length;
  3447. // offset: 0; size: 2; index to row
  3448. $row = self::getUInt2d($recordData, 0);
  3449. // offset: 2; size: 2; index to first column
  3450. $fc = self::getUInt2d($recordData, 2);
  3451. // offset: 4; size: 2 x nc; list of indexes to XF records
  3452. // add style information
  3453. if (!$this->readDataOnly && $this->readEmptyCells) {
  3454. for ($i = 0; $i < $length / 2 - 3; ++$i) {
  3455. $columnString = Coordinate::stringFromColumnIndex($fc + $i + 1);
  3456. // Read cell?
  3457. if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
  3458. $xfIndex = self::getUInt2d($recordData, 4 + 2 * $i);
  3459. $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  3460. }
  3461. }
  3462. }
  3463. // offset: 6; size 2; index to last column (not needed)
  3464. }
  3465. /**
  3466. * Read LABEL record
  3467. * This record represents a cell that contains a string. In
  3468. * BIFF8 it is usually replaced by the LABELSST record.
  3469. * Excel still uses this record, if it copies unformatted
  3470. * text cells to the clipboard.
  3471. *
  3472. * -- "OpenOffice.org's Documentation of the Microsoft
  3473. * Excel File Format"
  3474. */
  3475. private function readLabel()
  3476. {
  3477. $length = self::getUInt2d($this->data, $this->pos + 2);
  3478. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3479. // move stream pointer to next record
  3480. $this->pos += 4 + $length;
  3481. // offset: 0; size: 2; index to row
  3482. $row = self::getUInt2d($recordData, 0);
  3483. // offset: 2; size: 2; index to column
  3484. $column = self::getUInt2d($recordData, 2);
  3485. $columnString = Coordinate::stringFromColumnIndex($column + 1);
  3486. // Read cell?
  3487. if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
  3488. // offset: 4; size: 2; XF index
  3489. $xfIndex = self::getUInt2d($recordData, 4);
  3490. // add cell value
  3491. // todo: what if string is very long? continue record
  3492. if ($this->version == self::XLS_BIFF8) {
  3493. $string = self::readUnicodeStringLong(substr($recordData, 6));
  3494. $value = $string['value'];
  3495. } else {
  3496. $string = $this->readByteStringLong(substr($recordData, 6));
  3497. $value = $string['value'];
  3498. }
  3499. if ($this->readEmptyCells || trim($value) !== '') {
  3500. $cell = $this->phpSheet->getCell($columnString . ($row + 1));
  3501. $cell->setValueExplicit($value, DataType::TYPE_STRING);
  3502. if (!$this->readDataOnly) {
  3503. // add cell style
  3504. $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  3505. }
  3506. }
  3507. }
  3508. }
  3509. /**
  3510. * Read BLANK record.
  3511. */
  3512. private function readBlank()
  3513. {
  3514. $length = self::getUInt2d($this->data, $this->pos + 2);
  3515. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3516. // move stream pointer to next record
  3517. $this->pos += 4 + $length;
  3518. // offset: 0; size: 2; row index
  3519. $row = self::getUInt2d($recordData, 0);
  3520. // offset: 2; size: 2; col index
  3521. $col = self::getUInt2d($recordData, 2);
  3522. $columnString = Coordinate::stringFromColumnIndex($col + 1);
  3523. // Read cell?
  3524. if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) {
  3525. // offset: 4; size: 2; XF index
  3526. $xfIndex = self::getUInt2d($recordData, 4);
  3527. // add style information
  3528. if (!$this->readDataOnly && $this->readEmptyCells) {
  3529. $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]);
  3530. }
  3531. }
  3532. }
  3533. /**
  3534. * Read MSODRAWING record.
  3535. */
  3536. private function readMsoDrawing()
  3537. {
  3538. $length = self::getUInt2d($this->data, $this->pos + 2);
  3539. // get spliced record data
  3540. $splicedRecordData = $this->getSplicedRecordData();
  3541. $recordData = $splicedRecordData['recordData'];
  3542. $this->drawingData .= $recordData;
  3543. }
  3544. /**
  3545. * Read OBJ record.
  3546. */
  3547. private function readObj()
  3548. {
  3549. $length = self::getUInt2d($this->data, $this->pos + 2);
  3550. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3551. // move stream pointer to next record
  3552. $this->pos += 4 + $length;
  3553. if ($this->readDataOnly || $this->version != self::XLS_BIFF8) {
  3554. return;
  3555. }
  3556. // recordData consists of an array of subrecords looking like this:
  3557. // ft: 2 bytes; ftCmo type (0x15)
  3558. // cb: 2 bytes; size in bytes of ftCmo data
  3559. // ot: 2 bytes; Object Type
  3560. // id: 2 bytes; Object id number
  3561. // grbit: 2 bytes; Option Flags
  3562. // data: var; subrecord data
  3563. // for now, we are just interested in the second subrecord containing the object type
  3564. $ftCmoType = self::getUInt2d($recordData, 0);
  3565. $cbCmoSize = self::getUInt2d($recordData, 2);
  3566. $otObjType = self::getUInt2d($recordData, 4);
  3567. $idObjID = self::getUInt2d($recordData, 6);
  3568. $grbitOpts = self::getUInt2d($recordData, 6);
  3569. $this->objs[] = [
  3570. 'ftCmoType' => $ftCmoType,
  3571. 'cbCmoSize' => $cbCmoSize,
  3572. 'otObjType' => $otObjType,
  3573. 'idObjID' => $idObjID,
  3574. 'grbitOpts' => $grbitOpts,
  3575. ];
  3576. $this->textObjRef = $idObjID;
  3577. }
  3578. /**
  3579. * Read WINDOW2 record.
  3580. */
  3581. private function readWindow2()
  3582. {
  3583. $length = self::getUInt2d($this->data, $this->pos + 2);
  3584. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3585. // move stream pointer to next record
  3586. $this->pos += 4 + $length;
  3587. // offset: 0; size: 2; option flags
  3588. $options = self::getUInt2d($recordData, 0);
  3589. // offset: 2; size: 2; index to first visible row
  3590. $firstVisibleRow = self::getUInt2d($recordData, 2);
  3591. // offset: 4; size: 2; index to first visible colum
  3592. $firstVisibleColumn = self::getUInt2d($recordData, 4);
  3593. if ($this->version === self::XLS_BIFF8) {
  3594. // offset: 8; size: 2; not used
  3595. // offset: 10; size: 2; cached magnification factor in page break preview (in percent); 0 = Default (60%)
  3596. // offset: 12; size: 2; cached magnification factor in normal view (in percent); 0 = Default (100%)
  3597. // offset: 14; size: 4; not used
  3598. $zoomscaleInPageBreakPreview = self::getUInt2d($recordData, 10);
  3599. if ($zoomscaleInPageBreakPreview === 0) {
  3600. $zoomscaleInPageBreakPreview = 60;
  3601. }
  3602. $zoomscaleInNormalView = self::getUInt2d($recordData, 12);
  3603. if ($zoomscaleInNormalView === 0) {
  3604. $zoomscaleInNormalView = 100;
  3605. }
  3606. }
  3607. // bit: 1; mask: 0x0002; 0 = do not show gridlines, 1 = show gridlines
  3608. $showGridlines = (bool) ((0x0002 & $options) >> 1);
  3609. $this->phpSheet->setShowGridlines($showGridlines);
  3610. // bit: 2; mask: 0x0004; 0 = do not show headers, 1 = show headers
  3611. $showRowColHeaders = (bool) ((0x0004 & $options) >> 2);
  3612. $this->phpSheet->setShowRowColHeaders($showRowColHeaders);
  3613. // bit: 3; mask: 0x0008; 0 = panes are not frozen, 1 = panes are frozen
  3614. $this->frozen = (bool) ((0x0008 & $options) >> 3);
  3615. // bit: 6; mask: 0x0040; 0 = columns from left to right, 1 = columns from right to left
  3616. $this->phpSheet->setRightToLeft((bool) ((0x0040 & $options) >> 6));
  3617. // bit: 10; mask: 0x0400; 0 = sheet not active, 1 = sheet active
  3618. $isActive = (bool) ((0x0400 & $options) >> 10);
  3619. if ($isActive) {
  3620. $this->spreadsheet->setActiveSheetIndex($this->spreadsheet->getIndex($this->phpSheet));
  3621. }
  3622. // bit: 11; mask: 0x0800; 0 = normal view, 1 = page break view
  3623. $isPageBreakPreview = (bool) ((0x0800 & $options) >> 11);
  3624. //FIXME: set $firstVisibleRow and $firstVisibleColumn
  3625. if ($this->phpSheet->getSheetView()->getView() !== SheetView::SHEETVIEW_PAGE_LAYOUT) {
  3626. //NOTE: this setting is inferior to page layout view(Excel2007-)
  3627. $view = $isPageBreakPreview ? SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW : SheetView::SHEETVIEW_NORMAL;
  3628. $this->phpSheet->getSheetView()->setView($view);
  3629. if ($this->version === self::XLS_BIFF8) {
  3630. $zoomScale = $isPageBreakPreview ? $zoomscaleInPageBreakPreview : $zoomscaleInNormalView;
  3631. $this->phpSheet->getSheetView()->setZoomScale($zoomScale);
  3632. $this->phpSheet->getSheetView()->setZoomScaleNormal($zoomscaleInNormalView);
  3633. }
  3634. }
  3635. }
  3636. /**
  3637. * Read PLV Record(Created by Excel2007 or upper).
  3638. */
  3639. private function readPageLayoutView()
  3640. {
  3641. $length = self::getUInt2d($this->data, $this->pos + 2);
  3642. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3643. // move stream pointer to next record
  3644. $this->pos += 4 + $length;
  3645. // offset: 0; size: 2; rt
  3646. //->ignore
  3647. $rt = self::getUInt2d($recordData, 0);
  3648. // offset: 2; size: 2; grbitfr
  3649. //->ignore
  3650. $grbitFrt = self::getUInt2d($recordData, 2);
  3651. // offset: 4; size: 8; reserved
  3652. //->ignore
  3653. // offset: 12; size 2; zoom scale
  3654. $wScalePLV = self::getUInt2d($recordData, 12);
  3655. // offset: 14; size 2; grbit
  3656. $grbit = self::getUInt2d($recordData, 14);
  3657. // decomprise grbit
  3658. $fPageLayoutView = $grbit & 0x01;
  3659. $fRulerVisible = ($grbit >> 1) & 0x01; //no support
  3660. $fWhitespaceHidden = ($grbit >> 3) & 0x01; //no support
  3661. if ($fPageLayoutView === 1) {
  3662. $this->phpSheet->getSheetView()->setView(SheetView::SHEETVIEW_PAGE_LAYOUT);
  3663. $this->phpSheet->getSheetView()->setZoomScale($wScalePLV); //set by Excel2007 only if SHEETVIEW_PAGE_LAYOUT
  3664. }
  3665. //otherwise, we cannot know whether SHEETVIEW_PAGE_LAYOUT or SHEETVIEW_PAGE_BREAK_PREVIEW.
  3666. }
  3667. /**
  3668. * Read SCL record.
  3669. */
  3670. private function readScl()
  3671. {
  3672. $length = self::getUInt2d($this->data, $this->pos + 2);
  3673. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3674. // move stream pointer to next record
  3675. $this->pos += 4 + $length;
  3676. // offset: 0; size: 2; numerator of the view magnification
  3677. $numerator = self::getUInt2d($recordData, 0);
  3678. // offset: 2; size: 2; numerator of the view magnification
  3679. $denumerator = self::getUInt2d($recordData, 2);
  3680. // set the zoom scale (in percent)
  3681. $this->phpSheet->getSheetView()->setZoomScale($numerator * 100 / $denumerator);
  3682. }
  3683. /**
  3684. * Read PANE record.
  3685. */
  3686. private function readPane()
  3687. {
  3688. $length = self::getUInt2d($this->data, $this->pos + 2);
  3689. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3690. // move stream pointer to next record
  3691. $this->pos += 4 + $length;
  3692. if (!$this->readDataOnly) {
  3693. // offset: 0; size: 2; position of vertical split
  3694. $px = self::getUInt2d($recordData, 0);
  3695. // offset: 2; size: 2; position of horizontal split
  3696. $py = self::getUInt2d($recordData, 2);
  3697. // offset: 4; size: 2; top most visible row in the bottom pane
  3698. $rwTop = self::getUInt2d($recordData, 4);
  3699. // offset: 6; size: 2; first visible left column in the right pane
  3700. $colLeft = self::getUInt2d($recordData, 6);
  3701. if ($this->frozen) {
  3702. // frozen panes
  3703. $cell = Coordinate::stringFromColumnIndex($px + 1) . ($py + 1);
  3704. $topLeftCell = Coordinate::stringFromColumnIndex($colLeft + 1) . ($rwTop + 1);
  3705. $this->phpSheet->freezePane($cell, $topLeftCell);
  3706. }
  3707. // unfrozen panes; split windows; not supported by PhpSpreadsheet core
  3708. }
  3709. }
  3710. /**
  3711. * Read SELECTION record. There is one such record for each pane in the sheet.
  3712. */
  3713. private function readSelection()
  3714. {
  3715. $length = self::getUInt2d($this->data, $this->pos + 2);
  3716. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3717. // move stream pointer to next record
  3718. $this->pos += 4 + $length;
  3719. if (!$this->readDataOnly) {
  3720. // offset: 0; size: 1; pane identifier
  3721. $paneId = ord($recordData[0]);
  3722. // offset: 1; size: 2; index to row of the active cell
  3723. $r = self::getUInt2d($recordData, 1);
  3724. // offset: 3; size: 2; index to column of the active cell
  3725. $c = self::getUInt2d($recordData, 3);
  3726. // offset: 5; size: 2; index into the following cell range list to the
  3727. // entry that contains the active cell
  3728. $index = self::getUInt2d($recordData, 5);
  3729. // offset: 7; size: var; cell range address list containing all selected cell ranges
  3730. $data = substr($recordData, 7);
  3731. $cellRangeAddressList = $this->readBIFF5CellRangeAddressList($data); // note: also BIFF8 uses BIFF5 syntax
  3732. $selectedCells = $cellRangeAddressList['cellRangeAddresses'][0];
  3733. // first row '1' + last row '16384' indicates that full column is selected (apparently also in BIFF8!)
  3734. if (preg_match('/^([A-Z]+1\:[A-Z]+)16384$/', $selectedCells)) {
  3735. $selectedCells = preg_replace('/^([A-Z]+1\:[A-Z]+)16384$/', '${1}1048576', $selectedCells);
  3736. }
  3737. // first row '1' + last row '65536' indicates that full column is selected
  3738. if (preg_match('/^([A-Z]+1\:[A-Z]+)65536$/', $selectedCells)) {
  3739. $selectedCells = preg_replace('/^([A-Z]+1\:[A-Z]+)65536$/', '${1}1048576', $selectedCells);
  3740. }
  3741. // first column 'A' + last column 'IV' indicates that full row is selected
  3742. if (preg_match('/^(A\d+\:)IV(\d+)$/', $selectedCells)) {
  3743. $selectedCells = preg_replace('/^(A\d+\:)IV(\d+)$/', '${1}XFD${2}', $selectedCells);
  3744. }
  3745. $this->phpSheet->setSelectedCells($selectedCells);
  3746. }
  3747. }
  3748. private function includeCellRangeFiltered($cellRangeAddress)
  3749. {
  3750. $includeCellRange = true;
  3751. if ($this->getReadFilter() !== null) {
  3752. $includeCellRange = false;
  3753. $rangeBoundaries = Coordinate::getRangeBoundaries($cellRangeAddress);
  3754. ++$rangeBoundaries[1][0];
  3755. for ($row = $rangeBoundaries[0][1]; $row <= $rangeBoundaries[1][1]; ++$row) {
  3756. for ($column = $rangeBoundaries[0][0]; $column != $rangeBoundaries[1][0]; ++$column) {
  3757. if ($this->getReadFilter()->readCell($column, $row, $this->phpSheet->getTitle())) {
  3758. $includeCellRange = true;
  3759. break 2;
  3760. }
  3761. }
  3762. }
  3763. }
  3764. return $includeCellRange;
  3765. }
  3766. /**
  3767. * MERGEDCELLS.
  3768. *
  3769. * This record contains the addresses of merged cell ranges
  3770. * in the current sheet.
  3771. *
  3772. * -- "OpenOffice.org's Documentation of the Microsoft
  3773. * Excel File Format"
  3774. */
  3775. private function readMergedCells()
  3776. {
  3777. $length = self::getUInt2d($this->data, $this->pos + 2);
  3778. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3779. // move stream pointer to next record
  3780. $this->pos += 4 + $length;
  3781. if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) {
  3782. $cellRangeAddressList = $this->readBIFF8CellRangeAddressList($recordData);
  3783. foreach ($cellRangeAddressList['cellRangeAddresses'] as $cellRangeAddress) {
  3784. if ((strpos($cellRangeAddress, ':') !== false) &&
  3785. ($this->includeCellRangeFiltered($cellRangeAddress))) {
  3786. $this->phpSheet->mergeCells($cellRangeAddress);
  3787. }
  3788. }
  3789. }
  3790. }
  3791. /**
  3792. * Read HYPERLINK record.
  3793. */
  3794. private function readHyperLink()
  3795. {
  3796. $length = self::getUInt2d($this->data, $this->pos + 2);
  3797. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3798. // move stream pointer forward to next record
  3799. $this->pos += 4 + $length;
  3800. if (!$this->readDataOnly) {
  3801. // offset: 0; size: 8; cell range address of all cells containing this hyperlink
  3802. try {
  3803. $cellRange = $this->readBIFF8CellRangeAddressFixed($recordData);
  3804. } catch (PhpSpreadsheetException $e) {
  3805. return;
  3806. }
  3807. // offset: 8, size: 16; GUID of StdLink
  3808. // offset: 24, size: 4; unknown value
  3809. // offset: 28, size: 4; option flags
  3810. // bit: 0; mask: 0x00000001; 0 = no link or extant, 1 = file link or URL
  3811. $isFileLinkOrUrl = (0x00000001 & self::getUInt2d($recordData, 28)) >> 0;
  3812. // bit: 1; mask: 0x00000002; 0 = relative path, 1 = absolute path or URL
  3813. $isAbsPathOrUrl = (0x00000001 & self::getUInt2d($recordData, 28)) >> 1;
  3814. // bit: 2 (and 4); mask: 0x00000014; 0 = no description
  3815. $hasDesc = (0x00000014 & self::getUInt2d($recordData, 28)) >> 2;
  3816. // bit: 3; mask: 0x00000008; 0 = no text, 1 = has text
  3817. $hasText = (0x00000008 & self::getUInt2d($recordData, 28)) >> 3;
  3818. // bit: 7; mask: 0x00000080; 0 = no target frame, 1 = has target frame
  3819. $hasFrame = (0x00000080 & self::getUInt2d($recordData, 28)) >> 7;
  3820. // bit: 8; mask: 0x00000100; 0 = file link or URL, 1 = UNC path (inc. server name)
  3821. $isUNC = (0x00000100 & self::getUInt2d($recordData, 28)) >> 8;
  3822. // offset within record data
  3823. $offset = 32;
  3824. if ($hasDesc) {
  3825. // offset: 32; size: var; character count of description text
  3826. $dl = self::getInt4d($recordData, 32);
  3827. // offset: 36; size: var; character array of description text, no Unicode string header, always 16-bit characters, zero terminated
  3828. $desc = self::encodeUTF16(substr($recordData, 36, 2 * ($dl - 1)), false);
  3829. $offset += 4 + 2 * $dl;
  3830. }
  3831. if ($hasFrame) {
  3832. $fl = self::getInt4d($recordData, $offset);
  3833. $offset += 4 + 2 * $fl;
  3834. }
  3835. // detect type of hyperlink (there are 4 types)
  3836. $hyperlinkType = null;
  3837. if ($isUNC) {
  3838. $hyperlinkType = 'UNC';
  3839. } elseif (!$isFileLinkOrUrl) {
  3840. $hyperlinkType = 'workbook';
  3841. } elseif (ord($recordData[$offset]) == 0x03) {
  3842. $hyperlinkType = 'local';
  3843. } elseif (ord($recordData[$offset]) == 0xE0) {
  3844. $hyperlinkType = 'URL';
  3845. }
  3846. switch ($hyperlinkType) {
  3847. case 'URL':
  3848. // section 5.58.2: Hyperlink containing a URL
  3849. // e.g. http://example.org/index.php
  3850. // offset: var; size: 16; GUID of URL Moniker
  3851. $offset += 16;
  3852. // offset: var; size: 4; size (in bytes) of character array of the URL including trailing zero word
  3853. $us = self::getInt4d($recordData, $offset);
  3854. $offset += 4;
  3855. // offset: var; size: $us; character array of the URL, no Unicode string header, always 16-bit characters, zero-terminated
  3856. $url = self::encodeUTF16(substr($recordData, $offset, $us - 2), false);
  3857. $nullOffset = strpos($url, chr(0x00));
  3858. if ($nullOffset) {
  3859. $url = substr($url, 0, $nullOffset);
  3860. }
  3861. $url .= $hasText ? '#' : '';
  3862. $offset += $us;
  3863. break;
  3864. case 'local':
  3865. // section 5.58.3: Hyperlink to local file
  3866. // examples:
  3867. // mydoc.txt
  3868. // ../../somedoc.xls#Sheet!A1
  3869. // offset: var; size: 16; GUI of File Moniker
  3870. $offset += 16;
  3871. // offset: var; size: 2; directory up-level count.
  3872. $upLevelCount = self::getUInt2d($recordData, $offset);
  3873. $offset += 2;
  3874. // offset: var; size: 4; character count of the shortened file path and name, including trailing zero word
  3875. $sl = self::getInt4d($recordData, $offset);
  3876. $offset += 4;
  3877. // offset: var; size: sl; character array of the shortened file path and name in 8.3-DOS-format (compressed Unicode string)
  3878. $shortenedFilePath = substr($recordData, $offset, $sl);
  3879. $shortenedFilePath = self::encodeUTF16($shortenedFilePath, true);
  3880. $shortenedFilePath = substr($shortenedFilePath, 0, -1); // remove trailing zero
  3881. $offset += $sl;
  3882. // offset: var; size: 24; unknown sequence
  3883. $offset += 24;
  3884. // extended file path
  3885. // offset: var; size: 4; size of the following file link field including string lenth mark
  3886. $sz = self::getInt4d($recordData, $offset);
  3887. $offset += 4;
  3888. // only present if $sz > 0
  3889. if ($sz > 0) {
  3890. // offset: var; size: 4; size of the character array of the extended file path and name
  3891. $xl = self::getInt4d($recordData, $offset);
  3892. $offset += 4;
  3893. // offset: var; size 2; unknown
  3894. $offset += 2;
  3895. // offset: var; size $xl; character array of the extended file path and name.
  3896. $extendedFilePath = substr($recordData, $offset, $xl);
  3897. $extendedFilePath = self::encodeUTF16($extendedFilePath, false);
  3898. $offset += $xl;
  3899. }
  3900. // construct the path
  3901. $url = str_repeat('..\\', $upLevelCount);
  3902. $url .= ($sz > 0) ? $extendedFilePath : $shortenedFilePath; // use extended path if available
  3903. $url .= $hasText ? '#' : '';
  3904. break;
  3905. case 'UNC':
  3906. // section 5.58.4: Hyperlink to a File with UNC (Universal Naming Convention) Path
  3907. // todo: implement
  3908. return;
  3909. case 'workbook':
  3910. // section 5.58.5: Hyperlink to the Current Workbook
  3911. // e.g. Sheet2!B1:C2, stored in text mark field
  3912. $url = 'sheet://';
  3913. break;
  3914. default:
  3915. return;
  3916. }
  3917. if ($hasText) {
  3918. // offset: var; size: 4; character count of text mark including trailing zero word
  3919. $tl = self::getInt4d($recordData, $offset);
  3920. $offset += 4;
  3921. // offset: var; size: var; character array of the text mark without the # sign, no Unicode header, always 16-bit characters, zero-terminated
  3922. $text = self::encodeUTF16(substr($recordData, $offset, 2 * ($tl - 1)), false);
  3923. $url .= $text;
  3924. }
  3925. // apply the hyperlink to all the relevant cells
  3926. foreach (Coordinate::extractAllCellReferencesInRange($cellRange) as $coordinate) {
  3927. $this->phpSheet->getCell($coordinate)->getHyperLink()->setUrl($url);
  3928. }
  3929. }
  3930. }
  3931. /**
  3932. * Read DATAVALIDATIONS record.
  3933. */
  3934. private function readDataValidations()
  3935. {
  3936. $length = self::getUInt2d($this->data, $this->pos + 2);
  3937. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3938. // move stream pointer forward to next record
  3939. $this->pos += 4 + $length;
  3940. }
  3941. /**
  3942. * Read DATAVALIDATION record.
  3943. */
  3944. private function readDataValidation()
  3945. {
  3946. $length = self::getUInt2d($this->data, $this->pos + 2);
  3947. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  3948. // move stream pointer forward to next record
  3949. $this->pos += 4 + $length;
  3950. if ($this->readDataOnly) {
  3951. return;
  3952. }
  3953. // offset: 0; size: 4; Options
  3954. $options = self::getInt4d($recordData, 0);
  3955. // bit: 0-3; mask: 0x0000000F; type
  3956. $type = (0x0000000F & $options) >> 0;
  3957. switch ($type) {
  3958. case 0x00:
  3959. $type = DataValidation::TYPE_NONE;
  3960. break;
  3961. case 0x01:
  3962. $type = DataValidation::TYPE_WHOLE;
  3963. break;
  3964. case 0x02:
  3965. $type = DataValidation::TYPE_DECIMAL;
  3966. break;
  3967. case 0x03:
  3968. $type = DataValidation::TYPE_LIST;
  3969. break;
  3970. case 0x04:
  3971. $type = DataValidation::TYPE_DATE;
  3972. break;
  3973. case 0x05:
  3974. $type = DataValidation::TYPE_TIME;
  3975. break;
  3976. case 0x06:
  3977. $type = DataValidation::TYPE_TEXTLENGTH;
  3978. break;
  3979. case 0x07:
  3980. $type = DataValidation::TYPE_CUSTOM;
  3981. break;
  3982. }
  3983. // bit: 4-6; mask: 0x00000070; error type
  3984. $errorStyle = (0x00000070 & $options) >> 4;
  3985. switch ($errorStyle) {
  3986. case 0x00:
  3987. $errorStyle = DataValidation::STYLE_STOP;
  3988. break;
  3989. case 0x01:
  3990. $errorStyle = DataValidation::STYLE_WARNING;
  3991. break;
  3992. case 0x02:
  3993. $errorStyle = DataValidation::STYLE_INFORMATION;
  3994. break;
  3995. }
  3996. // bit: 7; mask: 0x00000080; 1= formula is explicit (only applies to list)
  3997. // I have only seen cases where this is 1
  3998. $explicitFormula = (0x00000080 & $options) >> 7;
  3999. // bit: 8; mask: 0x00000100; 1= empty cells allowed
  4000. $allowBlank = (0x00000100 & $options) >> 8;
  4001. // bit: 9; mask: 0x00000200; 1= suppress drop down arrow in list type validity
  4002. $suppressDropDown = (0x00000200 & $options) >> 9;
  4003. // bit: 18; mask: 0x00040000; 1= show prompt box if cell selected
  4004. $showInputMessage = (0x00040000 & $options) >> 18;
  4005. // bit: 19; mask: 0x00080000; 1= show error box if invalid values entered
  4006. $showErrorMessage = (0x00080000 & $options) >> 19;
  4007. // bit: 20-23; mask: 0x00F00000; condition operator
  4008. $operator = (0x00F00000 & $options) >> 20;
  4009. switch ($operator) {
  4010. case 0x00:
  4011. $operator = DataValidation::OPERATOR_BETWEEN;
  4012. break;
  4013. case 0x01:
  4014. $operator = DataValidation::OPERATOR_NOTBETWEEN;
  4015. break;
  4016. case 0x02:
  4017. $operator = DataValidation::OPERATOR_EQUAL;
  4018. break;
  4019. case 0x03:
  4020. $operator = DataValidation::OPERATOR_NOTEQUAL;
  4021. break;
  4022. case 0x04:
  4023. $operator = DataValidation::OPERATOR_GREATERTHAN;
  4024. break;
  4025. case 0x05:
  4026. $operator = DataValidation::OPERATOR_LESSTHAN;
  4027. break;
  4028. case 0x06:
  4029. $operator = DataValidation::OPERATOR_GREATERTHANOREQUAL;
  4030. break;
  4031. case 0x07:
  4032. $operator = DataValidation::OPERATOR_LESSTHANOREQUAL;
  4033. break;
  4034. }
  4035. // offset: 4; size: var; title of the prompt box
  4036. $offset = 4;
  4037. $string = self::readUnicodeStringLong(substr($recordData, $offset));
  4038. $promptTitle = $string['value'] !== chr(0) ? $string['value'] : '';
  4039. $offset += $string['size'];
  4040. // offset: var; size: var; title of the error box
  4041. $string = self::readUnicodeStringLong(substr($recordData, $offset));
  4042. $errorTitle = $string['value'] !== chr(0) ? $string['value'] : '';
  4043. $offset += $string['size'];
  4044. // offset: var; size: var; text of the prompt box
  4045. $string = self::readUnicodeStringLong(substr($recordData, $offset));
  4046. $prompt = $string['value'] !== chr(0) ? $string['value'] : '';
  4047. $offset += $string['size'];
  4048. // offset: var; size: var; text of the error box
  4049. $string = self::readUnicodeStringLong(substr($recordData, $offset));
  4050. $error = $string['value'] !== chr(0) ? $string['value'] : '';
  4051. $offset += $string['size'];
  4052. // offset: var; size: 2; size of the formula data for the first condition
  4053. $sz1 = self::getUInt2d($recordData, $offset);
  4054. $offset += 2;
  4055. // offset: var; size: 2; not used
  4056. $offset += 2;
  4057. // offset: var; size: $sz1; formula data for first condition (without size field)
  4058. $formula1 = substr($recordData, $offset, $sz1);
  4059. $formula1 = pack('v', $sz1) . $formula1; // prepend the length
  4060. try {
  4061. $formula1 = $this->getFormulaFromStructure($formula1);
  4062. // in list type validity, null characters are used as item separators
  4063. if ($type == DataValidation::TYPE_LIST) {
  4064. $formula1 = str_replace(chr(0), ',', $formula1);
  4065. }
  4066. } catch (PhpSpreadsheetException $e) {
  4067. return;
  4068. }
  4069. $offset += $sz1;
  4070. // offset: var; size: 2; size of the formula data for the first condition
  4071. $sz2 = self::getUInt2d($recordData, $offset);
  4072. $offset += 2;
  4073. // offset: var; size: 2; not used
  4074. $offset += 2;
  4075. // offset: var; size: $sz2; formula data for second condition (without size field)
  4076. $formula2 = substr($recordData, $offset, $sz2);
  4077. $formula2 = pack('v', $sz2) . $formula2; // prepend the length
  4078. try {
  4079. $formula2 = $this->getFormulaFromStructure($formula2);
  4080. } catch (PhpSpreadsheetException $e) {
  4081. return;
  4082. }
  4083. $offset += $sz2;
  4084. // offset: var; size: var; cell range address list with
  4085. $cellRangeAddressList = $this->readBIFF8CellRangeAddressList(substr($recordData, $offset));
  4086. $cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses'];
  4087. foreach ($cellRangeAddresses as $cellRange) {
  4088. $stRange = $this->phpSheet->shrinkRangeToFit($cellRange);
  4089. foreach (Coordinate::extractAllCellReferencesInRange($stRange) as $coordinate) {
  4090. $objValidation = $this->phpSheet->getCell($coordinate)->getDataValidation();
  4091. $objValidation->setType($type);
  4092. $objValidation->setErrorStyle($errorStyle);
  4093. $objValidation->setAllowBlank((bool) $allowBlank);
  4094. $objValidation->setShowInputMessage((bool) $showInputMessage);
  4095. $objValidation->setShowErrorMessage((bool) $showErrorMessage);
  4096. $objValidation->setShowDropDown(!$suppressDropDown);
  4097. $objValidation->setOperator($operator);
  4098. $objValidation->setErrorTitle($errorTitle);
  4099. $objValidation->setError($error);
  4100. $objValidation->setPromptTitle($promptTitle);
  4101. $objValidation->setPrompt($prompt);
  4102. $objValidation->setFormula1($formula1);
  4103. $objValidation->setFormula2($formula2);
  4104. }
  4105. }
  4106. }
  4107. /**
  4108. * Read SHEETLAYOUT record. Stores sheet tab color information.
  4109. */
  4110. private function readSheetLayout()
  4111. {
  4112. $length = self::getUInt2d($this->data, $this->pos + 2);
  4113. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  4114. // move stream pointer to next record
  4115. $this->pos += 4 + $length;
  4116. // local pointer in record data
  4117. $offset = 0;
  4118. if (!$this->readDataOnly) {
  4119. // offset: 0; size: 2; repeated record identifier 0x0862
  4120. // offset: 2; size: 10; not used
  4121. // offset: 12; size: 4; size of record data
  4122. // Excel 2003 uses size of 0x14 (documented), Excel 2007 uses size of 0x28 (not documented?)
  4123. $sz = self::getInt4d($recordData, 12);
  4124. switch ($sz) {
  4125. case 0x14:
  4126. // offset: 16; size: 2; color index for sheet tab
  4127. $colorIndex = self::getUInt2d($recordData, 16);
  4128. $color = Xls\Color::map($colorIndex, $this->palette, $this->version);
  4129. $this->phpSheet->getTabColor()->setRGB($color['rgb']);
  4130. break;
  4131. case 0x28:
  4132. // TODO: Investigate structure for .xls SHEETLAYOUT record as saved by MS Office Excel 2007
  4133. return;
  4134. break;
  4135. }
  4136. }
  4137. }
  4138. /**
  4139. * Read SHEETPROTECTION record (FEATHEADR).
  4140. */
  4141. private function readSheetProtection()
  4142. {
  4143. $length = self::getUInt2d($this->data, $this->pos + 2);
  4144. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  4145. // move stream pointer to next record
  4146. $this->pos += 4 + $length;
  4147. if ($this->readDataOnly) {
  4148. return;
  4149. }
  4150. // offset: 0; size: 2; repeated record header
  4151. // offset: 2; size: 2; FRT cell reference flag (=0 currently)
  4152. // offset: 4; size: 8; Currently not used and set to 0
  4153. // offset: 12; size: 2; Shared feature type index (2=Enhanced Protetion, 4=SmartTag)
  4154. $isf = self::getUInt2d($recordData, 12);
  4155. if ($isf != 2) {
  4156. return;
  4157. }
  4158. // offset: 14; size: 1; =1 since this is a feat header
  4159. // offset: 15; size: 4; size of rgbHdrSData
  4160. // rgbHdrSData, assume "Enhanced Protection"
  4161. // offset: 19; size: 2; option flags
  4162. $options = self::getUInt2d($recordData, 19);
  4163. // bit: 0; mask 0x0001; 1 = user may edit objects, 0 = users must not edit objects
  4164. $bool = (0x0001 & $options) >> 0;
  4165. $this->phpSheet->getProtection()->setObjects(!$bool);
  4166. // bit: 1; mask 0x0002; edit scenarios
  4167. $bool = (0x0002 & $options) >> 1;
  4168. $this->phpSheet->getProtection()->setScenarios(!$bool);
  4169. // bit: 2; mask 0x0004; format cells
  4170. $bool = (0x0004 & $options) >> 2;
  4171. $this->phpSheet->getProtection()->setFormatCells(!$bool);
  4172. // bit: 3; mask 0x0008; format columns
  4173. $bool = (0x0008 & $options) >> 3;
  4174. $this->phpSheet->getProtection()->setFormatColumns(!$bool);
  4175. // bit: 4; mask 0x0010; format rows
  4176. $bool = (0x0010 & $options) >> 4;
  4177. $this->phpSheet->getProtection()->setFormatRows(!$bool);
  4178. // bit: 5; mask 0x0020; insert columns
  4179. $bool = (0x0020 & $options) >> 5;
  4180. $this->phpSheet->getProtection()->setInsertColumns(!$bool);
  4181. // bit: 6; mask 0x0040; insert rows
  4182. $bool = (0x0040 & $options) >> 6;
  4183. $this->phpSheet->getProtection()->setInsertRows(!$bool);
  4184. // bit: 7; mask 0x0080; insert hyperlinks
  4185. $bool = (0x0080 & $options) >> 7;
  4186. $this->phpSheet->getProtection()->setInsertHyperlinks(!$bool);
  4187. // bit: 8; mask 0x0100; delete columns
  4188. $bool = (0x0100 & $options) >> 8;
  4189. $this->phpSheet->getProtection()->setDeleteColumns(!$bool);
  4190. // bit: 9; mask 0x0200; delete rows
  4191. $bool = (0x0200 & $options) >> 9;
  4192. $this->phpSheet->getProtection()->setDeleteRows(!$bool);
  4193. // bit: 10; mask 0x0400; select locked cells
  4194. $bool = (0x0400 & $options) >> 10;
  4195. $this->phpSheet->getProtection()->setSelectLockedCells(!$bool);
  4196. // bit: 11; mask 0x0800; sort cell range
  4197. $bool = (0x0800 & $options) >> 11;
  4198. $this->phpSheet->getProtection()->setSort(!$bool);
  4199. // bit: 12; mask 0x1000; auto filter
  4200. $bool = (0x1000 & $options) >> 12;
  4201. $this->phpSheet->getProtection()->setAutoFilter(!$bool);
  4202. // bit: 13; mask 0x2000; pivot tables
  4203. $bool = (0x2000 & $options) >> 13;
  4204. $this->phpSheet->getProtection()->setPivotTables(!$bool);
  4205. // bit: 14; mask 0x4000; select unlocked cells
  4206. $bool = (0x4000 & $options) >> 14;
  4207. $this->phpSheet->getProtection()->setSelectUnlockedCells(!$bool);
  4208. // offset: 21; size: 2; not used
  4209. }
  4210. /**
  4211. * Read RANGEPROTECTION record
  4212. * Reading of this record is based on Microsoft Office Excel 97-2000 Binary File Format Specification,
  4213. * where it is referred to as FEAT record.
  4214. */
  4215. private function readRangeProtection()
  4216. {
  4217. $length = self::getUInt2d($this->data, $this->pos + 2);
  4218. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  4219. // move stream pointer to next record
  4220. $this->pos += 4 + $length;
  4221. // local pointer in record data
  4222. $offset = 0;
  4223. if (!$this->readDataOnly) {
  4224. $offset += 12;
  4225. // offset: 12; size: 2; shared feature type, 2 = enhanced protection, 4 = smart tag
  4226. $isf = self::getUInt2d($recordData, 12);
  4227. if ($isf != 2) {
  4228. // we only read FEAT records of type 2
  4229. return;
  4230. }
  4231. $offset += 2;
  4232. $offset += 5;
  4233. // offset: 19; size: 2; count of ref ranges this feature is on
  4234. $cref = self::getUInt2d($recordData, 19);
  4235. $offset += 2;
  4236. $offset += 6;
  4237. // offset: 27; size: 8 * $cref; list of cell ranges (like in hyperlink record)
  4238. $cellRanges = [];
  4239. for ($i = 0; $i < $cref; ++$i) {
  4240. try {
  4241. $cellRange = $this->readBIFF8CellRangeAddressFixed(substr($recordData, 27 + 8 * $i, 8));
  4242. } catch (PhpSpreadsheetException $e) {
  4243. return;
  4244. }
  4245. $cellRanges[] = $cellRange;
  4246. $offset += 8;
  4247. }
  4248. // offset: var; size: var; variable length of feature specific data
  4249. $rgbFeat = substr($recordData, $offset);
  4250. $offset += 4;
  4251. // offset: var; size: 4; the encrypted password (only 16-bit although field is 32-bit)
  4252. $wPassword = self::getInt4d($recordData, $offset);
  4253. $offset += 4;
  4254. // Apply range protection to sheet
  4255. if ($cellRanges) {
  4256. $this->phpSheet->protectCells(implode(' ', $cellRanges), strtoupper(dechex($wPassword)), true);
  4257. }
  4258. }
  4259. }
  4260. /**
  4261. * Read a free CONTINUE record. Free CONTINUE record may be a camouflaged MSODRAWING record
  4262. * When MSODRAWING data on a sheet exceeds 8224 bytes, CONTINUE records are used instead. Undocumented.
  4263. * In this case, we must treat the CONTINUE record as a MSODRAWING record.
  4264. */
  4265. private function readContinue()
  4266. {
  4267. $length = self::getUInt2d($this->data, $this->pos + 2);
  4268. $recordData = $this->readRecordData($this->data, $this->pos + 4, $length);
  4269. // check if we are reading drawing data
  4270. // this is in case a free CONTINUE record occurs in other circumstances we are unaware of
  4271. if ($this->drawingData == '') {
  4272. // move stream pointer to next record
  4273. $this->pos += 4 + $length;
  4274. return;
  4275. }
  4276. // check if record data is at least 4 bytes long, otherwise there is no chance this is MSODRAWING data
  4277. if ($length < 4) {
  4278. // move stream pointer to next record
  4279. $this->pos += 4 + $length;
  4280. return;
  4281. }
  4282. // dirty check to see if CONTINUE record could be a camouflaged MSODRAWING record
  4283. // look inside CONTINUE record to see if it looks like a part of an Escher stream
  4284. // we know that Escher stream may be split at least at
  4285. // 0xF003 MsofbtSpgrContainer
  4286. // 0xF004 MsofbtSpContainer
  4287. // 0xF00D MsofbtClientTextbox
  4288. $validSplitPoints = [0xF003, 0xF004, 0xF00D]; // add identifiers if we find more
  4289. $splitPoint = self::getUInt2d($recordData, 2);
  4290. if (in_array($splitPoint, $validSplitPoints)) {
  4291. // get spliced record data (and move pointer to next record)
  4292. $splicedRecordData = $this->getSplicedRecordData();
  4293. $this->drawingData .= $splicedRecordData['recordData'];
  4294. return;
  4295. }
  4296. // move stream pointer to next record
  4297. $this->pos += 4 + $length;
  4298. }
  4299. /**
  4300. * Reads a record from current position in data stream and continues reading data as long as CONTINUE
  4301. * records are found. Splices the record data pieces and returns the combined string as if record data
  4302. * is in one piece.
  4303. * Moves to next current position in data stream to start of next record different from a CONtINUE record.
  4304. *
  4305. * @return array
  4306. */
  4307. private function getSplicedRecordData()
  4308. {
  4309. $data = '';
  4310. $spliceOffsets = [];
  4311. $i = 0;
  4312. $spliceOffsets[0] = 0;
  4313. do {
  4314. ++$i;
  4315. // offset: 0; size: 2; identifier
  4316. $identifier = self::getUInt2d($this->data, $this->pos);
  4317. // offset: 2; size: 2; length
  4318. $length = self::getUInt2d($this->data, $this->pos + 2);
  4319. $data .= $this->readRecordData($this->data, $this->pos + 4, $length);
  4320. $spliceOffsets[$i] = $spliceOffsets[$i - 1] + $length;
  4321. $this->pos += 4 + $length;
  4322. $nextIdentifier = self::getUInt2d($this->data, $this->pos);
  4323. } while ($nextIdentifier == self::XLS_TYPE_CONTINUE);
  4324. $splicedData = [
  4325. 'recordData' => $data,
  4326. 'spliceOffsets' => $spliceOffsets,
  4327. ];
  4328. return $splicedData;
  4329. }
  4330. /**
  4331. * Convert formula structure into human readable Excel formula like 'A3+A5*5'.
  4332. *
  4333. * @param string $formulaStructure The complete binary data for the formula
  4334. * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
  4335. *
  4336. * @return string Human readable formula
  4337. */
  4338. private function getFormulaFromStructure($formulaStructure, $baseCell = 'A1')
  4339. {
  4340. // offset: 0; size: 2; size of the following formula data
  4341. $sz = self::getUInt2d($formulaStructure, 0);
  4342. // offset: 2; size: sz
  4343. $formulaData = substr($formulaStructure, 2, $sz);
  4344. // offset: 2 + sz; size: variable (optional)
  4345. if (strlen($formulaStructure) > 2 + $sz) {
  4346. $additionalData = substr($formulaStructure, 2 + $sz);
  4347. } else {
  4348. $additionalData = '';
  4349. }
  4350. return $this->getFormulaFromData($formulaData, $additionalData, $baseCell);
  4351. }
  4352. /**
  4353. * Take formula data and additional data for formula and return human readable formula.
  4354. *
  4355. * @param string $formulaData The binary data for the formula itself
  4356. * @param string $additionalData Additional binary data going with the formula
  4357. * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
  4358. *
  4359. * @return string Human readable formula
  4360. */
  4361. private function getFormulaFromData($formulaData, $additionalData = '', $baseCell = 'A1')
  4362. {
  4363. // start parsing the formula data
  4364. $tokens = [];
  4365. while (strlen($formulaData) > 0 and $token = $this->getNextToken($formulaData, $baseCell)) {
  4366. $tokens[] = $token;
  4367. $formulaData = substr($formulaData, $token['size']);
  4368. }
  4369. $formulaString = $this->createFormulaFromTokens($tokens, $additionalData);
  4370. return $formulaString;
  4371. }
  4372. /**
  4373. * Take array of tokens together with additional data for formula and return human readable formula.
  4374. *
  4375. * @param array $tokens
  4376. * @param string $additionalData Additional binary data going with the formula
  4377. *
  4378. * @return string Human readable formula
  4379. */
  4380. private function createFormulaFromTokens($tokens, $additionalData)
  4381. {
  4382. // empty formula?
  4383. if (empty($tokens)) {
  4384. return '';
  4385. }
  4386. $formulaStrings = [];
  4387. foreach ($tokens as $token) {
  4388. // initialize spaces
  4389. $space0 = isset($space0) ? $space0 : ''; // spaces before next token, not tParen
  4390. $space1 = isset($space1) ? $space1 : ''; // carriage returns before next token, not tParen
  4391. $space2 = isset($space2) ? $space2 : ''; // spaces before opening parenthesis
  4392. $space3 = isset($space3) ? $space3 : ''; // carriage returns before opening parenthesis
  4393. $space4 = isset($space4) ? $space4 : ''; // spaces before closing parenthesis
  4394. $space5 = isset($space5) ? $space5 : ''; // carriage returns before closing parenthesis
  4395. switch ($token['name']) {
  4396. case 'tAdd': // addition
  4397. case 'tConcat': // addition
  4398. case 'tDiv': // division
  4399. case 'tEQ': // equality
  4400. case 'tGE': // greater than or equal
  4401. case 'tGT': // greater than
  4402. case 'tIsect': // intersection
  4403. case 'tLE': // less than or equal
  4404. case 'tList': // less than or equal
  4405. case 'tLT': // less than
  4406. case 'tMul': // multiplication
  4407. case 'tNE': // multiplication
  4408. case 'tPower': // power
  4409. case 'tRange': // range
  4410. case 'tSub': // subtraction
  4411. $op2 = array_pop($formulaStrings);
  4412. $op1 = array_pop($formulaStrings);
  4413. $formulaStrings[] = "$op1$space1$space0{$token['data']}$op2";
  4414. unset($space0, $space1);
  4415. break;
  4416. case 'tUplus': // unary plus
  4417. case 'tUminus': // unary minus
  4418. $op = array_pop($formulaStrings);
  4419. $formulaStrings[] = "$space1$space0{$token['data']}$op";
  4420. unset($space0, $space1);
  4421. break;
  4422. case 'tPercent': // percent sign
  4423. $op = array_pop($formulaStrings);
  4424. $formulaStrings[] = "$op$space1$space0{$token['data']}";
  4425. unset($space0, $space1);
  4426. break;
  4427. case 'tAttrVolatile': // indicates volatile function
  4428. case 'tAttrIf':
  4429. case 'tAttrSkip':
  4430. case 'tAttrChoose':
  4431. // token is only important for Excel formula evaluator
  4432. // do nothing
  4433. break;
  4434. case 'tAttrSpace': // space / carriage return
  4435. // space will be used when next token arrives, do not alter formulaString stack
  4436. switch ($token['data']['spacetype']) {
  4437. case 'type0':
  4438. $space0 = str_repeat(' ', $token['data']['spacecount']);
  4439. break;
  4440. case 'type1':
  4441. $space1 = str_repeat("\n", $token['data']['spacecount']);
  4442. break;
  4443. case 'type2':
  4444. $space2 = str_repeat(' ', $token['data']['spacecount']);
  4445. break;
  4446. case 'type3':
  4447. $space3 = str_repeat("\n", $token['data']['spacecount']);
  4448. break;
  4449. case 'type4':
  4450. $space4 = str_repeat(' ', $token['data']['spacecount']);
  4451. break;
  4452. case 'type5':
  4453. $space5 = str_repeat("\n", $token['data']['spacecount']);
  4454. break;
  4455. }
  4456. break;
  4457. case 'tAttrSum': // SUM function with one parameter
  4458. $op = array_pop($formulaStrings);
  4459. $formulaStrings[] = "{$space1}{$space0}SUM($op)";
  4460. unset($space0, $space1);
  4461. break;
  4462. case 'tFunc': // function with fixed number of arguments
  4463. case 'tFuncV': // function with variable number of arguments
  4464. if ($token['data']['function'] != '') {
  4465. // normal function
  4466. $ops = []; // array of operators
  4467. for ($i = 0; $i < $token['data']['args']; ++$i) {
  4468. $ops[] = array_pop($formulaStrings);
  4469. }
  4470. $ops = array_reverse($ops);
  4471. $formulaStrings[] = "$space1$space0{$token['data']['function']}(" . implode(',', $ops) . ')';
  4472. unset($space0, $space1);
  4473. } else {
  4474. // add-in function
  4475. $ops = []; // array of operators
  4476. for ($i = 0; $i < $token['data']['args'] - 1; ++$i) {
  4477. $ops[] = array_pop($formulaStrings);
  4478. }
  4479. $ops = array_reverse($ops);
  4480. $function = array_pop($formulaStrings);
  4481. $formulaStrings[] = "$space1$space0$function(" . implode(',', $ops) . ')';
  4482. unset($space0, $space1);
  4483. }
  4484. break;
  4485. case 'tParen': // parenthesis
  4486. $expression = array_pop($formulaStrings);
  4487. $formulaStrings[] = "$space3$space2($expression$space5$space4)";
  4488. unset($space2, $space3, $space4, $space5);
  4489. break;
  4490. case 'tArray': // array constant
  4491. $constantArray = self::readBIFF8ConstantArray($additionalData);
  4492. $formulaStrings[] = $space1 . $space0 . $constantArray['value'];
  4493. $additionalData = substr($additionalData, $constantArray['size']); // bite of chunk of additional data
  4494. unset($space0, $space1);
  4495. break;
  4496. case 'tMemArea':
  4497. // bite off chunk of additional data
  4498. $cellRangeAddressList = $this->readBIFF8CellRangeAddressList($additionalData);
  4499. $additionalData = substr($additionalData, $cellRangeAddressList['size']);
  4500. $formulaStrings[] = "$space1$space0{$token['data']}";
  4501. unset($space0, $space1);
  4502. break;
  4503. case 'tArea': // cell range address
  4504. case 'tBool': // boolean
  4505. case 'tErr': // error code
  4506. case 'tInt': // integer
  4507. case 'tMemErr':
  4508. case 'tMemFunc':
  4509. case 'tMissArg':
  4510. case 'tName':
  4511. case 'tNameX':
  4512. case 'tNum': // number
  4513. case 'tRef': // single cell reference
  4514. case 'tRef3d': // 3d cell reference
  4515. case 'tArea3d': // 3d cell range reference
  4516. case 'tRefN':
  4517. case 'tAreaN':
  4518. case 'tStr': // string
  4519. $formulaStrings[] = "$space1$space0{$token['data']}";
  4520. unset($space0, $space1);
  4521. break;
  4522. }
  4523. }
  4524. $formulaString = $formulaStrings[0];
  4525. return $formulaString;
  4526. }
  4527. /**
  4528. * Fetch next token from binary formula data.
  4529. *
  4530. * @param string $formulaData Formula data
  4531. * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
  4532. *
  4533. * @throws Exception
  4534. *
  4535. * @return array
  4536. */
  4537. private function getNextToken($formulaData, $baseCell = 'A1')
  4538. {
  4539. // offset: 0; size: 1; token id
  4540. $id = ord($formulaData[0]); // token id
  4541. $name = false; // initialize token name
  4542. switch ($id) {
  4543. case 0x03:
  4544. $name = 'tAdd';
  4545. $size = 1;
  4546. $data = '+';
  4547. break;
  4548. case 0x04:
  4549. $name = 'tSub';
  4550. $size = 1;
  4551. $data = '-';
  4552. break;
  4553. case 0x05:
  4554. $name = 'tMul';
  4555. $size = 1;
  4556. $data = '*';
  4557. break;
  4558. case 0x06:
  4559. $name = 'tDiv';
  4560. $size = 1;
  4561. $data = '/';
  4562. break;
  4563. case 0x07:
  4564. $name = 'tPower';
  4565. $size = 1;
  4566. $data = '^';
  4567. break;
  4568. case 0x08:
  4569. $name = 'tConcat';
  4570. $size = 1;
  4571. $data = '&';
  4572. break;
  4573. case 0x09:
  4574. $name = 'tLT';
  4575. $size = 1;
  4576. $data = '<';
  4577. break;
  4578. case 0x0A:
  4579. $name = 'tLE';
  4580. $size = 1;
  4581. $data = '<=';
  4582. break;
  4583. case 0x0B:
  4584. $name = 'tEQ';
  4585. $size = 1;
  4586. $data = '=';
  4587. break;
  4588. case 0x0C:
  4589. $name = 'tGE';
  4590. $size = 1;
  4591. $data = '>=';
  4592. break;
  4593. case 0x0D:
  4594. $name = 'tGT';
  4595. $size = 1;
  4596. $data = '>';
  4597. break;
  4598. case 0x0E:
  4599. $name = 'tNE';
  4600. $size = 1;
  4601. $data = '<>';
  4602. break;
  4603. case 0x0F:
  4604. $name = 'tIsect';
  4605. $size = 1;
  4606. $data = ' ';
  4607. break;
  4608. case 0x10:
  4609. $name = 'tList';
  4610. $size = 1;
  4611. $data = ',';
  4612. break;
  4613. case 0x11:
  4614. $name = 'tRange';
  4615. $size = 1;
  4616. $data = ':';
  4617. break;
  4618. case 0x12:
  4619. $name = 'tUplus';
  4620. $size = 1;
  4621. $data = '+';
  4622. break;
  4623. case 0x13:
  4624. $name = 'tUminus';
  4625. $size = 1;
  4626. $data = '-';
  4627. break;
  4628. case 0x14:
  4629. $name = 'tPercent';
  4630. $size = 1;
  4631. $data = '%';
  4632. break;
  4633. case 0x15: // parenthesis
  4634. $name = 'tParen';
  4635. $size = 1;
  4636. $data = null;
  4637. break;
  4638. case 0x16: // missing argument
  4639. $name = 'tMissArg';
  4640. $size = 1;
  4641. $data = '';
  4642. break;
  4643. case 0x17: // string
  4644. $name = 'tStr';
  4645. // offset: 1; size: var; Unicode string, 8-bit string length
  4646. $string = self::readUnicodeStringShort(substr($formulaData, 1));
  4647. $size = 1 + $string['size'];
  4648. $data = self::UTF8toExcelDoubleQuoted($string['value']);
  4649. break;
  4650. case 0x19: // Special attribute
  4651. // offset: 1; size: 1; attribute type flags:
  4652. switch (ord($formulaData[1])) {
  4653. case 0x01:
  4654. $name = 'tAttrVolatile';
  4655. $size = 4;
  4656. $data = null;
  4657. break;
  4658. case 0x02:
  4659. $name = 'tAttrIf';
  4660. $size = 4;
  4661. $data = null;
  4662. break;
  4663. case 0x04:
  4664. $name = 'tAttrChoose';
  4665. // offset: 2; size: 2; number of choices in the CHOOSE function ($nc, number of parameters decreased by 1)
  4666. $nc = self::getUInt2d($formulaData, 2);
  4667. // offset: 4; size: 2 * $nc
  4668. // offset: 4 + 2 * $nc; size: 2
  4669. $size = 2 * $nc + 6;
  4670. $data = null;
  4671. break;
  4672. case 0x08:
  4673. $name = 'tAttrSkip';
  4674. $size = 4;
  4675. $data = null;
  4676. break;
  4677. case 0x10:
  4678. $name = 'tAttrSum';
  4679. $size = 4;
  4680. $data = null;
  4681. break;
  4682. case 0x40:
  4683. case 0x41:
  4684. $name = 'tAttrSpace';
  4685. $size = 4;
  4686. // offset: 2; size: 2; space type and position
  4687. switch (ord($formulaData[2])) {
  4688. case 0x00:
  4689. $spacetype = 'type0';
  4690. break;
  4691. case 0x01:
  4692. $spacetype = 'type1';
  4693. break;
  4694. case 0x02:
  4695. $spacetype = 'type2';
  4696. break;
  4697. case 0x03:
  4698. $spacetype = 'type3';
  4699. break;
  4700. case 0x04:
  4701. $spacetype = 'type4';
  4702. break;
  4703. case 0x05:
  4704. $spacetype = 'type5';
  4705. break;
  4706. default:
  4707. throw new Exception('Unrecognized space type in tAttrSpace token');
  4708. break;
  4709. }
  4710. // offset: 3; size: 1; number of inserted spaces/carriage returns
  4711. $spacecount = ord($formulaData[3]);
  4712. $data = ['spacetype' => $spacetype, 'spacecount' => $spacecount];
  4713. break;
  4714. default:
  4715. throw new Exception('Unrecognized attribute flag in tAttr token');
  4716. break;
  4717. }
  4718. break;
  4719. case 0x1C: // error code
  4720. // offset: 1; size: 1; error code
  4721. $name = 'tErr';
  4722. $size = 2;
  4723. $data = Xls\ErrorCode::lookup(ord($formulaData[1]));
  4724. break;
  4725. case 0x1D: // boolean
  4726. // offset: 1; size: 1; 0 = false, 1 = true;
  4727. $name = 'tBool';
  4728. $size = 2;
  4729. $data = ord($formulaData[1]) ? 'TRUE' : 'FALSE';
  4730. break;
  4731. case 0x1E: // integer
  4732. // offset: 1; size: 2; unsigned 16-bit integer
  4733. $name = 'tInt';
  4734. $size = 3;
  4735. $data = self::getUInt2d($formulaData, 1);
  4736. break;
  4737. case 0x1F: // number
  4738. // offset: 1; size: 8;
  4739. $name = 'tNum';
  4740. $size = 9;
  4741. $data = self::extractNumber(substr($formulaData, 1));
  4742. $data = str_replace(',', '.', (string) $data); // in case non-English locale
  4743. break;
  4744. case 0x20: // array constant
  4745. case 0x40:
  4746. case 0x60:
  4747. // offset: 1; size: 7; not used
  4748. $name = 'tArray';
  4749. $size = 8;
  4750. $data = null;
  4751. break;
  4752. case 0x21: // function with fixed number of arguments
  4753. case 0x41:
  4754. case 0x61:
  4755. $name = 'tFunc';
  4756. $size = 3;
  4757. // offset: 1; size: 2; index to built-in sheet function
  4758. switch (self::getUInt2d($formulaData, 1)) {
  4759. case 2:
  4760. $function = 'ISNA';
  4761. $args = 1;
  4762. break;
  4763. case 3:
  4764. $function = 'ISERROR';
  4765. $args = 1;
  4766. break;
  4767. case 10:
  4768. $function = 'NA';
  4769. $args = 0;
  4770. break;
  4771. case 15:
  4772. $function = 'SIN';
  4773. $args = 1;
  4774. break;
  4775. case 16:
  4776. $function = 'COS';
  4777. $args = 1;
  4778. break;
  4779. case 17:
  4780. $function = 'TAN';
  4781. $args = 1;
  4782. break;
  4783. case 18:
  4784. $function = 'ATAN';
  4785. $args = 1;
  4786. break;
  4787. case 19:
  4788. $function = 'PI';
  4789. $args = 0;
  4790. break;
  4791. case 20:
  4792. $function = 'SQRT';
  4793. $args = 1;
  4794. break;
  4795. case 21:
  4796. $function = 'EXP';
  4797. $args = 1;
  4798. break;
  4799. case 22:
  4800. $function = 'LN';
  4801. $args = 1;
  4802. break;
  4803. case 23:
  4804. $function = 'LOG10';
  4805. $args = 1;
  4806. break;
  4807. case 24:
  4808. $function = 'ABS';
  4809. $args = 1;
  4810. break;
  4811. case 25:
  4812. $function = 'INT';
  4813. $args = 1;
  4814. break;
  4815. case 26:
  4816. $function = 'SIGN';
  4817. $args = 1;
  4818. break;
  4819. case 27:
  4820. $function = 'ROUND';
  4821. $args = 2;
  4822. break;
  4823. case 30:
  4824. $function = 'REPT';
  4825. $args = 2;
  4826. break;
  4827. case 31:
  4828. $function = 'MID';
  4829. $args = 3;
  4830. break;
  4831. case 32:
  4832. $function = 'LEN';
  4833. $args = 1;
  4834. break;
  4835. case 33:
  4836. $function = 'VALUE';
  4837. $args = 1;
  4838. break;
  4839. case 34:
  4840. $function = 'TRUE';
  4841. $args = 0;
  4842. break;
  4843. case 35:
  4844. $function = 'FALSE';
  4845. $args = 0;
  4846. break;
  4847. case 38:
  4848. $function = 'NOT';
  4849. $args = 1;
  4850. break;
  4851. case 39:
  4852. $function = 'MOD';
  4853. $args = 2;
  4854. break;
  4855. case 40:
  4856. $function = 'DCOUNT';
  4857. $args = 3;
  4858. break;
  4859. case 41:
  4860. $function = 'DSUM';
  4861. $args = 3;
  4862. break;
  4863. case 42:
  4864. $function = 'DAVERAGE';
  4865. $args = 3;
  4866. break;
  4867. case 43:
  4868. $function = 'DMIN';
  4869. $args = 3;
  4870. break;
  4871. case 44:
  4872. $function = 'DMAX';
  4873. $args = 3;
  4874. break;
  4875. case 45:
  4876. $function = 'DSTDEV';
  4877. $args = 3;
  4878. break;
  4879. case 48:
  4880. $function = 'TEXT';
  4881. $args = 2;
  4882. break;
  4883. case 61:
  4884. $function = 'MIRR';
  4885. $args = 3;
  4886. break;
  4887. case 63:
  4888. $function = 'RAND';
  4889. $args = 0;
  4890. break;
  4891. case 65:
  4892. $function = 'DATE';
  4893. $args = 3;
  4894. break;
  4895. case 66:
  4896. $function = 'TIME';
  4897. $args = 3;
  4898. break;
  4899. case 67:
  4900. $function = 'DAY';
  4901. $args = 1;
  4902. break;
  4903. case 68:
  4904. $function = 'MONTH';
  4905. $args = 1;
  4906. break;
  4907. case 69:
  4908. $function = 'YEAR';
  4909. $args = 1;
  4910. break;
  4911. case 71:
  4912. $function = 'HOUR';
  4913. $args = 1;
  4914. break;
  4915. case 72:
  4916. $function = 'MINUTE';
  4917. $args = 1;
  4918. break;
  4919. case 73:
  4920. $function = 'SECOND';
  4921. $args = 1;
  4922. break;
  4923. case 74:
  4924. $function = 'NOW';
  4925. $args = 0;
  4926. break;
  4927. case 75:
  4928. $function = 'AREAS';
  4929. $args = 1;
  4930. break;
  4931. case 76:
  4932. $function = 'ROWS';
  4933. $args = 1;
  4934. break;
  4935. case 77:
  4936. $function = 'COLUMNS';
  4937. $args = 1;
  4938. break;
  4939. case 83:
  4940. $function = 'TRANSPOSE';
  4941. $args = 1;
  4942. break;
  4943. case 86:
  4944. $function = 'TYPE';
  4945. $args = 1;
  4946. break;
  4947. case 97:
  4948. $function = 'ATAN2';
  4949. $args = 2;
  4950. break;
  4951. case 98:
  4952. $function = 'ASIN';
  4953. $args = 1;
  4954. break;
  4955. case 99:
  4956. $function = 'ACOS';
  4957. $args = 1;
  4958. break;
  4959. case 105:
  4960. $function = 'ISREF';
  4961. $args = 1;
  4962. break;
  4963. case 111:
  4964. $function = 'CHAR';
  4965. $args = 1;
  4966. break;
  4967. case 112:
  4968. $function = 'LOWER';
  4969. $args = 1;
  4970. break;
  4971. case 113:
  4972. $function = 'UPPER';
  4973. $args = 1;
  4974. break;
  4975. case 114:
  4976. $function = 'PROPER';
  4977. $args = 1;
  4978. break;
  4979. case 117:
  4980. $function = 'EXACT';
  4981. $args = 2;
  4982. break;
  4983. case 118:
  4984. $function = 'TRIM';
  4985. $args = 1;
  4986. break;
  4987. case 119:
  4988. $function = 'REPLACE';
  4989. $args = 4;
  4990. break;
  4991. case 121:
  4992. $function = 'CODE';
  4993. $args = 1;
  4994. break;
  4995. case 126:
  4996. $function = 'ISERR';
  4997. $args = 1;
  4998. break;
  4999. case 127:
  5000. $function = 'ISTEXT';
  5001. $args = 1;
  5002. break;
  5003. case 128:
  5004. $function = 'ISNUMBER';
  5005. $args = 1;
  5006. break;
  5007. case 129:
  5008. $function = 'ISBLANK';
  5009. $args = 1;
  5010. break;
  5011. case 130:
  5012. $function = 'T';
  5013. $args = 1;
  5014. break;
  5015. case 131:
  5016. $function = 'N';
  5017. $args = 1;
  5018. break;
  5019. case 140:
  5020. $function = 'DATEVALUE';
  5021. $args = 1;
  5022. break;
  5023. case 141:
  5024. $function = 'TIMEVALUE';
  5025. $args = 1;
  5026. break;
  5027. case 142:
  5028. $function = 'SLN';
  5029. $args = 3;
  5030. break;
  5031. case 143:
  5032. $function = 'SYD';
  5033. $args = 4;
  5034. break;
  5035. case 162:
  5036. $function = 'CLEAN';
  5037. $args = 1;
  5038. break;
  5039. case 163:
  5040. $function = 'MDETERM';
  5041. $args = 1;
  5042. break;
  5043. case 164:
  5044. $function = 'MINVERSE';
  5045. $args = 1;
  5046. break;
  5047. case 165:
  5048. $function = 'MMULT';
  5049. $args = 2;
  5050. break;
  5051. case 184:
  5052. $function = 'FACT';
  5053. $args = 1;
  5054. break;
  5055. case 189:
  5056. $function = 'DPRODUCT';
  5057. $args = 3;
  5058. break;
  5059. case 190:
  5060. $function = 'ISNONTEXT';
  5061. $args = 1;
  5062. break;
  5063. case 195:
  5064. $function = 'DSTDEVP';
  5065. $args = 3;
  5066. break;
  5067. case 196:
  5068. $function = 'DVARP';
  5069. $args = 3;
  5070. break;
  5071. case 198:
  5072. $function = 'ISLOGICAL';
  5073. $args = 1;
  5074. break;
  5075. case 199:
  5076. $function = 'DCOUNTA';
  5077. $args = 3;
  5078. break;
  5079. case 207:
  5080. $function = 'REPLACEB';
  5081. $args = 4;
  5082. break;
  5083. case 210:
  5084. $function = 'MIDB';
  5085. $args = 3;
  5086. break;
  5087. case 211:
  5088. $function = 'LENB';
  5089. $args = 1;
  5090. break;
  5091. case 212:
  5092. $function = 'ROUNDUP';
  5093. $args = 2;
  5094. break;
  5095. case 213:
  5096. $function = 'ROUNDDOWN';
  5097. $args = 2;
  5098. break;
  5099. case 214:
  5100. $function = 'ASC';
  5101. $args = 1;
  5102. break;
  5103. case 215:
  5104. $function = 'DBCS';
  5105. $args = 1;
  5106. break;
  5107. case 221:
  5108. $function = 'TODAY';
  5109. $args = 0;
  5110. break;
  5111. case 229:
  5112. $function = 'SINH';
  5113. $args = 1;
  5114. break;
  5115. case 230:
  5116. $function = 'COSH';
  5117. $args = 1;
  5118. break;
  5119. case 231:
  5120. $function = 'TANH';
  5121. $args = 1;
  5122. break;
  5123. case 232:
  5124. $function = 'ASINH';
  5125. $args = 1;
  5126. break;
  5127. case 233:
  5128. $function = 'ACOSH';
  5129. $args = 1;
  5130. break;
  5131. case 234:
  5132. $function = 'ATANH';
  5133. $args = 1;
  5134. break;
  5135. case 235:
  5136. $function = 'DGET';
  5137. $args = 3;
  5138. break;
  5139. case 244:
  5140. $function = 'INFO';
  5141. $args = 1;
  5142. break;
  5143. case 252:
  5144. $function = 'FREQUENCY';
  5145. $args = 2;
  5146. break;
  5147. case 261:
  5148. $function = 'ERROR.TYPE';
  5149. $args = 1;
  5150. break;
  5151. case 271:
  5152. $function = 'GAMMALN';
  5153. $args = 1;
  5154. break;
  5155. case 273:
  5156. $function = 'BINOMDIST';
  5157. $args = 4;
  5158. break;
  5159. case 274:
  5160. $function = 'CHIDIST';
  5161. $args = 2;
  5162. break;
  5163. case 275:
  5164. $function = 'CHIINV';
  5165. $args = 2;
  5166. break;
  5167. case 276:
  5168. $function = 'COMBIN';
  5169. $args = 2;
  5170. break;
  5171. case 277:
  5172. $function = 'CONFIDENCE';
  5173. $args = 3;
  5174. break;
  5175. case 278:
  5176. $function = 'CRITBINOM';
  5177. $args = 3;
  5178. break;
  5179. case 279:
  5180. $function = 'EVEN';
  5181. $args = 1;
  5182. break;
  5183. case 280:
  5184. $function = 'EXPONDIST';
  5185. $args = 3;
  5186. break;
  5187. case 281:
  5188. $function = 'FDIST';
  5189. $args = 3;
  5190. break;
  5191. case 282:
  5192. $function = 'FINV';
  5193. $args = 3;
  5194. break;
  5195. case 283:
  5196. $function = 'FISHER';
  5197. $args = 1;
  5198. break;
  5199. case 284:
  5200. $function = 'FISHERINV';
  5201. $args = 1;
  5202. break;
  5203. case 285:
  5204. $function = 'FLOOR';
  5205. $args = 2;
  5206. break;
  5207. case 286:
  5208. $function = 'GAMMADIST';
  5209. $args = 4;
  5210. break;
  5211. case 287:
  5212. $function = 'GAMMAINV';
  5213. $args = 3;
  5214. break;
  5215. case 288:
  5216. $function = 'CEILING';
  5217. $args = 2;
  5218. break;
  5219. case 289:
  5220. $function = 'HYPGEOMDIST';
  5221. $args = 4;
  5222. break;
  5223. case 290:
  5224. $function = 'LOGNORMDIST';
  5225. $args = 3;
  5226. break;
  5227. case 291:
  5228. $function = 'LOGINV';
  5229. $args = 3;
  5230. break;
  5231. case 292:
  5232. $function = 'NEGBINOMDIST';
  5233. $args = 3;
  5234. break;
  5235. case 293:
  5236. $function = 'NORMDIST';
  5237. $args = 4;
  5238. break;
  5239. case 294:
  5240. $function = 'NORMSDIST';
  5241. $args = 1;
  5242. break;
  5243. case 295:
  5244. $function = 'NORMINV';
  5245. $args = 3;
  5246. break;
  5247. case 296:
  5248. $function = 'NORMSINV';
  5249. $args = 1;
  5250. break;
  5251. case 297:
  5252. $function = 'STANDARDIZE';
  5253. $args = 3;
  5254. break;
  5255. case 298:
  5256. $function = 'ODD';
  5257. $args = 1;
  5258. break;
  5259. case 299:
  5260. $function = 'PERMUT';
  5261. $args = 2;
  5262. break;
  5263. case 300:
  5264. $function = 'POISSON';
  5265. $args = 3;
  5266. break;
  5267. case 301:
  5268. $function = 'TDIST';
  5269. $args = 3;
  5270. break;
  5271. case 302:
  5272. $function = 'WEIBULL';
  5273. $args = 4;
  5274. break;
  5275. case 303:
  5276. $function = 'SUMXMY2';
  5277. $args = 2;
  5278. break;
  5279. case 304:
  5280. $function = 'SUMX2MY2';
  5281. $args = 2;
  5282. break;
  5283. case 305:
  5284. $function = 'SUMX2PY2';
  5285. $args = 2;
  5286. break;
  5287. case 306:
  5288. $function = 'CHITEST';
  5289. $args = 2;
  5290. break;
  5291. case 307:
  5292. $function = 'CORREL';
  5293. $args = 2;
  5294. break;
  5295. case 308:
  5296. $function = 'COVAR';
  5297. $args = 2;
  5298. break;
  5299. case 309:
  5300. $function = 'FORECAST';
  5301. $args = 3;
  5302. break;
  5303. case 310:
  5304. $function = 'FTEST';
  5305. $args = 2;
  5306. break;
  5307. case 311:
  5308. $function = 'INTERCEPT';
  5309. $args = 2;
  5310. break;
  5311. case 312:
  5312. $function = 'PEARSON';
  5313. $args = 2;
  5314. break;
  5315. case 313:
  5316. $function = 'RSQ';
  5317. $args = 2;
  5318. break;
  5319. case 314:
  5320. $function = 'STEYX';
  5321. $args = 2;
  5322. break;
  5323. case 315:
  5324. $function = 'SLOPE';
  5325. $args = 2;
  5326. break;
  5327. case 316:
  5328. $function = 'TTEST';
  5329. $args = 4;
  5330. break;
  5331. case 325:
  5332. $function = 'LARGE';
  5333. $args = 2;
  5334. break;
  5335. case 326:
  5336. $function = 'SMALL';
  5337. $args = 2;
  5338. break;
  5339. case 327:
  5340. $function = 'QUARTILE';
  5341. $args = 2;
  5342. break;
  5343. case 328:
  5344. $function = 'PERCENTILE';
  5345. $args = 2;
  5346. break;
  5347. case 331:
  5348. $function = 'TRIMMEAN';
  5349. $args = 2;
  5350. break;
  5351. case 332:
  5352. $function = 'TINV';
  5353. $args = 2;
  5354. break;
  5355. case 337:
  5356. $function = 'POWER';
  5357. $args = 2;
  5358. break;
  5359. case 342:
  5360. $function = 'RADIANS';
  5361. $args = 1;
  5362. break;
  5363. case 343:
  5364. $function = 'DEGREES';
  5365. $args = 1;
  5366. break;
  5367. case 346:
  5368. $function = 'COUNTIF';
  5369. $args = 2;
  5370. break;
  5371. case 347:
  5372. $function = 'COUNTBLANK';
  5373. $args = 1;
  5374. break;
  5375. case 350:
  5376. $function = 'ISPMT';
  5377. $args = 4;
  5378. break;
  5379. case 351:
  5380. $function = 'DATEDIF';
  5381. $args = 3;
  5382. break;
  5383. case 352:
  5384. $function = 'DATESTRING';
  5385. $args = 1;
  5386. break;
  5387. case 353:
  5388. $function = 'NUMBERSTRING';
  5389. $args = 2;
  5390. break;
  5391. case 360:
  5392. $function = 'PHONETIC';
  5393. $args = 1;
  5394. break;
  5395. case 368:
  5396. $function = 'BAHTTEXT';
  5397. $args = 1;
  5398. break;
  5399. default:
  5400. throw new Exception('Unrecognized function in formula');
  5401. break;
  5402. }
  5403. $data = ['function' => $function, 'args' => $args];
  5404. break;
  5405. case 0x22: // function with variable number of arguments
  5406. case 0x42:
  5407. case 0x62:
  5408. $name = 'tFuncV';
  5409. $size = 4;
  5410. // offset: 1; size: 1; number of arguments
  5411. $args = ord($formulaData[1]);
  5412. // offset: 2: size: 2; index to built-in sheet function
  5413. $index = self::getUInt2d($formulaData, 2);
  5414. switch ($index) {
  5415. case 0:
  5416. $function = 'COUNT';
  5417. break;
  5418. case 1:
  5419. $function = 'IF';
  5420. break;
  5421. case 4:
  5422. $function = 'SUM';
  5423. break;
  5424. case 5:
  5425. $function = 'AVERAGE';
  5426. break;
  5427. case 6:
  5428. $function = 'MIN';
  5429. break;
  5430. case 7:
  5431. $function = 'MAX';
  5432. break;
  5433. case 8:
  5434. $function = 'ROW';
  5435. break;
  5436. case 9:
  5437. $function = 'COLUMN';
  5438. break;
  5439. case 11:
  5440. $function = 'NPV';
  5441. break;
  5442. case 12:
  5443. $function = 'STDEV';
  5444. break;
  5445. case 13:
  5446. $function = 'DOLLAR';
  5447. break;
  5448. case 14:
  5449. $function = 'FIXED';
  5450. break;
  5451. case 28:
  5452. $function = 'LOOKUP';
  5453. break;
  5454. case 29:
  5455. $function = 'INDEX';
  5456. break;
  5457. case 36:
  5458. $function = 'AND';
  5459. break;
  5460. case 37:
  5461. $function = 'OR';
  5462. break;
  5463. case 46:
  5464. $function = 'VAR';
  5465. break;
  5466. case 49:
  5467. $function = 'LINEST';
  5468. break;
  5469. case 50:
  5470. $function = 'TREND';
  5471. break;
  5472. case 51:
  5473. $function = 'LOGEST';
  5474. break;
  5475. case 52:
  5476. $function = 'GROWTH';
  5477. break;
  5478. case 56:
  5479. $function = 'PV';
  5480. break;
  5481. case 57:
  5482. $function = 'FV';
  5483. break;
  5484. case 58:
  5485. $function = 'NPER';
  5486. break;
  5487. case 59:
  5488. $function = 'PMT';
  5489. break;
  5490. case 60:
  5491. $function = 'RATE';
  5492. break;
  5493. case 62:
  5494. $function = 'IRR';
  5495. break;
  5496. case 64:
  5497. $function = 'MATCH';
  5498. break;
  5499. case 70:
  5500. $function = 'WEEKDAY';
  5501. break;
  5502. case 78:
  5503. $function = 'OFFSET';
  5504. break;
  5505. case 82:
  5506. $function = 'SEARCH';
  5507. break;
  5508. case 100:
  5509. $function = 'CHOOSE';
  5510. break;
  5511. case 101:
  5512. $function = 'HLOOKUP';
  5513. break;
  5514. case 102:
  5515. $function = 'VLOOKUP';
  5516. break;
  5517. case 109:
  5518. $function = 'LOG';
  5519. break;
  5520. case 115:
  5521. $function = 'LEFT';
  5522. break;
  5523. case 116:
  5524. $function = 'RIGHT';
  5525. break;
  5526. case 120:
  5527. $function = 'SUBSTITUTE';
  5528. break;
  5529. case 124:
  5530. $function = 'FIND';
  5531. break;
  5532. case 125:
  5533. $function = 'CELL';
  5534. break;
  5535. case 144:
  5536. $function = 'DDB';
  5537. break;
  5538. case 148:
  5539. $function = 'INDIRECT';
  5540. break;
  5541. case 167:
  5542. $function = 'IPMT';
  5543. break;
  5544. case 168:
  5545. $function = 'PPMT';
  5546. break;
  5547. case 169:
  5548. $function = 'COUNTA';
  5549. break;
  5550. case 183:
  5551. $function = 'PRODUCT';
  5552. break;
  5553. case 193:
  5554. $function = 'STDEVP';
  5555. break;
  5556. case 194:
  5557. $function = 'VARP';
  5558. break;
  5559. case 197:
  5560. $function = 'TRUNC';
  5561. break;
  5562. case 204:
  5563. $function = 'USDOLLAR';
  5564. break;
  5565. case 205:
  5566. $function = 'FINDB';
  5567. break;
  5568. case 206:
  5569. $function = 'SEARCHB';
  5570. break;
  5571. case 208:
  5572. $function = 'LEFTB';
  5573. break;
  5574. case 209:
  5575. $function = 'RIGHTB';
  5576. break;
  5577. case 216:
  5578. $function = 'RANK';
  5579. break;
  5580. case 219:
  5581. $function = 'ADDRESS';
  5582. break;
  5583. case 220:
  5584. $function = 'DAYS360';
  5585. break;
  5586. case 222:
  5587. $function = 'VDB';
  5588. break;
  5589. case 227:
  5590. $function = 'MEDIAN';
  5591. break;
  5592. case 228:
  5593. $function = 'SUMPRODUCT';
  5594. break;
  5595. case 247:
  5596. $function = 'DB';
  5597. break;
  5598. case 255:
  5599. $function = '';
  5600. break;
  5601. case 269:
  5602. $function = 'AVEDEV';
  5603. break;
  5604. case 270:
  5605. $function = 'BETADIST';
  5606. break;
  5607. case 272:
  5608. $function = 'BETAINV';
  5609. break;
  5610. case 317:
  5611. $function = 'PROB';
  5612. break;
  5613. case 318:
  5614. $function = 'DEVSQ';
  5615. break;
  5616. case 319:
  5617. $function = 'GEOMEAN';
  5618. break;
  5619. case 320:
  5620. $function = 'HARMEAN';
  5621. break;
  5622. case 321:
  5623. $function = 'SUMSQ';
  5624. break;
  5625. case 322:
  5626. $function = 'KURT';
  5627. break;
  5628. case 323:
  5629. $function = 'SKEW';
  5630. break;
  5631. case 324:
  5632. $function = 'ZTEST';
  5633. break;
  5634. case 329:
  5635. $function = 'PERCENTRANK';
  5636. break;
  5637. case 330:
  5638. $function = 'MODE';
  5639. break;
  5640. case 336:
  5641. $function = 'CONCATENATE';
  5642. break;
  5643. case 344:
  5644. $function = 'SUBTOTAL';
  5645. break;
  5646. case 345:
  5647. $function = 'SUMIF';
  5648. break;
  5649. case 354:
  5650. $function = 'ROMAN';
  5651. break;
  5652. case 358:
  5653. $function = 'GETPIVOTDATA';
  5654. break;
  5655. case 359:
  5656. $function = 'HYPERLINK';
  5657. break;
  5658. case 361:
  5659. $function = 'AVERAGEA';
  5660. break;
  5661. case 362:
  5662. $function = 'MAXA';
  5663. break;
  5664. case 363:
  5665. $function = 'MINA';
  5666. break;
  5667. case 364:
  5668. $function = 'STDEVPA';
  5669. break;
  5670. case 365:
  5671. $function = 'VARPA';
  5672. break;
  5673. case 366:
  5674. $function = 'STDEVA';
  5675. break;
  5676. case 367:
  5677. $function = 'VARA';
  5678. break;
  5679. default:
  5680. throw new Exception('Unrecognized function in formula');
  5681. break;
  5682. }
  5683. $data = ['function' => $function, 'args' => $args];
  5684. break;
  5685. case 0x23: // index to defined name
  5686. case 0x43:
  5687. case 0x63:
  5688. $name = 'tName';
  5689. $size = 5;
  5690. // offset: 1; size: 2; one-based index to definedname record
  5691. $definedNameIndex = self::getUInt2d($formulaData, 1) - 1;
  5692. // offset: 2; size: 2; not used
  5693. $data = $this->definedname[$definedNameIndex]['name'];
  5694. break;
  5695. case 0x24: // single cell reference e.g. A5
  5696. case 0x44:
  5697. case 0x64:
  5698. $name = 'tRef';
  5699. $size = 5;
  5700. $data = $this->readBIFF8CellAddress(substr($formulaData, 1, 4));
  5701. break;
  5702. case 0x25: // cell range reference to cells in the same sheet (2d)
  5703. case 0x45:
  5704. case 0x65:
  5705. $name = 'tArea';
  5706. $size = 9;
  5707. $data = $this->readBIFF8CellRangeAddress(substr($formulaData, 1, 8));
  5708. break;
  5709. case 0x26: // Constant reference sub-expression
  5710. case 0x46:
  5711. case 0x66:
  5712. $name = 'tMemArea';
  5713. // offset: 1; size: 4; not used
  5714. // offset: 5; size: 2; size of the following subexpression
  5715. $subSize = self::getUInt2d($formulaData, 5);
  5716. $size = 7 + $subSize;
  5717. $data = $this->getFormulaFromData(substr($formulaData, 7, $subSize));
  5718. break;
  5719. case 0x27: // Deleted constant reference sub-expression
  5720. case 0x47:
  5721. case 0x67:
  5722. $name = 'tMemErr';
  5723. // offset: 1; size: 4; not used
  5724. // offset: 5; size: 2; size of the following subexpression
  5725. $subSize = self::getUInt2d($formulaData, 5);
  5726. $size = 7 + $subSize;
  5727. $data = $this->getFormulaFromData(substr($formulaData, 7, $subSize));
  5728. break;
  5729. case 0x29: // Variable reference sub-expression
  5730. case 0x49:
  5731. case 0x69:
  5732. $name = 'tMemFunc';
  5733. // offset: 1; size: 2; size of the following sub-expression
  5734. $subSize = self::getUInt2d($formulaData, 1);
  5735. $size = 3 + $subSize;
  5736. $data = $this->getFormulaFromData(substr($formulaData, 3, $subSize));
  5737. break;
  5738. case 0x2C: // Relative 2d cell reference reference, used in shared formulas and some other places
  5739. case 0x4C:
  5740. case 0x6C:
  5741. $name = 'tRefN';
  5742. $size = 5;
  5743. $data = $this->readBIFF8CellAddressB(substr($formulaData, 1, 4), $baseCell);
  5744. break;
  5745. case 0x2D: // Relative 2d range reference
  5746. case 0x4D:
  5747. case 0x6D:
  5748. $name = 'tAreaN';
  5749. $size = 9;
  5750. $data = $this->readBIFF8CellRangeAddressB(substr($formulaData, 1, 8), $baseCell);
  5751. break;
  5752. case 0x39: // External name
  5753. case 0x59:
  5754. case 0x79:
  5755. $name = 'tNameX';
  5756. $size = 7;
  5757. // offset: 1; size: 2; index to REF entry in EXTERNSHEET record
  5758. // offset: 3; size: 2; one-based index to DEFINEDNAME or EXTERNNAME record
  5759. $index = self::getUInt2d($formulaData, 3);
  5760. // assume index is to EXTERNNAME record
  5761. $data = $this->externalNames[$index - 1]['name'];
  5762. // offset: 5; size: 2; not used
  5763. break;
  5764. case 0x3A: // 3d reference to cell
  5765. case 0x5A:
  5766. case 0x7A:
  5767. $name = 'tRef3d';
  5768. $size = 7;
  5769. try {
  5770. // offset: 1; size: 2; index to REF entry
  5771. $sheetRange = $this->readSheetRangeByRefIndex(self::getUInt2d($formulaData, 1));
  5772. // offset: 3; size: 4; cell address
  5773. $cellAddress = $this->readBIFF8CellAddress(substr($formulaData, 3, 4));
  5774. $data = "$sheetRange!$cellAddress";
  5775. } catch (PhpSpreadsheetException $e) {
  5776. // deleted sheet reference
  5777. $data = '#REF!';
  5778. }
  5779. break;
  5780. case 0x3B: // 3d reference to cell range
  5781. case 0x5B:
  5782. case 0x7B:
  5783. $name = 'tArea3d';
  5784. $size = 11;
  5785. try {
  5786. // offset: 1; size: 2; index to REF entry
  5787. $sheetRange = $this->readSheetRangeByRefIndex(self::getUInt2d($formulaData, 1));
  5788. // offset: 3; size: 8; cell address
  5789. $cellRangeAddress = $this->readBIFF8CellRangeAddress(substr($formulaData, 3, 8));
  5790. $data = "$sheetRange!$cellRangeAddress";
  5791. } catch (PhpSpreadsheetException $e) {
  5792. // deleted sheet reference
  5793. $data = '#REF!';
  5794. }
  5795. break;
  5796. // Unknown cases // don't know how to deal with
  5797. default:
  5798. throw new Exception('Unrecognized token ' . sprintf('%02X', $id) . ' in formula');
  5799. break;
  5800. }
  5801. return [
  5802. 'id' => $id,
  5803. 'name' => $name,
  5804. 'size' => $size,
  5805. 'data' => $data,
  5806. ];
  5807. }
  5808. /**
  5809. * Reads a cell address in BIFF8 e.g. 'A2' or '$A$2'
  5810. * section 3.3.4.
  5811. *
  5812. * @param string $cellAddressStructure
  5813. *
  5814. * @return string
  5815. */
  5816. private function readBIFF8CellAddress($cellAddressStructure)
  5817. {
  5818. // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767))
  5819. $row = self::getUInt2d($cellAddressStructure, 0) + 1;
  5820. // offset: 2; size: 2; index to column or column offset + relative flags
  5821. // bit: 7-0; mask 0x00FF; column index
  5822. $column = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($cellAddressStructure, 2)) + 1);
  5823. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  5824. if (!(0x4000 & self::getUInt2d($cellAddressStructure, 2))) {
  5825. $column = '$' . $column;
  5826. }
  5827. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  5828. if (!(0x8000 & self::getUInt2d($cellAddressStructure, 2))) {
  5829. $row = '$' . $row;
  5830. }
  5831. return $column . $row;
  5832. }
  5833. /**
  5834. * Reads a cell address in BIFF8 for shared formulas. Uses positive and negative values for row and column
  5835. * to indicate offsets from a base cell
  5836. * section 3.3.4.
  5837. *
  5838. * @param string $cellAddressStructure
  5839. * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas
  5840. *
  5841. * @return string
  5842. */
  5843. private function readBIFF8CellAddressB($cellAddressStructure, $baseCell = 'A1')
  5844. {
  5845. list($baseCol, $baseRow) = Coordinate::coordinateFromString($baseCell);
  5846. $baseCol = Coordinate::columnIndexFromString($baseCol) - 1;
  5847. // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767))
  5848. $rowIndex = self::getUInt2d($cellAddressStructure, 0);
  5849. $row = self::getUInt2d($cellAddressStructure, 0) + 1;
  5850. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  5851. if (!(0x4000 & self::getUInt2d($cellAddressStructure, 2))) {
  5852. // offset: 2; size: 2; index to column or column offset + relative flags
  5853. // bit: 7-0; mask 0x00FF; column index
  5854. $colIndex = 0x00FF & self::getUInt2d($cellAddressStructure, 2);
  5855. $column = Coordinate::stringFromColumnIndex($colIndex + 1);
  5856. $column = '$' . $column;
  5857. } else {
  5858. // offset: 2; size: 2; index to column or column offset + relative flags
  5859. // bit: 7-0; mask 0x00FF; column index
  5860. $relativeColIndex = 0x00FF & self::getInt2d($cellAddressStructure, 2);
  5861. $colIndex = $baseCol + $relativeColIndex;
  5862. $colIndex = ($colIndex < 256) ? $colIndex : $colIndex - 256;
  5863. $colIndex = ($colIndex >= 0) ? $colIndex : $colIndex + 256;
  5864. $column = Coordinate::stringFromColumnIndex($colIndex + 1);
  5865. }
  5866. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  5867. if (!(0x8000 & self::getUInt2d($cellAddressStructure, 2))) {
  5868. $row = '$' . $row;
  5869. } else {
  5870. $rowIndex = ($rowIndex <= 32767) ? $rowIndex : $rowIndex - 65536;
  5871. $row = $baseRow + $rowIndex;
  5872. }
  5873. return $column . $row;
  5874. }
  5875. /**
  5876. * Reads a cell range address in BIFF5 e.g. 'A2:B6' or 'A1'
  5877. * always fixed range
  5878. * section 2.5.14.
  5879. *
  5880. * @param string $subData
  5881. *
  5882. * @throws Exception
  5883. *
  5884. * @return string
  5885. */
  5886. private function readBIFF5CellRangeAddressFixed($subData)
  5887. {
  5888. // offset: 0; size: 2; index to first row
  5889. $fr = self::getUInt2d($subData, 0) + 1;
  5890. // offset: 2; size: 2; index to last row
  5891. $lr = self::getUInt2d($subData, 2) + 1;
  5892. // offset: 4; size: 1; index to first column
  5893. $fc = ord($subData[4]);
  5894. // offset: 5; size: 1; index to last column
  5895. $lc = ord($subData[5]);
  5896. // check values
  5897. if ($fr > $lr || $fc > $lc) {
  5898. throw new Exception('Not a cell range address');
  5899. }
  5900. // column index to letter
  5901. $fc = Coordinate::stringFromColumnIndex($fc + 1);
  5902. $lc = Coordinate::stringFromColumnIndex($lc + 1);
  5903. if ($fr == $lr and $fc == $lc) {
  5904. return "$fc$fr";
  5905. }
  5906. return "$fc$fr:$lc$lr";
  5907. }
  5908. /**
  5909. * Reads a cell range address in BIFF8 e.g. 'A2:B6' or 'A1'
  5910. * always fixed range
  5911. * section 2.5.14.
  5912. *
  5913. * @param string $subData
  5914. *
  5915. * @throws Exception
  5916. *
  5917. * @return string
  5918. */
  5919. private function readBIFF8CellRangeAddressFixed($subData)
  5920. {
  5921. // offset: 0; size: 2; index to first row
  5922. $fr = self::getUInt2d($subData, 0) + 1;
  5923. // offset: 2; size: 2; index to last row
  5924. $lr = self::getUInt2d($subData, 2) + 1;
  5925. // offset: 4; size: 2; index to first column
  5926. $fc = self::getUInt2d($subData, 4);
  5927. // offset: 6; size: 2; index to last column
  5928. $lc = self::getUInt2d($subData, 6);
  5929. // check values
  5930. if ($fr > $lr || $fc > $lc) {
  5931. throw new Exception('Not a cell range address');
  5932. }
  5933. // column index to letter
  5934. $fc = Coordinate::stringFromColumnIndex($fc + 1);
  5935. $lc = Coordinate::stringFromColumnIndex($lc + 1);
  5936. if ($fr == $lr and $fc == $lc) {
  5937. return "$fc$fr";
  5938. }
  5939. return "$fc$fr:$lc$lr";
  5940. }
  5941. /**
  5942. * Reads a cell range address in BIFF8 e.g. 'A2:B6' or '$A$2:$B$6'
  5943. * there are flags indicating whether column/row index is relative
  5944. * section 3.3.4.
  5945. *
  5946. * @param string $subData
  5947. *
  5948. * @return string
  5949. */
  5950. private function readBIFF8CellRangeAddress($subData)
  5951. {
  5952. // todo: if cell range is just a single cell, should this funciton
  5953. // not just return e.g. 'A1' and not 'A1:A1' ?
  5954. // offset: 0; size: 2; index to first row (0... 65535) (or offset (-32768... 32767))
  5955. $fr = self::getUInt2d($subData, 0) + 1;
  5956. // offset: 2; size: 2; index to last row (0... 65535) (or offset (-32768... 32767))
  5957. $lr = self::getUInt2d($subData, 2) + 1;
  5958. // offset: 4; size: 2; index to first column or column offset + relative flags
  5959. // bit: 7-0; mask 0x00FF; column index
  5960. $fc = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($subData, 4)) + 1);
  5961. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  5962. if (!(0x4000 & self::getUInt2d($subData, 4))) {
  5963. $fc = '$' . $fc;
  5964. }
  5965. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  5966. if (!(0x8000 & self::getUInt2d($subData, 4))) {
  5967. $fr = '$' . $fr;
  5968. }
  5969. // offset: 6; size: 2; index to last column or column offset + relative flags
  5970. // bit: 7-0; mask 0x00FF; column index
  5971. $lc = Coordinate::stringFromColumnIndex((0x00FF & self::getUInt2d($subData, 6)) + 1);
  5972. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  5973. if (!(0x4000 & self::getUInt2d($subData, 6))) {
  5974. $lc = '$' . $lc;
  5975. }
  5976. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  5977. if (!(0x8000 & self::getUInt2d($subData, 6))) {
  5978. $lr = '$' . $lr;
  5979. }
  5980. return "$fc$fr:$lc$lr";
  5981. }
  5982. /**
  5983. * Reads a cell range address in BIFF8 for shared formulas. Uses positive and negative values for row and column
  5984. * to indicate offsets from a base cell
  5985. * section 3.3.4.
  5986. *
  5987. * @param string $subData
  5988. * @param string $baseCell Base cell
  5989. *
  5990. * @return string Cell range address
  5991. */
  5992. private function readBIFF8CellRangeAddressB($subData, $baseCell = 'A1')
  5993. {
  5994. list($baseCol, $baseRow) = Coordinate::coordinateFromString($baseCell);
  5995. $baseCol = Coordinate::columnIndexFromString($baseCol) - 1;
  5996. // TODO: if cell range is just a single cell, should this funciton
  5997. // not just return e.g. 'A1' and not 'A1:A1' ?
  5998. // offset: 0; size: 2; first row
  5999. $frIndex = self::getUInt2d($subData, 0); // adjust below
  6000. // offset: 2; size: 2; relative index to first row (0... 65535) should be treated as offset (-32768... 32767)
  6001. $lrIndex = self::getUInt2d($subData, 2); // adjust below
  6002. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  6003. if (!(0x4000 & self::getUInt2d($subData, 4))) {
  6004. // absolute column index
  6005. // offset: 4; size: 2; first column with relative/absolute flags
  6006. // bit: 7-0; mask 0x00FF; column index
  6007. $fcIndex = 0x00FF & self::getUInt2d($subData, 4);
  6008. $fc = Coordinate::stringFromColumnIndex($fcIndex + 1);
  6009. $fc = '$' . $fc;
  6010. } else {
  6011. // column offset
  6012. // offset: 4; size: 2; first column with relative/absolute flags
  6013. // bit: 7-0; mask 0x00FF; column index
  6014. $relativeFcIndex = 0x00FF & self::getInt2d($subData, 4);
  6015. $fcIndex = $baseCol + $relativeFcIndex;
  6016. $fcIndex = ($fcIndex < 256) ? $fcIndex : $fcIndex - 256;
  6017. $fcIndex = ($fcIndex >= 0) ? $fcIndex : $fcIndex + 256;
  6018. $fc = Coordinate::stringFromColumnIndex($fcIndex + 1);
  6019. }
  6020. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  6021. if (!(0x8000 & self::getUInt2d($subData, 4))) {
  6022. // absolute row index
  6023. $fr = $frIndex + 1;
  6024. $fr = '$' . $fr;
  6025. } else {
  6026. // row offset
  6027. $frIndex = ($frIndex <= 32767) ? $frIndex : $frIndex - 65536;
  6028. $fr = $baseRow + $frIndex;
  6029. }
  6030. // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index)
  6031. if (!(0x4000 & self::getUInt2d($subData, 6))) {
  6032. // absolute column index
  6033. // offset: 6; size: 2; last column with relative/absolute flags
  6034. // bit: 7-0; mask 0x00FF; column index
  6035. $lcIndex = 0x00FF & self::getUInt2d($subData, 6);
  6036. $lc = Coordinate::stringFromColumnIndex($lcIndex + 1);
  6037. $lc = '$' . $lc;
  6038. } else {
  6039. // column offset
  6040. // offset: 4; size: 2; first column with relative/absolute flags
  6041. // bit: 7-0; mask 0x00FF; column index
  6042. $relativeLcIndex = 0x00FF & self::getInt2d($subData, 4);
  6043. $lcIndex = $baseCol + $relativeLcIndex;
  6044. $lcIndex = ($lcIndex < 256) ? $lcIndex : $lcIndex - 256;
  6045. $lcIndex = ($lcIndex >= 0) ? $lcIndex : $lcIndex + 256;
  6046. $lc = Coordinate::stringFromColumnIndex($lcIndex + 1);
  6047. }
  6048. // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index)
  6049. if (!(0x8000 & self::getUInt2d($subData, 6))) {
  6050. // absolute row index
  6051. $lr = $lrIndex + 1;
  6052. $lr = '$' . $lr;
  6053. } else {
  6054. // row offset
  6055. $lrIndex = ($lrIndex <= 32767) ? $lrIndex : $lrIndex - 65536;
  6056. $lr = $baseRow + $lrIndex;
  6057. }
  6058. return "$fc$fr:$lc$lr";
  6059. }
  6060. /**
  6061. * Read BIFF8 cell range address list
  6062. * section 2.5.15.
  6063. *
  6064. * @param string $subData
  6065. *
  6066. * @return array
  6067. */
  6068. private function readBIFF8CellRangeAddressList($subData)
  6069. {
  6070. $cellRangeAddresses = [];
  6071. // offset: 0; size: 2; number of the following cell range addresses
  6072. $nm = self::getUInt2d($subData, 0);
  6073. $offset = 2;
  6074. // offset: 2; size: 8 * $nm; list of $nm (fixed) cell range addresses
  6075. for ($i = 0; $i < $nm; ++$i) {
  6076. $cellRangeAddresses[] = $this->readBIFF8CellRangeAddressFixed(substr($subData, $offset, 8));
  6077. $offset += 8;
  6078. }
  6079. return [
  6080. 'size' => 2 + 8 * $nm,
  6081. 'cellRangeAddresses' => $cellRangeAddresses,
  6082. ];
  6083. }
  6084. /**
  6085. * Read BIFF5 cell range address list
  6086. * section 2.5.15.
  6087. *
  6088. * @param string $subData
  6089. *
  6090. * @return array
  6091. */
  6092. private function readBIFF5CellRangeAddressList($subData)
  6093. {
  6094. $cellRangeAddresses = [];
  6095. // offset: 0; size: 2; number of the following cell range addresses
  6096. $nm = self::getUInt2d($subData, 0);
  6097. $offset = 2;
  6098. // offset: 2; size: 6 * $nm; list of $nm (fixed) cell range addresses
  6099. for ($i = 0; $i < $nm; ++$i) {
  6100. $cellRangeAddresses[] = $this->readBIFF5CellRangeAddressFixed(substr($subData, $offset, 6));
  6101. $offset += 6;
  6102. }
  6103. return [
  6104. 'size' => 2 + 6 * $nm,
  6105. 'cellRangeAddresses' => $cellRangeAddresses,
  6106. ];
  6107. }
  6108. /**
  6109. * Get a sheet range like Sheet1:Sheet3 from REF index
  6110. * Note: If there is only one sheet in the range, one gets e.g Sheet1
  6111. * It can also happen that the REF structure uses the -1 (FFFF) code to indicate deleted sheets,
  6112. * in which case an Exception is thrown.
  6113. *
  6114. * @param int $index
  6115. *
  6116. * @throws Exception
  6117. *
  6118. * @return false|string
  6119. */
  6120. private function readSheetRangeByRefIndex($index)
  6121. {
  6122. if (isset($this->ref[$index])) {
  6123. $type = $this->externalBooks[$this->ref[$index]['externalBookIndex']]['type'];
  6124. switch ($type) {
  6125. case 'internal':
  6126. // check if we have a deleted 3d reference
  6127. if ($this->ref[$index]['firstSheetIndex'] == 0xFFFF or $this->ref[$index]['lastSheetIndex'] == 0xFFFF) {
  6128. throw new Exception('Deleted sheet reference');
  6129. }
  6130. // we have normal sheet range (collapsed or uncollapsed)
  6131. $firstSheetName = $this->sheets[$this->ref[$index]['firstSheetIndex']]['name'];
  6132. $lastSheetName = $this->sheets[$this->ref[$index]['lastSheetIndex']]['name'];
  6133. if ($firstSheetName == $lastSheetName) {
  6134. // collapsed sheet range
  6135. $sheetRange = $firstSheetName;
  6136. } else {
  6137. $sheetRange = "$firstSheetName:$lastSheetName";
  6138. }
  6139. // escape the single-quotes
  6140. $sheetRange = str_replace("'", "''", $sheetRange);
  6141. // if there are special characters, we need to enclose the range in single-quotes
  6142. // todo: check if we have identified the whole set of special characters
  6143. // it seems that the following characters are not accepted for sheet names
  6144. // and we may assume that they are not present: []*/:\?
  6145. if (preg_match("/[ !\"@#£$%&{()}<>=+'|^,;-]/u", $sheetRange)) {
  6146. $sheetRange = "'$sheetRange'";
  6147. }
  6148. return $sheetRange;
  6149. break;
  6150. default:
  6151. // TODO: external sheet support
  6152. throw new Exception('Xls reader only supports internal sheets in formulas');
  6153. break;
  6154. }
  6155. }
  6156. return false;
  6157. }
  6158. /**
  6159. * read BIFF8 constant value array from array data
  6160. * returns e.g. ['value' => '{1,2;3,4}', 'size' => 40]
  6161. * section 2.5.8.
  6162. *
  6163. * @param string $arrayData
  6164. *
  6165. * @return array
  6166. */
  6167. private static function readBIFF8ConstantArray($arrayData)
  6168. {
  6169. // offset: 0; size: 1; number of columns decreased by 1
  6170. $nc = ord($arrayData[0]);
  6171. // offset: 1; size: 2; number of rows decreased by 1
  6172. $nr = self::getUInt2d($arrayData, 1);
  6173. $size = 3; // initialize
  6174. $arrayData = substr($arrayData, 3);
  6175. // offset: 3; size: var; list of ($nc + 1) * ($nr + 1) constant values
  6176. $matrixChunks = [];
  6177. for ($r = 1; $r <= $nr + 1; ++$r) {
  6178. $items = [];
  6179. for ($c = 1; $c <= $nc + 1; ++$c) {
  6180. $constant = self::readBIFF8Constant($arrayData);
  6181. $items[] = $constant['value'];
  6182. $arrayData = substr($arrayData, $constant['size']);
  6183. $size += $constant['size'];
  6184. }
  6185. $matrixChunks[] = implode(',', $items); // looks like e.g. '1,"hello"'
  6186. }
  6187. $matrix = '{' . implode(';', $matrixChunks) . '}';
  6188. return [
  6189. 'value' => $matrix,
  6190. 'size' => $size,
  6191. ];
  6192. }
  6193. /**
  6194. * read BIFF8 constant value which may be 'Empty Value', 'Number', 'String Value', 'Boolean Value', 'Error Value'
  6195. * section 2.5.7
  6196. * returns e.g. ['value' => '5', 'size' => 9].
  6197. *
  6198. * @param string $valueData
  6199. *
  6200. * @return array
  6201. */
  6202. private static function readBIFF8Constant($valueData)
  6203. {
  6204. // offset: 0; size: 1; identifier for type of constant
  6205. $identifier = ord($valueData[0]);
  6206. switch ($identifier) {
  6207. case 0x00: // empty constant (what is this?)
  6208. $value = '';
  6209. $size = 9;
  6210. break;
  6211. case 0x01: // number
  6212. // offset: 1; size: 8; IEEE 754 floating-point value
  6213. $value = self::extractNumber(substr($valueData, 1, 8));
  6214. $size = 9;
  6215. break;
  6216. case 0x02: // string value
  6217. // offset: 1; size: var; Unicode string, 16-bit string length
  6218. $string = self::readUnicodeStringLong(substr($valueData, 1));
  6219. $value = '"' . $string['value'] . '"';
  6220. $size = 1 + $string['size'];
  6221. break;
  6222. case 0x04: // boolean
  6223. // offset: 1; size: 1; 0 = FALSE, 1 = TRUE
  6224. if (ord($valueData[1])) {
  6225. $value = 'TRUE';
  6226. } else {
  6227. $value = 'FALSE';
  6228. }
  6229. $size = 9;
  6230. break;
  6231. case 0x10: // error code
  6232. // offset: 1; size: 1; error code
  6233. $value = Xls\ErrorCode::lookup(ord($valueData[1]));
  6234. $size = 9;
  6235. break;
  6236. }
  6237. return [
  6238. 'value' => $value,
  6239. 'size' => $size,
  6240. ];
  6241. }
  6242. /**
  6243. * Extract RGB color
  6244. * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.4.
  6245. *
  6246. * @param string $rgb Encoded RGB value (4 bytes)
  6247. *
  6248. * @return array
  6249. */
  6250. private static function readRGB($rgb)
  6251. {
  6252. // offset: 0; size 1; Red component
  6253. $r = ord($rgb[0]);
  6254. // offset: 1; size: 1; Green component
  6255. $g = ord($rgb[1]);
  6256. // offset: 2; size: 1; Blue component
  6257. $b = ord($rgb[2]);
  6258. // HEX notation, e.g. 'FF00FC'
  6259. $rgb = sprintf('%02X%02X%02X', $r, $g, $b);
  6260. return ['rgb' => $rgb];
  6261. }
  6262. /**
  6263. * Read byte string (8-bit string length)
  6264. * OpenOffice documentation: 2.5.2.
  6265. *
  6266. * @param string $subData
  6267. *
  6268. * @return array
  6269. */
  6270. private function readByteStringShort($subData)
  6271. {
  6272. // offset: 0; size: 1; length of the string (character count)
  6273. $ln = ord($subData[0]);
  6274. // offset: 1: size: var; character array (8-bit characters)
  6275. $value = $this->decodeCodepage(substr($subData, 1, $ln));
  6276. return [
  6277. 'value' => $value,
  6278. 'size' => 1 + $ln, // size in bytes of data structure
  6279. ];
  6280. }
  6281. /**
  6282. * Read byte string (16-bit string length)
  6283. * OpenOffice documentation: 2.5.2.
  6284. *
  6285. * @param string $subData
  6286. *
  6287. * @return array
  6288. */
  6289. private function readByteStringLong($subData)
  6290. {
  6291. // offset: 0; size: 2; length of the string (character count)
  6292. $ln = self::getUInt2d($subData, 0);
  6293. // offset: 2: size: var; character array (8-bit characters)
  6294. $value = $this->decodeCodepage(substr($subData, 2));
  6295. //return $string;
  6296. return [
  6297. 'value' => $value,
  6298. 'size' => 2 + $ln, // size in bytes of data structure
  6299. ];
  6300. }
  6301. /**
  6302. * Extracts an Excel Unicode short string (8-bit string length)
  6303. * OpenOffice documentation: 2.5.3
  6304. * function will automatically find out where the Unicode string ends.
  6305. *
  6306. * @param string $subData
  6307. *
  6308. * @return array
  6309. */
  6310. private static function readUnicodeStringShort($subData)
  6311. {
  6312. $value = '';
  6313. // offset: 0: size: 1; length of the string (character count)
  6314. $characterCount = ord($subData[0]);
  6315. $string = self::readUnicodeString(substr($subData, 1), $characterCount);
  6316. // add 1 for the string length
  6317. $string['size'] += 1;
  6318. return $string;
  6319. }
  6320. /**
  6321. * Extracts an Excel Unicode long string (16-bit string length)
  6322. * OpenOffice documentation: 2.5.3
  6323. * this function is under construction, needs to support rich text, and Asian phonetic settings.
  6324. *
  6325. * @param string $subData
  6326. *
  6327. * @return array
  6328. */
  6329. private static function readUnicodeStringLong($subData)
  6330. {
  6331. $value = '';
  6332. // offset: 0: size: 2; length of the string (character count)
  6333. $characterCount = self::getUInt2d($subData, 0);
  6334. $string = self::readUnicodeString(substr($subData, 2), $characterCount);
  6335. // add 2 for the string length
  6336. $string['size'] += 2;
  6337. return $string;
  6338. }
  6339. /**
  6340. * Read Unicode string with no string length field, but with known character count
  6341. * this function is under construction, needs to support rich text, and Asian phonetic settings
  6342. * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.3.
  6343. *
  6344. * @param string $subData
  6345. * @param int $characterCount
  6346. *
  6347. * @return array
  6348. */
  6349. private static function readUnicodeString($subData, $characterCount)
  6350. {
  6351. $value = '';
  6352. // offset: 0: size: 1; option flags
  6353. // bit: 0; mask: 0x01; character compression (0 = compressed 8-bit, 1 = uncompressed 16-bit)
  6354. $isCompressed = !((0x01 & ord($subData[0])) >> 0);
  6355. // bit: 2; mask: 0x04; Asian phonetic settings
  6356. $hasAsian = (0x04) & ord($subData[0]) >> 2;
  6357. // bit: 3; mask: 0x08; Rich-Text settings
  6358. $hasRichText = (0x08) & ord($subData[0]) >> 3;
  6359. // offset: 1: size: var; character array
  6360. // this offset assumes richtext and Asian phonetic settings are off which is generally wrong
  6361. // needs to be fixed
  6362. $value = self::encodeUTF16(substr($subData, 1, $isCompressed ? $characterCount : 2 * $characterCount), $isCompressed);
  6363. return [
  6364. 'value' => $value,
  6365. 'size' => $isCompressed ? 1 + $characterCount : 1 + 2 * $characterCount, // the size in bytes including the option flags
  6366. ];
  6367. }
  6368. /**
  6369. * Convert UTF-8 string to string surounded by double quotes. Used for explicit string tokens in formulas.
  6370. * Example: hello"world --> "hello""world".
  6371. *
  6372. * @param string $value UTF-8 encoded string
  6373. *
  6374. * @return string
  6375. */
  6376. private static function UTF8toExcelDoubleQuoted($value)
  6377. {
  6378. return '"' . str_replace('"', '""', $value) . '"';
  6379. }
  6380. /**
  6381. * Reads first 8 bytes of a string and return IEEE 754 float.
  6382. *
  6383. * @param string $data Binary string that is at least 8 bytes long
  6384. *
  6385. * @return float
  6386. */
  6387. private static function extractNumber($data)
  6388. {
  6389. $rknumhigh = self::getInt4d($data, 4);
  6390. $rknumlow = self::getInt4d($data, 0);
  6391. $sign = ($rknumhigh & 0x80000000) >> 31;
  6392. $exp = (($rknumhigh & 0x7ff00000) >> 20) - 1023;
  6393. $mantissa = (0x100000 | ($rknumhigh & 0x000fffff));
  6394. $mantissalow1 = ($rknumlow & 0x80000000) >> 31;
  6395. $mantissalow2 = ($rknumlow & 0x7fffffff);
  6396. $value = $mantissa / pow(2, (20 - $exp));
  6397. if ($mantissalow1 != 0) {
  6398. $value += 1 / pow(2, (21 - $exp));
  6399. }
  6400. $value += $mantissalow2 / pow(2, (52 - $exp));
  6401. if ($sign) {
  6402. $value *= -1;
  6403. }
  6404. return $value;
  6405. }
  6406. /**
  6407. * @param int $rknum
  6408. *
  6409. * @return float
  6410. */
  6411. private static function getIEEE754($rknum)
  6412. {
  6413. if (($rknum & 0x02) != 0) {
  6414. $value = $rknum >> 2;
  6415. } else {
  6416. // changes by mmp, info on IEEE754 encoding from
  6417. // research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html
  6418. // The RK format calls for using only the most significant 30 bits
  6419. // of the 64 bit floating point value. The other 34 bits are assumed
  6420. // to be 0 so we use the upper 30 bits of $rknum as follows...
  6421. $sign = ($rknum & 0x80000000) >> 31;
  6422. $exp = ($rknum & 0x7ff00000) >> 20;
  6423. $mantissa = (0x100000 | ($rknum & 0x000ffffc));
  6424. $value = $mantissa / pow(2, (20 - ($exp - 1023)));
  6425. if ($sign) {
  6426. $value = -1 * $value;
  6427. }
  6428. //end of changes by mmp
  6429. }
  6430. if (($rknum & 0x01) != 0) {
  6431. $value /= 100;
  6432. }
  6433. return $value;
  6434. }
  6435. /**
  6436. * Get UTF-8 string from (compressed or uncompressed) UTF-16 string.
  6437. *
  6438. * @param string $string
  6439. * @param bool $compressed
  6440. *
  6441. * @return string
  6442. */
  6443. private static function encodeUTF16($string, $compressed = false)
  6444. {
  6445. if ($compressed) {
  6446. $string = self::uncompressByteString($string);
  6447. }
  6448. return StringHelper::convertEncoding($string, 'UTF-8', 'UTF-16LE');
  6449. }
  6450. /**
  6451. * Convert UTF-16 string in compressed notation to uncompressed form. Only used for BIFF8.
  6452. *
  6453. * @param string $string
  6454. *
  6455. * @return string
  6456. */
  6457. private static function uncompressByteString($string)
  6458. {
  6459. $uncompressedString = '';
  6460. $strLen = strlen($string);
  6461. for ($i = 0; $i < $strLen; ++$i) {
  6462. $uncompressedString .= $string[$i] . "\0";
  6463. }
  6464. return $uncompressedString;
  6465. }
  6466. /**
  6467. * Convert string to UTF-8. Only used for BIFF5.
  6468. *
  6469. * @param string $string
  6470. *
  6471. * @return string
  6472. */
  6473. private function decodeCodepage($string)
  6474. {
  6475. return StringHelper::convertEncoding($string, 'UTF-8', $this->codepage);
  6476. }
  6477. /**
  6478. * Read 16-bit unsigned integer.
  6479. *
  6480. * @param string $data
  6481. * @param int $pos
  6482. *
  6483. * @return int
  6484. */
  6485. public static function getUInt2d($data, $pos)
  6486. {
  6487. return ord($data[$pos]) | (ord($data[$pos + 1]) << 8);
  6488. }
  6489. /**
  6490. * Read 16-bit signed integer.
  6491. *
  6492. * @param string $data
  6493. * @param int $pos
  6494. *
  6495. * @return int
  6496. */
  6497. public static function getInt2d($data, $pos)
  6498. {
  6499. return unpack('s', $data[$pos] . $data[$pos + 1])[1];
  6500. }
  6501. /**
  6502. * Read 32-bit signed integer.
  6503. *
  6504. * @param string $data
  6505. * @param int $pos
  6506. *
  6507. * @return int
  6508. */
  6509. public static function getInt4d($data, $pos)
  6510. {
  6511. // FIX: represent numbers correctly on 64-bit system
  6512. // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334
  6513. // Changed by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems
  6514. $_or_24 = ord($data[$pos + 3]);
  6515. if ($_or_24 >= 128) {
  6516. // negative number
  6517. $_ord_24 = -abs((256 - $_or_24) << 24);
  6518. } else {
  6519. $_ord_24 = ($_or_24 & 127) << 24;
  6520. }
  6521. return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24;
  6522. }
  6523. private function parseRichText($is)
  6524. {
  6525. $value = new RichText();
  6526. $value->createText($is);
  6527. return $value;
  6528. }
  6529. }