phplot.php 392 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204
  1. <?php
  2. /**
  3. * PHPlot - A class for creating scientific and business graphs, charts, plots
  4. *
  5. * This file contains two PHP classes which are used to create graphs,
  6. * charts, and plots. The PHPlot class is the basic class which creates
  7. * indexed-color images, and the extended PHPlot_truecolor class creates
  8. * full-color (24-bit) images.
  9. * PHPlot currently requires PHP 5.3 or later.
  10. *
  11. * $Id: phplot.php 1774 2015-11-03 00:18:50Z lbayuk $
  12. *
  13. * @version 6.2.0
  14. * @copyright 1998-2015 Afan Ottenheimer
  15. * @license GNU Lesser General Public License, version 2.1
  16. * @link http://sourceforge.net/projects/phplot/ PHPlot Web Site with downloads, tracker, discussion
  17. * @link http://phplot.sourceforge.net PHPlot Project Web Site with links to documentation
  18. * @author lbayuk (2006-present) <lbayuk@users.sourceforge.net>
  19. * @author Miguel de Benito Delgado (co-author and maintainer, 2003-2005)
  20. * @author Afan Ottenheimer (original author)
  21. */
  22. /*
  23. * This is free software; you can redistribute it and/or
  24. * modify it under the terms of the GNU Lesser General Public
  25. * License as published by the Free Software Foundation;
  26. * version 2.1 of the License.
  27. *
  28. * This software is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  31. * Lesser General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Lesser General Public
  34. * License along with this software; if not, write to the Free Software
  35. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36. * ---------------------------------------------------------------------
  37. */
  38. /**
  39. * Class for creating a plot
  40. *
  41. * The PHPlot class represents a plot (chart, graph) with all associated
  42. * parameters. This creates a palette (indexed) color image which is limited
  43. * to 256 total colors. For truecolor images (24 bit R, G, B), see the
  44. * PHPlot_truecolor class.
  45. *
  46. * In most cases, methods of PHPlot just change the internal properties, and
  47. * nothing actually happens until the DrawGraph() method is used. Therefore
  48. * methods can be used in any order up until DrawGraph(); the order should not
  49. * affect the results.
  50. *
  51. * Note: Without a background image, the PHPlot class creates a palette
  52. * (indexed) color image, and the PHPlot_truecolor class creates a truecolor
  53. * image. If a background image is used with the constructor of either class,
  54. * the type of image produced matches the type of the background image.
  55. *
  56. */
  57. class PHPlot
  58. {
  59. /** PHPlot version constant as a string */
  60. const version = '6.2.0';
  61. /** PHPlot version constant as a number = major * 10000 + minor * 100 + patch */
  62. const version_id = 60200;
  63. // All class variables are declared here, and initialized (if applicable).
  64. // Starting with PHPlot-6.0, most variables have 'protected' visibility
  65. // For more information on these variables, see the Reference Manual, Developer's Guide, List
  66. // of Member Variables. The list below is in alphabetical order, matching the manual.
  67. /** Calculated width of bars for bar charts */
  68. protected $actual_bar_width;
  69. /** Calculated bar gap */
  70. protected $bar_adjust_gap;
  71. /** Extra space between groups of bars */
  72. public $bar_extra_space = 0.5;
  73. /** Width of bar relative to space for one bar */
  74. public $bar_width_adjust = 1;
  75. /** Color (R,G,B,A) for image background */
  76. protected $bg_color;
  77. /** Background image filename */
  78. protected $bgimg;
  79. /** Background image tiling mode */
  80. protected $bgmode;
  81. /** Scale factor for box widths in box plots */
  82. public $boxes_frac_width = 0.3;
  83. /** Maximum half-width for boxes in box plots */
  84. public $boxes_max_width = 8;
  85. /** Minimum half-width for boxes in box plots */
  86. public $boxes_min_width = 2;
  87. /** Ratio of the width of the 'T' ends of box plot whiskers to the width of the boxes */
  88. public $boxes_t_width = 0.6;
  89. /** Flag: Don't send cache suppression headers */
  90. protected $browser_cache = FALSE;
  91. /** Max bubble size for bubbles plots */
  92. public $bubbles_max_size;
  93. /** Min bubbles size for bubble plots */
  94. public $bubbles_min_size = 6;
  95. /** Callback (hook) function information, indexed by callback reason */
  96. protected $callbacks = array(
  97. 'data_points' => NULL,
  98. 'draw_setup' => NULL,
  99. 'draw_image_background' => NULL,
  100. 'draw_plotarea_background' => NULL,
  101. 'draw_titles' => NULL,
  102. 'draw_axes' => NULL,
  103. 'draw_graph' => NULL,
  104. 'draw_border' => NULL,
  105. 'draw_legend' => NULL,
  106. 'draw_all' => NULL,
  107. 'data_color' => NULL,
  108. 'debug_textbox' => NULL,
  109. 'debug_scale' => NULL,
  110. );
  111. /** Flag: Draw dashed or solid grid lines? */
  112. protected $dashed_grid = TRUE;
  113. /** Initial dashed pattern code */
  114. protected $dashed_style = '2-4';
  115. /** The (converted) data array */
  116. protected $data;
  117. /** Array of colors (R,G,B,A) for data borders available with some plot types */
  118. protected $data_border_colors;
  119. /** Array of colors (R,G,B,A) for data lines/marks/bars/etc. */
  120. protected $data_colors;
  121. /** Maximum number of dependent variable values */
  122. protected $data_columns;
  123. /** Array: Per row maximum Y value */
  124. protected $data_max;
  125. /** Array: Per row minimum Y value */
  126. protected $data_min;
  127. /** Format of the data array */
  128. protected $data_type = 'text-data';
  129. /** Obsolete - suffix for 'data'-formatted labels */
  130. public $data_units_text = '';
  131. /** Angle (in degrees) for data value labels */
  132. public $data_value_label_angle = 90;
  133. /** Distance (in pixels) for data value labels */
  134. public $data_value_label_distance = 5;
  135. /** Color (R,G,B,A) to use for axis data labels */
  136. protected $datalabel_color;
  137. /** Flag: data type has error bars */
  138. protected $datatype_error_bars;
  139. /** Flag: data type has implied X or Y */
  140. protected $datatype_implied;
  141. /** Flag: data type is one-column data for pie chart */
  142. protected $datatype_pie_single;
  143. /** Flag: data type has swapped X and Y values (horizontal plot) */
  144. protected $datatype_swapped_xy;
  145. /** Flag: data type includes Y and Z value pairs */
  146. protected $datatype_yz;
  147. /** Static array of data type information */
  148. static protected $datatypes = array( // See DecodeDataType() and $datatype_* flags
  149. 'text-data' => array('implied' => TRUE),
  150. 'text-data-single' => array('implied' => TRUE, 'pie_single' => TRUE),
  151. 'data-data' => array(),
  152. 'data-data-error' => array('error_bars' => TRUE),
  153. 'data-data-yx' => array('swapped_xy' => TRUE),
  154. 'text-data-yx' => array('implied' => TRUE, 'swapped_xy' => TRUE),
  155. 'data-data-xyz' => array('yz' => TRUE),
  156. 'data-data-yx-error' => array('swapped_xy' => TRUE, 'error_bars' => TRUE),
  157. );
  158. /** Static array of data type aliases => primary name */
  159. static protected $datatypes_map = array(
  160. 'text-linear' => 'text-data',
  161. 'linear-linear' => 'data-data',
  162. 'linear-linear-error' => 'data-data-error',
  163. 'text-data-pie' => 'text-data-single',
  164. 'data-data-error-yx' => 'data-data-yx-error',
  165. );
  166. /** Character to use for decimal point in formatted numbers */
  167. protected $decimal_point;
  168. /** The default color array, used to initialize data_colors and error_bar_colors */
  169. protected $default_colors = array(
  170. 'SkyBlue', 'green', 'orange', 'blue', 'red', 'DarkGreen', 'purple', 'peru',
  171. 'cyan', 'salmon', 'SlateBlue', 'YellowGreen', 'magenta', 'aquamarine1', 'gold', 'violet'
  172. );
  173. /** Dashed-line template, as a string of space-separated markers (see SetDefaultDashedStyle) */
  174. protected $default_dashed_style;
  175. /** Default TrueType font file */
  176. protected $default_ttfont;
  177. /** Array of flags for elements that must be drawn at most once */
  178. protected $done = array();
  179. /** Flag: How to handle missing Y values */
  180. protected $draw_broken_lines = FALSE;
  181. /** Flag: Draw data borders, available with some plot types */
  182. protected $draw_data_borders;
  183. /** Flag: Draw borders on pie chart segments */
  184. protected $draw_pie_borders;
  185. /** Flag: Draw the background of the plot area */
  186. protected $draw_plot_area_background = FALSE;
  187. /** Flag: Draw X data label lines */
  188. protected $draw_x_data_label_lines = FALSE;
  189. /** Flag: Draw X grid lines? */
  190. protected $draw_x_grid;
  191. /** Flag: Draw Y data label lines */
  192. protected $draw_y_data_label_lines = FALSE;
  193. /** Flag: Draw Y grid lines? */
  194. protected $draw_y_grid;
  195. /** Color (R,G,B,A) to use for data value labels */
  196. protected $dvlabel_color;
  197. /** Array of colors (R,G,B,A) for error bars */
  198. protected $error_bar_colors;
  199. /** Thickness of error bar lines */
  200. protected $error_bar_line_width = 1;
  201. /** Shape (style) of error bars: line or tee */
  202. protected $error_bar_shape = 'tee';
  203. /** Size of error bars */
  204. protected $error_bar_size = 5;
  205. /** Image format: png, gif, jpg, wbmp */
  206. protected $file_format = 'png';
  207. /** Array of font information (should be protected, but public for possible callback use) */
  208. public $fonts;
  209. /** Flag: Draw grid on top of or behind the plot */
  210. public $grid_at_foreground = FALSE;
  211. /** Color (R,G,B,A) to use for axes, plot area border, legend border, pie chart lines and text */
  212. protected $grid_color;
  213. /** Controls fraction of bar group space used for bar */
  214. public $group_frac_width = 0.7;
  215. /** Color (R,G,B,A) for image border, if drawn */
  216. protected $i_border;
  217. /** Image border type */
  218. protected $image_border_type = 'none';
  219. /** Width of image border in pixels */
  220. protected $image_border_width;
  221. /** Image height */
  222. protected $image_height;
  223. /** Image width */
  224. protected $image_width;
  225. /** Image resource (should be protected, but public to reduce breakage) */
  226. public $img;
  227. /** Prevent recursion in error message image production */
  228. protected $in_error;
  229. /** Flag: don't send headers */
  230. protected $is_inline = FALSE;
  231. /** Label format info */
  232. protected $label_format = array('x' => array(), 'xd' => array(), 'y' => array(), 'yd' => array());
  233. /** Pie chart label position factor */
  234. protected $label_scale_position = 0.5;
  235. /** Legend text array */
  236. protected $legend;
  237. /** Color (R,G,B,A) for the legend background */
  238. protected $legend_bg_color;
  239. /** Alignment of color boxes or shape markers in the legend: left, right, or none */
  240. protected $legend_colorbox_align = 'right';
  241. /** Color control for colorbox borders in legend */
  242. protected $legend_colorbox_borders = 'textcolor';
  243. /** Adjusts width of color boxes in the legend */
  244. public $legend_colorbox_width = 1;
  245. /** Array holding legend position information */
  246. protected $legend_pos;
  247. /** Flag: reverse the order of lines in the legend box, bottom to top */
  248. protected $legend_reverse_order = FALSE;
  249. /** Legend style setting, left or right */
  250. protected $legend_text_align = 'right';
  251. /** Color (R,G,B,A) for the legend text */
  252. protected $legend_text_color;
  253. /** Draw color boxes (if false or unset) or shape markers (if true) in the legend */
  254. protected $legend_use_shapes = FALSE;
  255. /** Color (R,G,B,A) for grid lines and X data lines */
  256. protected $light_grid_color;
  257. /** Controls inter-line spacing of text */
  258. protected $line_spacing = 4;
  259. /** Plot line style(s) */
  260. protected $line_styles = array('solid', 'solid', 'dashed');
  261. /** Plot line width(s) */
  262. protected $line_widths = 1;
  263. /** Flag to avoid importing locale info */
  264. public $locale_override = FALSE;
  265. /** Overall max X value in the data array */
  266. protected $max_x;
  267. /** Overall max Y value in the data array */
  268. protected $max_y;
  269. /** Overall max Z value in the data array (for X/Y/Z data type only) */
  270. protected $max_z;
  271. /** Overall min X value in the data array */
  272. protected $min_x;
  273. /** Overall min Y value in the data array */
  274. protected $min_y;
  275. /** Overall min Z value in the data array (for X/Y/Z data type only) */
  276. protected $min_z;
  277. /** Color index of image background */
  278. protected $ndx_bg_color;
  279. /** Color index array for data borders */
  280. protected $ndx_data_border_colors;
  281. /** Color index array for plot data lines/marks/bars/etc. */
  282. protected $ndx_data_colors;
  283. /** Color index array for plot data, darker shade */
  284. protected $ndx_data_dark_colors;
  285. /** Color index for axis data labels */
  286. protected $ndx_datalabel_color;
  287. /** Color index for data value labels */
  288. protected $ndx_dvlabel_color;
  289. /** Color index array for error bars */
  290. protected $ndx_error_bar_colors;
  291. /** Color index for axes, plot area border, legend border, pie chart lines and text */
  292. protected $ndx_grid_color;
  293. /** Color index for image border lines */
  294. protected $ndx_i_border;
  295. /** Color index for image border lines, darker shade */
  296. protected $ndx_i_border_dark;
  297. /** Color index for the legend background */
  298. protected $ndx_legend_bg_color;
  299. /** Color index for the legend text */
  300. protected $ndx_legend_text_color;
  301. /** Color index for grid lines and X data lines */
  302. protected $ndx_light_grid_color;
  303. /** Color index for unshaded pie chart segment borders */
  304. protected $ndx_pieborder_color;
  305. /** Color index for pie chart data labels */
  306. protected $ndx_pielabel_color;
  307. /** Color index of plot area background */
  308. protected $ndx_plot_bg_color;
  309. /** Color index for labels and legend text */
  310. protected $ndx_text_color;
  311. /** Color index for tick marks */
  312. protected $ndx_tick_color;
  313. /** Color index for tick labels */
  314. protected $ndx_ticklabel_color;
  315. /** Color index for main title */
  316. protected $ndx_title_color;
  317. /** Color index for X title */
  318. protected $ndx_x_title_color;
  319. /** Color index for Y title */
  320. protected $ndx_y_title_color;
  321. /** Number of rows in the data array (number of points along X, or number of bar groups, for example) */
  322. protected $num_data_rows;
  323. /** Array with number of entries in each data row (including label and X if present) */
  324. protected $num_recs;
  325. /** Forced number of X tick marks */
  326. protected $num_x_ticks = '';
  327. /** Forced number of Y tick marks */
  328. protected $num_y_ticks = '';
  329. /** Scale factor for element widths in OHLC plots. */
  330. public $ohlc_frac_width = 0.3;
  331. /** Maximum half-width for elements in OHLC plots */
  332. public $ohlc_max_width = 8;
  333. /** Minimum half-width for elements in OHLC plots */
  334. public $ohlc_min_width = 2;
  335. /** Redirect to output file */
  336. protected $output_file;
  337. /** Aspect ratio for shaded pie charts */
  338. public $pie_diam_factor = 0.5;
  339. /** Flag: True to draw pie chart segments clockwise, false or unset for counter-clockwise. */
  340. protected $pie_direction_cw = FALSE;
  341. /** Flag: If true, do not include label sizes when calculating pie size. */
  342. protected $pie_full_size = FALSE;
  343. /** Source of label text for pie charts (percent, value, label, or index) */
  344. protected $pie_label_source;
  345. /** Minimum amount of the plot area that will be reserved for the pie */
  346. public $pie_min_size_factor = 0.5;
  347. /** Starting angle in degrees for the first segment in a pie chart */
  348. protected $pie_start_angle = 0;
  349. /** Color (R,G,B,A) to use for unshaded pie chart segment borders */
  350. protected $pieborder_color;
  351. /** Color (R,G,B,A) to use for pie chart data labels */
  352. protected $pielabel_color;
  353. /** Calculated plot area array: ([0],[1]) is top left, ([2],[3]) is bottom right */
  354. protected $plot_area;
  355. /** Height of the plot area */
  356. protected $plot_area_height;
  357. /** Width of the plot area */
  358. protected $plot_area_width;
  359. /** Color (R,G,B,A) for plot area background */
  360. protected $plot_bg_color;
  361. /** Where to draw plot borders. Can be scalar or array of choices. */
  362. protected $plot_border_type;
  363. /** Max X of the plot area in world coordinates */
  364. protected $plot_max_x;
  365. /** Max Y of the plot area in world coordinates */
  366. protected $plot_max_y;
  367. /** Min X of the plot area in world coordinates */
  368. protected $plot_min_x;
  369. /** Min Y of the plot area in world coordinates */
  370. protected $plot_min_y;
  371. /** X device coordinate of the plot area origin */
  372. protected $plot_origin_x;
  373. /** Y device coordinate of the plot area origin */
  374. protected $plot_origin_y;
  375. /** Selected plot type */
  376. protected $plot_type = 'linepoints';
  377. /** Plot area background image filename */
  378. protected $plotbgimg;
  379. /** Plot area background image tiling mode */
  380. protected $plotbgmode;
  381. /** Array of plot type information, indexed by plot type */
  382. static protected $plots = array(
  383. 'area' => array(
  384. 'draw_method' => 'DrawArea',
  385. 'abs_vals' => TRUE,
  386. ),
  387. 'bars' => array(
  388. 'draw_method' => 'DrawBars',
  389. ),
  390. 'boxes' => array(
  391. 'draw_method' => 'DrawBoxes',
  392. 'adjust_type' => 1, // See GetRangeEndAdjust()
  393. ),
  394. 'bubbles' => array(
  395. 'draw_method' => 'DrawBubbles',
  396. 'adjust_type' => 1, // See GetRangeEndAdjust()
  397. ),
  398. 'candlesticks' => array(
  399. 'draw_method' => 'DrawOHLC',
  400. 'draw_arg' => array(TRUE, FALSE), // Draw candlesticks, only fill if "closed down"
  401. 'adjust_type' => 2, // See GetRangeEndAdjust()
  402. ),
  403. 'candlesticks2' => array(
  404. 'draw_method' => 'DrawOHLC',
  405. 'draw_arg' => array(TRUE, TRUE), // Draw candlesticks, fill always
  406. 'adjust_type' => 2, // See GetRangeEndAdjust()
  407. ),
  408. 'linepoints' => array(
  409. 'draw_method' => 'DrawLinePoints',
  410. 'legend_alt_marker' => 'shape',
  411. ),
  412. 'lines' => array(
  413. 'draw_method' => 'DrawLines',
  414. 'legend_alt_marker' => 'line',
  415. ),
  416. 'ohlc' => array(
  417. 'draw_method' => 'DrawOHLC',
  418. 'draw_arg' => array(FALSE), // Don't draw candlesticks
  419. 'adjust_type' => 2, // See GetRangeEndAdjust()
  420. ),
  421. 'pie' => array(
  422. 'draw_method' => 'DrawPieChart',
  423. 'suppress_axes' => TRUE,
  424. 'abs_vals' => TRUE,
  425. ),
  426. 'points' => array(
  427. 'draw_method' => 'DrawDots',
  428. 'legend_alt_marker' => 'shape',
  429. ),
  430. 'squared' => array(
  431. 'draw_method' => 'DrawSquared',
  432. 'legend_alt_marker' => 'line',
  433. ),
  434. 'squaredarea' => array(
  435. 'draw_method' => 'DrawSquaredArea',
  436. 'abs_vals' => TRUE,
  437. ),
  438. 'stackedarea' => array(
  439. 'draw_method' => 'DrawArea',
  440. 'draw_arg' => array(TRUE), // Tells DrawArea to draw stacked area plot
  441. 'sum_vals' => TRUE,
  442. 'abs_vals' => TRUE,
  443. ),
  444. 'stackedbars' => array(
  445. 'draw_method' => 'DrawStackedBars',
  446. 'sum_vals' => TRUE,
  447. ),
  448. 'stackedsquaredarea' => array(
  449. 'draw_method' => 'DrawSquaredArea',
  450. 'draw_arg' => array(TRUE), // Tells DrawSquaredArea the data is cumulative
  451. 'sum_vals' => TRUE,
  452. 'abs_vals' => TRUE,
  453. ),
  454. 'thinbarline' => array(
  455. 'draw_method' => 'DrawThinBarLines',
  456. ),
  457. );
  458. /** Size of point_shapes and point_sizes arrays */
  459. protected $point_counts;
  460. /** Marker shapes for point plots */
  461. protected $point_shapes = array(
  462. 'diamond', 'dot', 'delta', 'home', 'yield', 'box', 'circle', 'up', 'down', 'cross'
  463. );
  464. /** Marker sizes for point plots */
  465. protected $point_sizes = array(6);
  466. /** Flag: Automatic PrintImage after DrawGraph? */
  467. protected $print_image = TRUE;
  468. /** Tuning parameters for plot range calculation */
  469. protected $rangectl = array( 'x' => array(
  470. 'adjust_mode' => 'T', // T=adjust to next tick
  471. 'adjust_amount' => NULL, // See GetRangeEndAdjust()
  472. 'zero_magnet' => 0.857142, // Value is 6/7
  473. ),
  474. 'y' => array(
  475. 'adjust_mode' => 'T', // T=adjust to next tick
  476. 'adjust_amount' => NULL, // See GetRangeEndAdjust()
  477. 'zero_magnet' => 0.857142, // Value is 6/7
  478. ));
  479. /** Area for each bar in a bar chart */
  480. protected $record_bar_width;
  481. /** Maximum of num_recs[], max number of entries (including label and X if present) for all data rows */
  482. protected $records_per_group;
  483. /** Array mapping color names to array of R, G, B values */
  484. protected $rgb_array;
  485. /** Fixed extra margin used in multiple places */
  486. public $safe_margin = 5;
  487. /** Stores PHPlot version when object was serialized */
  488. protected $saved_version;
  489. /** Drop shadow size for pie and bar charts */
  490. protected $shading = 5;
  491. /** Skip bottom tick mark */
  492. protected $skip_bottom_tick = FALSE;
  493. /** Skip left tick mark */
  494. protected $skip_left_tick = FALSE;
  495. /** Skip right tick mark */
  496. protected $skip_right_tick = FALSE;
  497. /** Skip top tick mark */
  498. protected $skip_top_tick = FALSE;
  499. /** MIME boundary sequence used with streaming plots */
  500. protected $stream_boundary;
  501. /** Boundary and MIME header, output before each frame in a plot stream */
  502. protected $stream_frame_header;
  503. /** Name of the GD output function for this image type, used with streaming plots */
  504. protected $stream_output_f;
  505. /** Flag: Don't produce an error image on fatal error */
  506. protected $suppress_error_image = FALSE;
  507. /** Flag: Don't draw the X axis line */
  508. protected $suppress_x_axis = FALSE;
  509. /** Flag: Don't draw the Y axis line */
  510. protected $suppress_y_axis = FALSE;
  511. /** Color (R,G,B,A) for labels and legend text */
  512. protected $text_color;
  513. /** Character to use to group 1000s in formatted numbers */
  514. protected $thousands_sep;
  515. /** Color (R,G,B,A) for tick marks */
  516. protected $tick_color;
  517. /** Tuning parameters for tick increment calculation */
  518. protected $tickctl = array( 'x' => array(
  519. 'tick_mode' => NULL,
  520. 'min_ticks' => 8,
  521. 'tick_inc_integer' => FALSE,
  522. ),
  523. 'y' => array(
  524. 'tick_mode' => NULL,
  525. 'min_ticks' => 8,
  526. 'tick_inc_integer' => FALSE,
  527. ));
  528. /** Color (R,G,B,A) to use for tick labels */
  529. protected $ticklabel_color;
  530. /** Color (R,G,B,A) for main title (and default for X and Y titles) */
  531. protected $title_color;
  532. /** Y offset of main title position */
  533. protected $title_offset;
  534. /** Main title text */
  535. protected $title_txt = '';
  536. /** Total number of entries (rows times columns in each row) in the data array. */
  537. protected $total_records;
  538. /** Color (R,G,B,A) designated as transparent */
  539. protected $transparent_color;
  540. /** Flag: True if serialized object had a truecolor image */
  541. protected $truecolor;
  542. /** TrueType font directory */
  543. protected $ttf_path = '.';
  544. /** Default font type, True for TrueType, False for GD */
  545. protected $use_ttf = FALSE;
  546. /** Position of X axis (in world coordinates) */
  547. protected $x_axis_position;
  548. /** Device coordinate for the X axis */
  549. protected $x_axis_y_pixels;
  550. /** Effective X data label text angle */
  551. protected $x_data_label_angle;
  552. /** X data label text angle (see also x_data_label_angle) */
  553. protected $x_data_label_angle_u = '';
  554. /** Position of X data labels */
  555. protected $x_data_label_pos;
  556. /** X tick label text angle (and default for x_data_label_angle) */
  557. protected $x_label_angle = 0;
  558. /** Label offset relative to plot area */
  559. protected $x_label_axis_offset;
  560. /** Label offset relative to plot area */
  561. protected $x_label_bot_offset;
  562. /** Label offset relative to plot area */
  563. protected $x_label_top_offset;
  564. /** Calculated plot area margin - left side */
  565. protected $x_left_margin;
  566. /** Calculated plot area margin - right side */
  567. protected $x_right_margin;
  568. /** X tick anchor point */
  569. protected $x_tick_anchor;
  570. /** Length of X tick marks (inside plot area) */
  571. protected $x_tick_cross = 3;
  572. /** Effective step between X tick marks */
  573. protected $x_tick_inc;
  574. /** Step between X tick marks (see also x_tick_inc) */
  575. protected $x_tick_inc_u = '';
  576. /** Position of X tick labels */
  577. protected $x_tick_label_pos;
  578. /** Length of X tick marks (outside plot area) */
  579. protected $x_tick_length = 5;
  580. /** Position of X tick marks */
  581. protected $x_tick_pos = 'plotdown';
  582. /** Title offset relative to plot area */
  583. protected $x_title_bot_offset;
  584. /** Color (R,G,B,A) for X title */
  585. protected $x_title_color;
  586. /** X Axis title position */
  587. protected $x_title_pos = 'none';
  588. /** Title offset relative to plot area */
  589. protected $x_title_top_offset;
  590. /** X Axis title text */
  591. protected $x_title_txt = '';
  592. /** X scale factor for converting World to Device coordinates */
  593. protected $xscale;
  594. /** Linear or log scale on X */
  595. protected $xscale_type = 'linear';
  596. /** Position of Y axis (in world coordinates) */
  597. protected $y_axis_position;
  598. /** Device coordinate for the Y axis */
  599. protected $y_axis_x_pixels;
  600. /** Calculated plot area margin - bottom */
  601. protected $y_bot_margin;
  602. /** Y data label text angle */
  603. protected $y_data_label_angle = 0;
  604. /** Position of Y data labels */
  605. protected $y_data_label_pos;
  606. /** Y tick label text angle */
  607. protected $y_label_angle = 0;
  608. /** Label offset relative to plot area */
  609. protected $y_label_axis_offset;
  610. /** Label offset relative to plot area */
  611. protected $y_label_left_offset;
  612. /** Label offset relative to plot area */
  613. protected $y_label_right_offset;
  614. /** Y tick anchor point */
  615. protected $y_tick_anchor;
  616. /** Length of Y tick marks (inside plot area) */
  617. protected $y_tick_cross = 3;
  618. /** Effective step between Y tick marks */
  619. protected $y_tick_inc;
  620. /** Step between Y tick marks (see also y_tick_inc) */
  621. protected $y_tick_inc_u = '';
  622. /** Position of Y tick labels */
  623. protected $y_tick_label_pos;
  624. /** Length of Y tick marks (outside plot area) */
  625. protected $y_tick_length = 5;
  626. /** Position of Y tick marks */
  627. protected $y_tick_pos = 'plotleft';
  628. /** Color (R,G,B,A) for Y title */
  629. protected $y_title_color;
  630. /** Title offset relative to plot area */
  631. protected $y_title_left_offset;
  632. /** Y Axis title position */
  633. protected $y_title_pos = 'none';
  634. /** Title offset relative to plot area */
  635. protected $y_title_right_offset;
  636. /** Y Axis title text */
  637. protected $y_title_txt = '';
  638. /** Calculated plot area margin - top */
  639. protected $y_top_margin;
  640. /** Y scale factor for converting World to Device coordinates */
  641. protected $yscale;
  642. /** Linear or log scale on Y */
  643. protected $yscale_type = 'linear';
  644. /**
  645. * Constructor: Sets up GD palette image resource, and initializes plot style controls
  646. *
  647. * @param int $width Image width in pixels
  648. * @param int $height Image height in pixels
  649. * @param string $output_file Path for output file. Omit, or NULL, or '' to mean no output file
  650. * @param string $input_file Path to a file to be used as background. Omit, NULL, or '' for none
  651. */
  652. function __construct($width=600, $height=400, $output_file=NULL, $input_file=NULL)
  653. {
  654. $this->initialize('imagecreate', $width, $height, $output_file, $input_file);
  655. }
  656. /**
  657. * Initializes a PHPlot object (used by PHPlot and PHPlot_truecolor constructors)
  658. *
  659. * @param string $imagecreate_function GD function to use: imagecreate or imagecreatetruecolor
  660. * @param int $width Image width in pixels
  661. * @param int $height Image height in pixels
  662. * @param string $output_file Path for output file. Omit, or NULL, or '' to mean no output file
  663. * @param string $input_file Path to a file to be used as background. Omit, NULL, or '' for none
  664. * @since 5.6.0
  665. */
  666. protected function initialize($imagecreate_function, $width, $height, $output_file, $input_file)
  667. {
  668. $this->SetRGBArray('small');
  669. if (isset($output_file) && $output_file !== '')
  670. $this->SetOutputFile($output_file);
  671. if (isset($input_file) && $input_file !== '') {
  672. $this->SetInputFile($input_file);
  673. } else {
  674. $this->image_width = $width;
  675. $this->image_height = $height;
  676. $this->img = call_user_func($imagecreate_function, $width, $height);
  677. if (!$this->img)
  678. return $this->PrintError(get_class($this) . '(): Could not create image resource.');
  679. }
  680. $this->SetDefaultStyles();
  681. $this->SetDefaultFonts();
  682. }
  683. /**
  684. * Prepares object for serialization
  685. *
  686. * The image resource cannot be serialized. But rather than try to filter it out from the other
  687. * properties, just let PHP serialize it (it will become an integer=0), and then fix it in __wakeup.
  688. * This way the object is still usable after serialize().
  689. * Note: This does not work if an input file was provided to the constructor.
  690. *
  691. * @return string[] Array of object property names, as required by PHP spec for __sleep()
  692. * @since 5.8.0
  693. */
  694. function __sleep()
  695. {
  696. $this->truecolor = imageistruecolor($this->img); // Remember image type
  697. $this->saved_version = self::version; // Remember version of PHPlot, for checking on unserialize
  698. return array_keys(get_object_vars($this));
  699. }
  700. /**
  701. * Cleans up object after unserialization
  702. *
  703. * Recreates the image resource (which is not serializable), after validating the PHPlot version.
  704. * @since 5.8.0
  705. */
  706. function __wakeup()
  707. {
  708. if (strcmp($this->saved_version, self::version) != 0)
  709. $this->PrintError(get_class($this) . '(): Unserialize version mismatch');
  710. $imagecreate_function = $this->truecolor ? 'imagecreatetruecolor' : 'imagecreate';
  711. $this->img = call_user_func($imagecreate_function, $this->image_width, $this->image_height);
  712. if (!$this->img)
  713. $this->PrintError(get_class($this) . '(): Could not create image resource.');
  714. unset($this->truecolor, $this->saved_version);
  715. }
  716. /**
  717. * Reads an image file (used by constructor via SetInput file, and by tile_img for backgrounds)
  718. *
  719. * @param string $image_filename Filename of the image file to read
  720. * @param int $width Reference variable for width of the image in pixels
  721. * @param int $height Reference variable for height of the image in pixels
  722. * @return resource Image resource (False on error if an error handler returns True)
  723. * @since 5.0.4
  724. */
  725. protected function GetImage($image_filename, &$width, &$height)
  726. {
  727. $error = '';
  728. $size = getimagesize($image_filename);
  729. if (!$size) {
  730. $error = "Unable to query image file $image_filename";
  731. } else {
  732. $image_type = $size[2];
  733. switch ($image_type) {
  734. case IMAGETYPE_GIF:
  735. $img = @ ImageCreateFromGIF ($image_filename);
  736. break;
  737. case IMAGETYPE_PNG:
  738. $img = @ ImageCreateFromPNG ($image_filename);
  739. break;
  740. case IMAGETYPE_JPEG:
  741. $img = @ ImageCreateFromJPEG ($image_filename);
  742. break;
  743. default:
  744. $error = "Unknown image type ($image_type) for image file $image_filename";
  745. break;
  746. }
  747. }
  748. if (empty($error) && !$img) {
  749. // getimagesize is OK, but GD won't read it. Maybe unsupported format.
  750. $error = "Failed to read image file $image_filename";
  751. }
  752. if (!empty($error)) {
  753. return $this->PrintError("GetImage(): $error");
  754. }
  755. $width = $size[0];
  756. $height = $size[1];
  757. return $img;
  758. }
  759. /**
  760. * Selects an input file to be used as background for the whole graph
  761. *
  762. * @param string $which_input_file Pathname to the image file to use as a background
  763. * @deprecated Public use discouraged; intended for use by class constructor
  764. * @return bool True (False on error if an error handler returns True)
  765. */
  766. function SetInputFile($which_input_file)
  767. {
  768. $im = $this->GetImage($which_input_file, $this->image_width, $this->image_height);
  769. if (!$im)
  770. return FALSE; // GetImage already produced an error message.
  771. // Deallocate any resources previously allocated
  772. if (isset($this->img))
  773. imagedestroy($this->img);
  774. $this->img = $im;
  775. // Do not overwrite the input file with the background color.
  776. $this->done['background'] = TRUE;
  777. return TRUE;
  778. }
  779. /////////////////////////////////////////////
  780. ////////////// COLORS
  781. /////////////////////////////////////////////
  782. /**
  783. * Allocates a GD color index for a color specified as an array (R,G,B,A)
  784. *
  785. * At drawing time, this allocates a GD color index for the specified color, which
  786. * is specified as a 4 component array. Earlier, when a color is specified,
  787. * SetRGBColor() parsed and checked it and converted it to this component array form.
  788. *
  789. * @param int[] $color Color specification as (R, G, B, A), or unset variable
  790. * @param int $default_color_index An already-allocated GD color index to use if $color is unset
  791. * @return int A GD color index that can be used when drawing
  792. * @since 5.2.0
  793. */
  794. protected function GetColorIndex(&$color, $default_color_index = 0)
  795. {
  796. if (empty($color)) return $default_color_index;
  797. list($r, $g, $b, $a) = $color;
  798. return imagecolorresolvealpha($this->img, $r, $g, $b, $a);
  799. }
  800. /**
  801. * Allocates an array of GD color indexes from an array of color specification arrays
  802. *
  803. * This is used for the data_colors array, for example.
  804. * Note: $color_array must use 0-based sequential integer indexes.
  805. *
  806. * @param array $color_array Array of color specifications, each an array (R,G,B,A)
  807. * @param int $max_colors Limit color allocation to no more than this number of colors
  808. * @return int[] Array of GD color indexes that can be used when drawing
  809. * @since 5.3.1
  810. */
  811. protected function GetColorIndexArray($color_array, $max_colors)
  812. {
  813. $n = min(count($color_array), $max_colors);
  814. $result = array();
  815. for ($i = 0; $i < $n; $i++)
  816. $result[] = $this->GetColorIndex($color_array[$i]);
  817. return $result;
  818. }
  819. /**
  820. * Allocates an array of GD color indexes for darker shades from an array of color specifications
  821. *
  822. * This is used for shadow colors such as those in bar charts with shading.
  823. *
  824. * @param array $color_array Array of color specifications, each an array (R,G,B,A)
  825. * @param int $max_colors Limit color allocation to no more than this number of colors
  826. * @return int[] Array of GD color indexes that can be used when drawing shadow colors
  827. * @since 5.3.1
  828. */
  829. protected function GetDarkColorIndexArray($color_array, $max_colors)
  830. {
  831. $n = min(count($color_array), $max_colors);
  832. $result = array();
  833. for ($i = 0; $i < $n; $i++)
  834. $result[] = $this->GetDarkColorIndex($color_array[$i]);
  835. return $result;
  836. }
  837. /**
  838. * Allocates a GD color index for a darker shade of a color specified as an array (R,G,B,A)
  839. *
  840. * See notes on GetColorIndex() above.
  841. *
  842. * @param int[] $color Color specification as (R, G, B, A)
  843. * @return int A GD color index that can be used when drawing a shadow color
  844. * @since 5.2.0
  845. */
  846. protected function GetDarkColorIndex($color)
  847. {
  848. list ($r, $g, $b, $a) = $color;
  849. $r = max(0, $r - 0x30);
  850. $g = max(0, $g - 0x30);
  851. $b = max(0, $b - 0x30);
  852. return imagecolorresolvealpha($this->img, $r, $g, $b, $a);
  853. }
  854. /**
  855. * Sets or reverts all colors and styles to their defaults
  856. *
  857. * @return bool True always
  858. */
  859. protected function SetDefaultStyles()
  860. {
  861. $this->SetDefaultDashedStyle($this->dashed_style);
  862. $this->SetImageBorderColor(array(194, 194, 194));
  863. $this->SetPlotBgColor('white');
  864. $this->SetBackgroundColor('white');
  865. $this->SetTextColor('black');
  866. $this->SetGridColor('black');
  867. $this->SetLightGridColor('gray');
  868. $this->SetTickColor('black');
  869. $this->SetTitleColor('black');
  870. // These functions set up the default colors when called without parameters
  871. $this->SetDataColors();
  872. $this->SetErrorBarColors();
  873. $this->SetDataBorderColors();
  874. return TRUE;
  875. }
  876. /**
  877. * Sets the overall image background color
  878. *
  879. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  880. * @return bool True (False on error if an error handler returns True)
  881. */
  882. function SetBackgroundColor($which_color)
  883. {
  884. return (bool)($this->bg_color = $this->SetRGBColor($which_color));
  885. }
  886. /**
  887. * Sets the plot area background color, which is only drawn if SetDrawPlotAreaBackground is used.
  888. *
  889. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  890. * @return bool True (False on error if an error handler returns True)
  891. */
  892. function SetPlotBgColor($which_color)
  893. {
  894. return (bool)($this->plot_bg_color = $this->SetRGBColor($which_color));
  895. }
  896. /**
  897. * Sets the color of the plot title, and the default color of the X and Y titles.
  898. *
  899. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  900. * @return bool True (False on error if an error handler returns True)
  901. */
  902. function SetTitleColor($which_color)
  903. {
  904. return (bool)($this->title_color = $this->SetRGBColor($which_color));
  905. }
  906. /**
  907. * Sets the color of the X title, overriding the color set with SetTitleColor()
  908. *
  909. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  910. * @return bool True (False on error if an error handler returns True)
  911. * @since 5.2.0
  912. */
  913. function SetXTitleColor($which_color)
  914. {
  915. return (bool)($this->x_title_color = $this->SetRGBColor($which_color));
  916. }
  917. /**
  918. * Sets the color of the Y title, overriding the color set with SetTitleColor()
  919. *
  920. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  921. * @return bool True (False on error if an error handler returns True)
  922. * @since 5.2.0
  923. */
  924. function SetYTitleColor($which_color)
  925. {
  926. return (bool)($this->y_title_color = $this->SetRGBColor($which_color));
  927. }
  928. /**
  929. * Sets the color of the axis tick marks
  930. *
  931. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  932. * @return bool True (False on error if an error handler returns True)
  933. */
  934. function SetTickColor($which_color)
  935. {
  936. return (bool)($this->tick_color = $this->SetRGBColor($which_color));
  937. }
  938. /**
  939. * @deprecated Use SetTitleColor() instead
  940. */
  941. function SetLabelColor($which_color)
  942. {
  943. return $this->SetTitleColor($which_color);
  944. }
  945. /**
  946. * Sets the general text color, which is the default color for legend text, tick and data labels
  947. *
  948. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  949. * @return bool True (False on error if an error handler returns True)
  950. */
  951. function SetTextColor($which_color)
  952. {
  953. return (bool)($this->text_color = $this->SetRGBColor($which_color));
  954. }
  955. /**
  956. * Sets the color for data labels, overriding the default set with SetTextColor()
  957. *
  958. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  959. * @return bool True (False on error if an error handler returns True)
  960. * @since 5.7.0
  961. */
  962. function SetDataLabelColor($which_color)
  963. {
  964. return (bool)($this->datalabel_color = $this->SetRGBColor($which_color));
  965. }
  966. /**
  967. * Sets the color for data value labels, overriding SetTextColor() and SetDataLabelColor()
  968. *
  969. * Note: Data Value Labels are the labels within the plot area (not the axis labels).
  970. *
  971. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  972. * @return bool True (False on error if an error handler returns True)
  973. * @since 5.7.0
  974. */
  975. function SetDataValueLabelColor($which_color)
  976. {
  977. return (bool)($this->dvlabel_color = $this->SetRGBColor($which_color));
  978. }
  979. /**
  980. * Sets the color for pie chart data labels, overriding the default set with SetGridColor()
  981. *
  982. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  983. * @return bool True (False on error if an error handler returns True)
  984. * @since 5.7.0
  985. */
  986. function SetPieLabelColor($which_color)
  987. {
  988. return (bool)($this->pielabel_color = $this->SetRGBColor($which_color));
  989. }
  990. /**
  991. * Sets the color for pie chart segment borders
  992. *
  993. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  994. * @return bool True (False on error if an error handler returns True)
  995. * @since 6.0.0
  996. */
  997. function SetPieBorderColor($which_color)
  998. {
  999. return (bool)($this->pieborder_color = $this->SetRGBColor($which_color));
  1000. }
  1001. /**
  1002. * Sets the color for tick labels, overriding the default set with SetTextColor()
  1003. *
  1004. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  1005. * @return bool True (False on error if an error handler returns True)
  1006. * @since 5.7.0
  1007. */
  1008. function SetTickLabelColor($which_color)
  1009. {
  1010. return (bool)($this->ticklabel_color = $this->SetRGBColor($which_color));
  1011. }
  1012. /**
  1013. * Sets the X and Y grid colors, and the data label line color
  1014. *
  1015. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  1016. * @return bool True (False on error if an error handler returns True)
  1017. */
  1018. function SetLightGridColor($which_color)
  1019. {
  1020. return (bool)($this->light_grid_color = $this->SetRGBColor($which_color));
  1021. }
  1022. /**
  1023. * Sets the color used for the X and Y axis lines, plot border, and legend border
  1024. *
  1025. * Also sets the default color for the pie chart data labels and pie chart segment borders.
  1026. * These can be overridden by SetPieLabelColor() and SetPieBorderColor() respectively.
  1027. * Note: This has nothing to do with the grid, and we don't know where this name came from.
  1028. *
  1029. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  1030. * @return bool True (False on error if an error handler returns True)
  1031. */
  1032. function SetGridColor($which_color)
  1033. {
  1034. return (bool)($this->grid_color = $this->SetRGBColor($which_color));
  1035. }
  1036. /**
  1037. * Sets the color used for the image border, drawn if SetImageBorderType() enables it
  1038. *
  1039. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  1040. * @return bool True (False on error if an error handler returns True)
  1041. */
  1042. function SetImageBorderColor($which_color)
  1043. {
  1044. return (bool)($this->i_border = $this->SetRGBColor($which_color));
  1045. }
  1046. /**
  1047. * Designates a color to be transparent, if transparency is supported by the image format
  1048. *
  1049. * @param string|int[]|null $which_color Color to make transparent; empty|omit|NULL to reset to none
  1050. * @return bool True (False on error if an error handler returns True)
  1051. */
  1052. function SetTransparentColor($which_color = NULL)
  1053. {
  1054. $this->transparent_color = empty($which_color) ? NULL : $this->SetRGBColor($which_color);
  1055. return ($this->transparent_color !== FALSE); // True unless SetRGBColor() returned an error
  1056. }
  1057. /**
  1058. * Sets the color used for the legend background, which defaults to the image background color
  1059. *
  1060. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  1061. * @return bool True (False on error if an error handler returns True)
  1062. * @since 6.0.0
  1063. */
  1064. function SetLegendBgColor($which_color)
  1065. {
  1066. return (bool)($this->legend_bg_color = $this->SetRGBColor($which_color));
  1067. }
  1068. /**
  1069. * Sets the color used for the legend text, which defaults to the general text color
  1070. *
  1071. * @param string|int[] $which_color Color name or spec (#rrggbb, (r,g,b) array, etc)
  1072. * @return bool True (False on error if an error handler returns True)
  1073. * @since 6.0.0
  1074. */
  1075. function SetLegendTextColor($which_color)
  1076. {
  1077. return (bool)($this->legend_text_color = $this->SetRGBColor($which_color));
  1078. }
  1079. /**
  1080. * Sets the array of colors to be used (the color map)
  1081. *
  1082. * The color map maps color names into arrays of R, G, B and optionally A values.
  1083. * The selected color map can be user defined, a small predefined one,
  1084. * or a large one included from the file 'rgb.inc.php'.
  1085. *
  1086. * @param array|string $which_color_array Color map array (name=>(R,G,B[,A]), or keyword small | large
  1087. * @return bool True always
  1088. */
  1089. function SetRGBArray($which_color_array)
  1090. {
  1091. if (is_array($which_color_array)) { // User defined array
  1092. $this->rgb_array = $which_color_array;
  1093. } elseif ($which_color_array == 'small') { // Small predefined color array
  1094. $this->rgb_array = array(
  1095. 'white' => array(255, 255, 255),
  1096. 'snow' => array(255, 250, 250),
  1097. 'PeachPuff' => array(255, 218, 185),
  1098. 'ivory' => array(255, 255, 240),
  1099. 'lavender' => array(230, 230, 250),
  1100. 'black' => array( 0, 0, 0),
  1101. 'DimGrey' => array(105, 105, 105),
  1102. 'gray' => array(190, 190, 190),
  1103. 'grey' => array(190, 190, 190),
  1104. 'navy' => array( 0, 0, 128),
  1105. 'SlateBlue' => array(106, 90, 205),
  1106. 'blue' => array( 0, 0, 255),
  1107. 'SkyBlue' => array(135, 206, 235),
  1108. 'cyan' => array( 0, 255, 255),
  1109. 'DarkGreen' => array( 0, 100, 0),
  1110. 'green' => array( 0, 255, 0),
  1111. 'YellowGreen' => array(154, 205, 50),
  1112. 'yellow' => array(255, 255, 0),
  1113. 'orange' => array(255, 165, 0),
  1114. 'gold' => array(255, 215, 0),
  1115. 'peru' => array(205, 133, 63),
  1116. 'beige' => array(245, 245, 220),
  1117. 'wheat' => array(245, 222, 179),
  1118. 'tan' => array(210, 180, 140),
  1119. 'brown' => array(165, 42, 42),
  1120. 'salmon' => array(250, 128, 114),
  1121. 'red' => array(255, 0, 0),
  1122. 'pink' => array(255, 192, 203),
  1123. 'maroon' => array(176, 48, 96),
  1124. 'magenta' => array(255, 0, 255),
  1125. 'violet' => array(238, 130, 238),
  1126. 'plum' => array(221, 160, 221),
  1127. 'orchid' => array(218, 112, 214),
  1128. 'purple' => array(160, 32, 240),
  1129. 'azure1' => array(240, 255, 255),
  1130. 'aquamarine1' => array(127, 255, 212)
  1131. );
  1132. } elseif ($which_color_array == 'large') { // Large color array
  1133. if (!@include('rgb.inc.php')) {
  1134. return $this->PrintError("SetRGBArray(): Large color map could not be loaded "
  1135. . "from 'rgb.inc.php'.");
  1136. }
  1137. $this->rgb_array = $ColorArray;
  1138. } else {
  1139. return $this->PrintError("SetRGBArray(): Invalid color map selection");
  1140. }
  1141. return TRUE;
  1142. }
  1143. /**
  1144. * Parses a color specification and returns the color component values
  1145. *
  1146. * Accepted color specification forms are (1) component array: array(R,G,B)
  1147. * or array(R,G,B,A); (2) component string hexadecimal: "#RRGGBB" or
  1148. * "#RRGGBBAA"; (3) A color name from the color map array with optional
  1149. * alpha value suffix as ":alpha". R, G, and B are integers 0-255, and
  1150. * Alpha is 0 (opaque) to 127 (transparent).
  1151. *
  1152. * @param string|int[] $color_asked Color spec to parse (color name, #rrggbb, (r,g,b) array, etc)
  1153. * @param int $alpha Optional default alpha value (0-127, default 0 for opaque)
  1154. * @return int[] Color component values as array (red, green, blue, alpha)
  1155. * @deprecated Public use discouraged; intended for class internal use
  1156. */
  1157. function SetRGBColor($color_asked, $alpha = 0)
  1158. {
  1159. if (empty($color_asked)) {
  1160. $ret_val = array(0, 0, 0);
  1161. } elseif (is_array($color_asked) && (($n = count($color_asked)) == 3 || $n == 4) ) {
  1162. // Already an array of 3 or 4 elements:
  1163. $ret_val = $color_asked;
  1164. } elseif (preg_match('/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i',
  1165. $color_asked, $ss)) {
  1166. // #RRGGBB or #RRGGBBAA notation:
  1167. $ret_val = array(hexdec($ss[1]), hexdec($ss[2]), hexdec($ss[3]));
  1168. if (isset($ss[4])) $ret_val[] = hexdec($ss[4]);
  1169. } elseif (isset($this->rgb_array[$color_asked])) {
  1170. // Color by name:
  1171. $ret_val = $this->rgb_array[$color_asked];
  1172. } elseif (preg_match('/(.+):([\d]+)$/', $color_asked, $ss)
  1173. && isset($this->rgb_array[$ss[1]])) {
  1174. // Color by name with ":alpha" suffix, alpha is a decimal number:
  1175. $ret_val = $this->rgb_array[$ss[1]];
  1176. $ret_val[3] = (int)$ss[2];
  1177. } else {
  1178. return $this->PrintError("SetRGBColor(): Color '$color_asked' is not valid.");
  1179. }
  1180. // Append alpha if not already provided for:
  1181. if (count($ret_val) == 3)
  1182. $ret_val[] = $alpha;
  1183. return $ret_val;
  1184. }
  1185. /**
  1186. * Sets the colors used for plotting data sets, with optional default alpha value
  1187. *
  1188. * If passed an array, use the values as colors for sequential data sets.
  1189. * If passed a single color specification, plot all data sets using that
  1190. * single color.
  1191. * Special use cases for the $which_data argument: Missing or NULL loads
  1192. * the default data color map if no map is already set; an empty string or
  1193. * False loads the default color map even if a color map is already set.
  1194. * Note: The default value for $alpha here is NULL, not 0, so we can tell
  1195. * if it was defaulted. But the effective default value is 0 (opaque).
  1196. *
  1197. * @param array|string $which_data Array of color specifications, or one color, or empty
  1198. * @param array|string $which_border Data border colors, deprecated - use SetDataBorderColors() instead
  1199. * @param int $alpha Default alpha to apply to all data colors that do not have an alpha value
  1200. * @return bool True (False on error if an error handler returns True)
  1201. */
  1202. function SetDataColors($which_data = NULL, $which_border = NULL, $alpha = NULL)
  1203. {
  1204. if (is_array($which_data)) {
  1205. $colors = $which_data; // Use supplied array
  1206. } elseif (!empty($which_data)) {
  1207. $colors = array($which_data); // Use supplied single color
  1208. } elseif (empty($this->data_colors) || !is_null($which_data)) {
  1209. $colors = $this->default_colors; // Use default color array
  1210. } else {
  1211. // which_data is NULL or missing and a color array is already set.
  1212. // The existing color array is left alone, except that if $alpha is
  1213. // given this will replace the alpha value of each existing color.
  1214. // This makes SetDataColors(NULL, NULL, $alpha) work.
  1215. if (isset($alpha)) {
  1216. $n_colors = count($this->data_colors);
  1217. for ($i = 0; $i < $n_colors; $i++) {
  1218. $this->data_colors[$i][3] = $alpha; // Component 3 = alpha value
  1219. }
  1220. }
  1221. // No need to reparse the colors or anything else.
  1222. return TRUE;
  1223. }
  1224. if (!isset($alpha))
  1225. $alpha = 0; // Actual default is opaque colors.
  1226. // Check each color and convert to array (r,g,b,a) form.
  1227. // Use the $alpha argument as a default for the alpha value of each color.
  1228. $this->data_colors = array();
  1229. foreach ($colors as $color) {
  1230. $color_array = $this->SetRGBColor($color, $alpha);
  1231. if (!$color_array) return FALSE; // SetRGBColor already did an error message.
  1232. $this->data_colors[] = $color_array;
  1233. }
  1234. // For past compatibility:
  1235. return $this->SetDataBorderColors($which_border);
  1236. }
  1237. /**
  1238. * Sets the colors used for data borders in some plot types
  1239. *
  1240. * For plot types which support data borders, such as 'bars', this sets
  1241. * the colors used for those borders. See also SetDrawDataBorders().
  1242. * Special cases: If $which_br is missing or NULL, use the default of all
  1243. * black if colors were not already set; if an empty string or False then
  1244. * set the default of all black regardless.
  1245. *
  1246. * @param array|string $which_br Array of color specifications, or one color, or empty
  1247. * @return bool True (False on error if an error handler returns True)
  1248. */
  1249. function SetDataBorderColors($which_br = NULL)
  1250. {
  1251. if (is_array($which_br)) {
  1252. $colors = $which_br; // Use supplied array
  1253. } elseif (!empty($which_br)) {
  1254. $colors = array($which_br); // Use supplied single color
  1255. } elseif (empty($this->data_border_colors) || !is_null($which_br)) {
  1256. $colors = array('black'); // Use default
  1257. } else {
  1258. return TRUE; // Do nothing: which_br is NULL or missing and a color array is already set.
  1259. }
  1260. // Check each color and convert to array (r,g,b,a) form.
  1261. $this->data_border_colors = array();
  1262. foreach ($colors as $color) {
  1263. $color_array = $this->SetRGBColor($color);
  1264. if (!$color_array) return FALSE; // SetRGBColor already did an error message.
  1265. $this->data_border_colors[] = $color_array;
  1266. }
  1267. return TRUE;
  1268. }
  1269. /**
  1270. * Sets the colors used for data error bars
  1271. *
  1272. * Special cases for $which_err: Missing or NULL loads the default colors
  1273. * (same as default data colors) if no colors are aleady set; an empty
  1274. * string or False loads the default colors even if colors were already set.
  1275. *
  1276. * @param array|string $which_err Array of color specifications, or one color, or empty
  1277. * @return bool True (False on error if an error handler returns True)
  1278. */
  1279. function SetErrorBarColors($which_err = NULL)
  1280. {
  1281. if (is_array($which_err)) {
  1282. $colors = $which_err; // Use supplied array
  1283. } elseif (!empty($which_err)) {
  1284. $colors = array($which_err); // Use supplied single color
  1285. } elseif (empty($this->error_bar_colors) || !is_null($which_err)) {
  1286. $colors = $this->default_colors; // Use default color array
  1287. } else {
  1288. return TRUE; // Do nothing: which_err is NULL or missing and a color array is already set.
  1289. }
  1290. // Check each color and convert to array (r,g,b,a) form.
  1291. $this->error_bar_colors = array();
  1292. foreach ($colors as $color) {
  1293. $color_array = $this->SetRGBColor($color);
  1294. if (!$color_array) return FALSE; // SetRGBColor already did an error message.
  1295. $this->error_bar_colors[] = $color_array;
  1296. }
  1297. return TRUE;
  1298. }
  1299. /**
  1300. * Sets the default dashed line style (on/off pattern for dashed lines)
  1301. *
  1302. * For example: SetDashedStyle('2-3-1-2') means 2 dots of color, 3
  1303. * transparent, 1 color, then 2 transparent.
  1304. * This builds a template string $this->default_dashed_style which contains
  1305. * a space-separated series of marker (#) for pixels on, and the value of
  1306. * IMG_COLOR_TRANSPARENT for each pixel which is off.
  1307. * See SetDashedStyle() for how it is used.
  1308. *
  1309. * @param string $which_style Dashed line specification, in the form <pixels_on>-<pixels_off>...
  1310. * @return bool True (False on error if an error handler returns True)
  1311. */
  1312. function SetDefaultDashedStyle($which_style)
  1313. {
  1314. // Validate the argument as "(number)-(number)-..." with at least 2 numbers:
  1315. if (!preg_match('/^\d+-\d+(-\d+)*$/', $which_style)) {
  1316. return $this->PrintError("SetDefaultDashedStyle(): Wrong parameter '$which_style'.");
  1317. }
  1318. $result = '';
  1319. $use_color = TRUE;
  1320. $transparent = ' ' . IMG_COLOR_TRANSPARENT;
  1321. // Expand the dashed line style specifier:
  1322. foreach (explode('-', $which_style) as $n) {
  1323. $result .= str_repeat($use_color ? ' #' : $transparent, $n);
  1324. $use_color = !$use_color; // Alternate color and transparent
  1325. }
  1326. $this->default_dashed_style = ltrim($result);
  1327. return TRUE;
  1328. }
  1329. /**
  1330. * Returns a GD line style for drawing patterned or solid lines
  1331. *
  1332. * This returns a value which can be used in GD when drawing lines.
  1333. * If styles are off, it just returns the color supplied.
  1334. * If styles are on, it applies the given color to the pre-set dashed
  1335. * line style (see SetDefaultDashedStyle()) and sets that as the GD
  1336. * line style, then returns the special GD code for drawing styled lines.
  1337. *
  1338. * @param int $which_ndxcol Color index to be used for drawing
  1339. * @param bool $use_style TRUE or omit for dashed lines, FALSE for solid lines
  1340. * @return int A GD color index for drawing: either $which_ndxcol or IMG_COLOR_STYLED
  1341. */
  1342. protected function SetDashedStyle($which_ndxcol, $use_style = TRUE)
  1343. {
  1344. if (!$use_style)
  1345. return $which_ndxcol; // Styles are off; use original color for drawing
  1346. // Set the line style, substituting the specified color for the # marker:
  1347. imagesetstyle($this->img, explode(' ', str_replace('#', $which_ndxcol, $this->default_dashed_style)));
  1348. return IMG_COLOR_STYLED; // Use this value as the color for drawing
  1349. }
  1350. /**
  1351. * Sets line widths (thickness) for each data set
  1352. *
  1353. * @param int[]|int $which_lw Array of line widths in pixels, or a single value to use for all data sets
  1354. * @return bool True always
  1355. */
  1356. function SetLineWidths($which_lw=NULL)
  1357. {
  1358. if (is_array($which_lw)) {
  1359. $this->line_widths = $which_lw; // Use provided array
  1360. } elseif (!is_null($which_lw)) {
  1361. $this->line_widths = array($which_lw); // Convert value to array
  1362. }
  1363. return TRUE;
  1364. }
  1365. /**
  1366. * Sets the line style (solid or dashed) for each data set
  1367. *
  1368. * @param string[]|string $which_ls Array or single keyword: solid | dashed | none
  1369. * @return bool True always
  1370. */
  1371. function SetLineStyles($which_ls=NULL)
  1372. {
  1373. if (is_array($which_ls)) {
  1374. $this->line_styles = $which_ls; // Use provided array
  1375. } elseif (!is_null($which_ls)) {
  1376. $this->line_styles = ($which_ls) ? array($which_ls) : array('solid');
  1377. }
  1378. return TRUE;
  1379. }
  1380. /////////////////////////////////////////////
  1381. ////////////// TEXT and FONTS
  1382. /////////////////////////////////////////////
  1383. /**
  1384. * Sets spacing between lines of multi-line labels
  1385. *
  1386. * @param int $which_spc Text line spacing factor (pixels for GD text, scale control for TTF text)
  1387. * @return bool True always
  1388. */
  1389. function SetLineSpacing($which_spc)
  1390. {
  1391. $this->line_spacing = $which_spc;
  1392. return TRUE;
  1393. }
  1394. /**
  1395. * Sets the default font type
  1396. *
  1397. * @param bool $which_ttf True to default to TrueType fonts, False to default to GD (fixed) fonts
  1398. * @return bool True (False on error if an error handler returns True)
  1399. */
  1400. function SetUseTTF($which_ttf)
  1401. {
  1402. $this->use_ttf = $which_ttf;
  1403. return $this->SetDefaultFonts();
  1404. }
  1405. /**
  1406. * Sets the default TrueType font directory
  1407. *
  1408. * @param string $which_path Full path to a directory containing TrueType fonts
  1409. * @return bool True (False on error if an error handler returns True)
  1410. */
  1411. function SetTTFPath($which_path)
  1412. {
  1413. if (!is_dir($which_path) || !is_readable($which_path)) {
  1414. return $this->PrintError("SetTTFPath(): $which_path is not a valid path.");
  1415. }
  1416. $this->ttf_path = $which_path;
  1417. return TRUE;
  1418. }
  1419. /**
  1420. * Sets the default TrueType font, and resets all elements to use that TrueType font and default sizes
  1421. *
  1422. * @param string $which_font Font filename or path; omit or NULL to use a default font
  1423. * @return bool True (False on error if an error handler returns True)
  1424. */
  1425. function SetDefaultTTFont($which_font = NULL)
  1426. {
  1427. $this->default_ttfont = $which_font;
  1428. return $this->SetUseTTF(TRUE);
  1429. }
  1430. /**
  1431. * Returns the default TrueType font name, searching for one if necessary
  1432. *
  1433. * If no default has been set, this tries some likely candidates for a font which
  1434. * can be loaded. If it finds one that works, that becomes the default TT font.
  1435. * If there is no default and it cannot find a working font, it falls back to
  1436. * the original PHPlot default (which will not likely work either).
  1437. *
  1438. * @return string Default TrueType font filename or pathname
  1439. * @since 5.1.3
  1440. */
  1441. protected function GetDefaultTTFont()
  1442. {
  1443. if (!isset($this->default_ttfont)) {
  1444. // No default font yet. Try some common sans-serif fonts.
  1445. $fonts = array('LiberationSans-Regular.ttf', // For Linux with a correct GD font search path
  1446. 'Verdana.ttf', 'Arial.ttf', 'Helvetica.ttf', // For Windows, maybe others
  1447. 'liberation/LiberationSans-Regular.ttf', // For newer Ubuntu etc
  1448. 'ttf-liberation/LiberationSans-Regular.ttf', // For older Debian, Ubuntu, etc
  1449. 'benjamingothic.ttf', // Original PHPlot default
  1450. );
  1451. foreach ($fonts as $font) {
  1452. // First try the font name alone, to see if GD can find and load it.
  1453. if (@imagettfbbox(10, 0, $font, "1") !== False)
  1454. break;
  1455. // If the font wasn't found, try it with the default TTF path in front.
  1456. $font_with_path = $this->ttf_path . DIRECTORY_SEPARATOR . $font;
  1457. if (@imagettfbbox(10, 0, $font_with_path, "1") !== False) {
  1458. $font = $font_with_path;
  1459. break;
  1460. }
  1461. }
  1462. // We either have a working font, or are using the last one regardless.
  1463. $this->default_ttfont = $font;
  1464. }
  1465. return $this->default_ttfont;
  1466. }
  1467. /**
  1468. * Selects all the default font values and sizes
  1469. *
  1470. * @return bool True (False on error if an error handler returns True)
  1471. */
  1472. protected function SetDefaultFonts()
  1473. {
  1474. if ($this->use_ttf) {
  1475. // Defaults for use of TrueType fonts:
  1476. return $this->SetFontTTF('generic', '', 8)
  1477. && $this->SetFontTTF('title', '', 14)
  1478. && $this->SetFontTTF('legend', '', 8)
  1479. && $this->SetFontTTF('x_label', '', 6)
  1480. && $this->SetFontTTF('y_label', '', 6)
  1481. && $this->SetFontTTF('x_title', '', 10)
  1482. && $this->SetFontTTF('y_title', '', 10);
  1483. }
  1484. // Defaults for use of GD fonts:
  1485. return $this->SetFontGD('generic', 2)
  1486. && $this->SetFontGD('title', 5)
  1487. && $this->SetFontGD('legend', 2)
  1488. && $this->SetFontGD('x_label', 1)
  1489. && $this->SetFontGD('y_label', 1)
  1490. && $this->SetFontGD('x_title', 3)
  1491. && $this->SetFontGD('y_title', 3);
  1492. }
  1493. /**
  1494. * Selects a GD (fixed) font to use for a plot element
  1495. *
  1496. * Available element names are: title legend generic x_label y_label x_title y_title
  1497. *
  1498. * @param string $which_elem Name of the element to change the font for
  1499. * @param int|string $which_font GD font number: 1 2 3 4 or 5
  1500. * @param int $which_spacing Optional spacing in pixels between text lines
  1501. * @return bool True (False on error if an error handler returns True)
  1502. * @since 5.0.6
  1503. */
  1504. function SetFontGD($which_elem, $which_font, $which_spacing = NULL)
  1505. {
  1506. if ($which_font < 1 || 5 < $which_font) {
  1507. return $this->PrintError(__FUNCTION__ . ': Font size must be 1, 2, 3, 4 or 5');
  1508. }
  1509. if (!$this->CheckOption($which_elem,
  1510. 'generic, title, legend, x_label, y_label, x_title, y_title',
  1511. __FUNCTION__)) {
  1512. return FALSE;
  1513. }
  1514. // Store the font parameters: name/size, char cell height and width.
  1515. $this->fonts[$which_elem] = array('ttf' => FALSE,
  1516. 'font' => $which_font,
  1517. 'height' => ImageFontHeight($which_font),
  1518. 'width' => ImageFontWidth($which_font),
  1519. 'line_spacing' => $which_spacing);
  1520. return TRUE;
  1521. }
  1522. /**
  1523. * Selects a TrueType font for to use for a plot element
  1524. *
  1525. * Available element names are: title legend generic x_label y_label x_title y_title
  1526. *
  1527. * @param string $which_elem Name of the element to change the font for
  1528. * @param string $which_font TrueType font file or pathname; empty or NULL for the default font
  1529. * @param int $which_size Optional font size in points (default 12)
  1530. * @param int $which_spacing Optional line spacing adjustment factor
  1531. * @return bool True (False on error if an error handler returns True)
  1532. * @since 5.0.6
  1533. */
  1534. function SetFontTTF($which_elem, $which_font, $which_size = 12, $which_spacing = NULL)
  1535. {
  1536. if (!$this->CheckOption($which_elem,
  1537. 'generic, title, legend, x_label, y_label, x_title, y_title',
  1538. __FUNCTION__)) {
  1539. return FALSE;
  1540. }
  1541. // Empty font name means use the default font.
  1542. if (empty($which_font))
  1543. $which_font = $this->GetDefaultTTFont();
  1544. $path = $which_font;
  1545. // First try the font name directly, if not then try with path.
  1546. // Use GD imagettfbbox() to determine if this is a valid font.
  1547. // The return $bbox is used below, if valid.
  1548. if (($bbox = @imagettfbbox($which_size, 0, $path, "E")) === False) {
  1549. $path = $this->ttf_path . DIRECTORY_SEPARATOR . $which_font;
  1550. if (($bbox = @imagettfbbox($which_size, 0, $path, "E")) === False) {
  1551. return $this->PrintError(__FUNCTION__ . ": Can't find TrueType font $which_font");
  1552. }
  1553. }
  1554. // Calculate the font height and inherent line spacing. TrueType fonts have this information
  1555. // internally, but PHP/GD has no way to directly access it. So get the bounding box size of
  1556. // an upper-case character without descenders, and the baseline-to-baseline height.
  1557. // Note: In practice, $which_size = $height, maybe +/-1 . But which_size is in points,
  1558. // and height is in pixels, and someday GD may be able to tell the difference.
  1559. // The character width is saved too, but not used by the normal text drawing routines - it
  1560. // isn't necessarily a fixed-space font. It is used in DrawLegend.
  1561. $height = $bbox[1] - $bbox[5];
  1562. $width = $bbox[2] - $bbox[0];
  1563. $bbox = ImageTTFBBox($which_size, 0, $path, "E\nE");
  1564. $spacing = $bbox[1] - $bbox[5] - 2 * $height;
  1565. // Store the font parameters:
  1566. $this->fonts[$which_elem] = array('ttf' => TRUE,
  1567. 'font' => $path,
  1568. 'size' => $which_size,
  1569. 'height' => $height,
  1570. 'width' => $width,
  1571. 'spacing' => $spacing,
  1572. 'line_spacing' => $which_spacing);
  1573. return TRUE;
  1574. }
  1575. /**
  1576. * Selects which font to use for a plot element
  1577. *
  1578. * This uses either GD (fixed) or TrueType fonts, depending on the default text
  1579. * font type as set with SetUseTTF().
  1580. *
  1581. * Available element names are: title legend generic x_label y_label x_title y_title
  1582. *
  1583. * @param string $which_elem Name of the element to change the font for
  1584. * @param int|string $which_font For GD fonts, a font number; for TrueType, a font filename or pathname
  1585. * @param int $which_size Optional font size in points for TrueType fonts, ignored for GD fonts
  1586. * @param int $line_spacing Optional line spacing adjustment factor
  1587. * @return bool True (False on error if an error handler returns True)
  1588. */
  1589. function SetFont($which_elem, $which_font, $which_size = 12, $line_spacing = NULL)
  1590. {
  1591. if ($this->use_ttf)
  1592. return $this->SetFontTTF($which_elem, $which_font, $which_size, $line_spacing);
  1593. return $this->SetFontGD($which_elem, $which_font, $line_spacing);
  1594. }
  1595. /**
  1596. * Returns the inter-line spacing for a font
  1597. *
  1598. * @param array $font The font, specified as a PHPlot font array
  1599. * @return int Spacing between text lines in pixels for text using this font
  1600. * @since 5.0.6
  1601. */
  1602. protected function GetLineSpacing($font)
  1603. {
  1604. // Use the per-font line spacing preference, if set, else the global value:
  1605. if (isset($font['line_spacing']))
  1606. $line_spacing = $font['line_spacing'];
  1607. else
  1608. $line_spacing = $this->line_spacing;
  1609. // For GD fonts, that is the spacing in pixels.
  1610. // For TTF, adjust based on the 'natural' font spacing (see SetFontTTF):
  1611. if ($font['ttf']) {
  1612. $line_spacing = (int)($line_spacing * $font['spacing'] / 6.0);
  1613. }
  1614. return $line_spacing;
  1615. }
  1616. /*
  1617. * Text drawing and sizing functions:
  1618. * ProcessText is meant for use only by DrawText and SizeText.
  1619. * ProcessText(True, ...) - Draw a block of text
  1620. * ProcessText(False, ...) - Just return ($width, $height) of
  1621. * the orthogonal bounding box containing the text.
  1622. * ProcessText is further split into separate functions for GD and TTF
  1623. * text, due to the size of the code.
  1624. *
  1625. * Horizontal and vertical alignment are relative to the drawing. That is:
  1626. * vertical text (90 deg) gets centered along Y position with
  1627. * v_align = 'center', and adjusted to the right of X position with
  1628. * h_align = 'right'. Another way to look at this is to say
  1629. * that text rotation happens first, then alignment.
  1630. *
  1631. * Original multiple lines code submitted by Remi Ricard.
  1632. * Original vertical code submitted by Marlin Viss.
  1633. *
  1634. * Text routines rewritten by ljb to fix alignment and position problems.
  1635. * Here is my explanation and notes.
  1636. *
  1637. * + Process TTF text one line at a time, not as a block. (See below)
  1638. * + Flipped top vs bottom vertical alignment. The usual interpretation
  1639. * is: bottom align means bottom of the text is at the specified Y
  1640. * coordinate. For some reason, PHPlot did left/right the correct way,
  1641. * but had top/bottom reversed. I fixed it, and left the default valign
  1642. * argument as bottom, but the meaning of the default value changed.
  1643. *
  1644. * For GD font text, only single-line text is handled by GD, and the
  1645. * basepoint is the upper left corner of each text line.
  1646. * For TTF text, multi-line text could be handled by GD, with the text
  1647. * basepoint at the lower left corner of the first line of text.
  1648. * (Behavior of TTF drawing routines on multi-line text is not documented.)
  1649. * But you cannot do left/center/right alignment on each line that way,
  1650. * or proper line spacing.
  1651. * Therefore, for either text type, we have to break up the text into
  1652. * lines and position each line independently.
  1653. *
  1654. * There are 9 alignment modes: Horizontal = left, center, or right, and
  1655. * Vertical = top, center, or bottom. Alignment is interpreted relative to
  1656. * the image, not as the text is read. This makes sense when you consider
  1657. * for example X axis labels. They need to be centered below the marks
  1658. * (center, top alignment) regardless of the text angle.
  1659. * 'Bottom' alignment really means baseline alignment.
  1660. *
  1661. * GD font text is supported (by libgd) at 0 degrees and 90 degrees only.
  1662. * Multi-line or single line text works with any of the 9 alignment modes.
  1663. *
  1664. * TTF text can be at any angle. The 9 alignment modes work for all angles,
  1665. * but the results might not be what you expect for multi-line text. Alignment
  1666. * applies to the orthogonal (aligned with X and Y axes) bounding box that
  1667. * contains the text, and to each line in the multi-line text box. Since
  1668. * alignment is relative to the image, 45 degree multi-line text aligns
  1669. * differently from 46 degree text.
  1670. *
  1671. * Note that PHPlot allows multi-line text for the 3 titles, and they
  1672. * are only drawn at 0 degrees (main and X titles) or 90 degrees (Y title).
  1673. * Data labels can also be multi-line, and they can be drawn at any angle.
  1674. * -ljb 2007-11-03
  1675. *
  1676. */
  1677. /**
  1678. * Draws or returns the size of a text string using GD fixed fonts
  1679. *
  1680. * This is intended for use only by ProcessText(). See notes there, but note that
  1681. * the $font and alignment parameters are pre-processed there and differ here.
  1682. * GD text only supports 0 and 90 degrees. This function treats an angle >= 45
  1683. * as 90 degrees, and < 45 as 0 degrees.
  1684. *
  1685. * @param bool $draw_it True to draw the text, False to just return the orthogonal width and height
  1686. * @param array $font A PHPlot font array (with 'ttf' = False)
  1687. * @param float $angle Text angle in degrees. GD only supports 0 and 90.
  1688. * @param int $x Reference point X coordinate for the text (ignored if $draw_it is False)
  1689. * @param int $y Reference point Y coordinate for the text (ignored if $draw_it is False)
  1690. * @param int $color GD color index to use for drawing the text (ignored if $draw_it is False)
  1691. * @param string $text The text to draw or size (can have newlines \n within)
  1692. * @param float $h_factor Horizontal alignment factor: 0=left|0.5=center|1=right (ignored if !$draw_it)
  1693. * @param float $v_factor Vertical alignment factor: 0=top|0.5=center|1=bottom (ignored if !$draw_it)
  1694. * @return bool|int[] True, if drawing text; an array of ($width, $height) if not.
  1695. * @since 5.0.5
  1696. */
  1697. protected function ProcessTextGD($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor)
  1698. {
  1699. // Extract font parameters:
  1700. $font_number = $font['font'];
  1701. $font_width = $font['width'];
  1702. $font_height = $font['height'];
  1703. $line_spacing = $this->GetLineSpacing($font);
  1704. // Break up the text into lines, trim whitespace, find longest line.
  1705. // Save the lines and length for drawing below.
  1706. $longest = 0;
  1707. foreach (explode("\n", $text) as $each_line) {
  1708. $lines[] = $line = trim($each_line);
  1709. $line_lens[] = $line_len = strlen($line);
  1710. if ($line_len > $longest) $longest = $line_len;
  1711. }
  1712. $n_lines = count($lines);
  1713. // Width, height are based on font size and longest line, line count respectively.
  1714. // These are relative to the text angle.
  1715. $total_width = $longest * $font_width;
  1716. $total_height = $n_lines * $font_height + ($n_lines - 1) * $line_spacing;
  1717. if (!$draw_it) {
  1718. if ($angle < 45) return array($total_width, $total_height);
  1719. return array($total_height, $total_width);
  1720. }
  1721. $interline_step = $font_height + $line_spacing; // Line-to-line step
  1722. if ($angle >= 45) {
  1723. // Vertical text (90 degrees):
  1724. // (Remember the alignment convention with vertical text)
  1725. // For 90 degree text, alignment factors change like this:
  1726. $temp = $v_factor;
  1727. $v_factor = $h_factor;
  1728. $h_factor = 1 - $temp;
  1729. $draw_func = 'ImageStringUp';
  1730. // Rotation matrix "R" for 90 degrees (with Y pointing down):
  1731. $r00 = 0; $r01 = 1;
  1732. $r10 = -1; $r11 = 0;
  1733. } else {
  1734. // Horizontal text (0 degrees):
  1735. $draw_func = 'ImageString';
  1736. // Rotation matrix "R" for 0 degrees:
  1737. $r00 = 1; $r01 = 0;
  1738. $r10 = 0; $r11 = 1;
  1739. }
  1740. // Adjust for vertical alignment (horizontal text) or horizontal alignment (vertical text):
  1741. $factor = (int)($total_height * $v_factor);
  1742. $xpos = $x - $r01 * $factor;
  1743. $ypos = $y - $r11 * $factor;
  1744. // Debug callback provides the bounding box:
  1745. if ($this->GetCallback('debug_textbox')) {
  1746. if ($angle >= 45) {
  1747. $bbox_width = $total_height;
  1748. $bbox_height = $total_width;
  1749. $px = $xpos;
  1750. $py = $ypos - (1 - $h_factor) * $total_width;
  1751. } else {
  1752. $bbox_width = $total_width;
  1753. $bbox_height = $total_height;
  1754. $px = $xpos - $h_factor * $total_width;
  1755. $py = $ypos;
  1756. }
  1757. $this->DoCallback('debug_textbox', $px, $py, $bbox_width, $bbox_height);
  1758. }
  1759. for ($i = 0; $i < $n_lines; $i++) {
  1760. // Adjust for alignment of this line within the text block:
  1761. $factor = (int)($line_lens[$i] * $font_width * $h_factor);
  1762. $x = $xpos - $r00 * $factor;
  1763. $y = $ypos - $r10 * $factor;
  1764. // Call ImageString or ImageStringUp:
  1765. $draw_func($this->img, $font_number, $x, $y, $lines[$i], $color);
  1766. // Step to the next line of text. This is a rotation of (x=0, y=interline_spacing)
  1767. $xpos += $r01 * $interline_step;
  1768. $ypos += $r11 * $interline_step;
  1769. }
  1770. return TRUE;
  1771. }
  1772. /**
  1773. * Draws or returns the size of a text string using TrueType fonts (TTF)
  1774. *
  1775. * This is intended for use only by ProcessText(). See notes there, but note that
  1776. * the $font and alignment parameters are pre-processed there and differ here.
  1777. *
  1778. * @param bool $draw_it True to draw the text, False to just return the orthogonal width and height
  1779. * @param array $font A PHPlot font array (with 'ttf' = True)
  1780. * @param float $angle Text angle in degrees
  1781. * @param int $x Reference point X coordinate for the text (ignored if $draw_it is False)
  1782. * @param int $y Reference point Y coordinate for the text (ignored if $draw_it is False)
  1783. * @param int $color GD color index to use for drawing the text (ignored if $draw_it is False)
  1784. * @param string $text The text to draw or size (can have newlines \n within)
  1785. * @param float $h_factor Horizontal alignment factor: 0=left|0.5=center|1=right (ignored if !$draw_it)
  1786. * @param float $v_factor Vertical alignment factor: 0=top|0.5=center|1=bottom (ignored if !$draw_it)
  1787. * @return bool|int[] True, if drawing text; an array of ($width, $height) if not.
  1788. * @since 5.0.5
  1789. */
  1790. protected function ProcessTextTTF($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor)
  1791. {
  1792. // Extract font parameters (see SetFontTTF):
  1793. $font_file = $font['font'];
  1794. $font_size = $font['size'];
  1795. $font_height = $font['height'];
  1796. $line_spacing = $this->GetLineSpacing($font);
  1797. // Break up the text into lines, trim whitespace.
  1798. // Calculate the total width and height of the text box at 0 degrees.
  1799. // Save the trimmed lines and their widths for later when drawing.
  1800. // To get uniform spacing, don't use the actual line heights.
  1801. // Total height = Font-specific line heights plus inter-line spacing.
  1802. // Total width = width of widest line.
  1803. // Last Line Descent is the offset from the bottom to the text baseline.
  1804. // Note: For some reason, ImageTTFBBox uses (-1,-1) as the reference point.
  1805. // So 1+bbox[1] is the baseline to bottom distance.
  1806. $total_width = 0;
  1807. $lastline_descent = 0;
  1808. foreach (explode("\n", $text) as $each_line) {
  1809. $lines[] = $line = trim($each_line);
  1810. $bbox = ImageTTFBBox($font_size, 0, $font_file, $line);
  1811. $line_widths[] = $width = $bbox[2] - $bbox[0];
  1812. if ($width > $total_width) $total_width = $width;
  1813. $lastline_descent = 1 + $bbox[1];
  1814. }
  1815. $n_lines = count($lines);
  1816. $total_height = $n_lines * $font_height + ($n_lines - 1) * $line_spacing;
  1817. // Calculate the rotation matrix for the text's angle. Remember that GD points Y down,
  1818. // so the sin() terms change sign.
  1819. $theta = deg2rad($angle);
  1820. $cos_t = cos($theta);
  1821. $sin_t = sin($theta);
  1822. $r00 = $cos_t; $r01 = $sin_t;
  1823. $r10 = -$sin_t; $r11 = $cos_t;
  1824. // Make a bounding box of the right size, with upper left corner at (0,0).
  1825. // By convention, the point order is: LL, LR, UR, UL.
  1826. // Note this is still working with the text at 0 degrees.
  1827. // When sizing text (SizeText), use the overall size with descenders.
  1828. // This tells the caller how much room to leave for the text.
  1829. // When drawing text (DrawText), use the size without descenders - that
  1830. // is, down to the baseline. This is for accurate positioning.
  1831. $b[0] = 0;
  1832. if ($draw_it) {
  1833. $b[1] = $total_height;
  1834. } else {
  1835. $b[1] = $total_height + $lastline_descent;
  1836. }
  1837. $b[2] = $total_width; $b[3] = $b[1];
  1838. $b[4] = $total_width; $b[5] = 0;
  1839. $b[6] = 0; $b[7] = 0;
  1840. // Rotate the bounding box, then offset to the reference point:
  1841. for ($i = 0; $i < 8; $i += 2) {
  1842. $x_b = $b[$i];
  1843. $y_b = $b[$i+1];
  1844. $c[$i] = $x + $r00 * $x_b + $r01 * $y_b;
  1845. $c[$i+1] = $y + $r10 * $x_b + $r11 * $y_b;
  1846. }
  1847. // Get an orthogonal (aligned with X and Y axes) bounding box around it, by
  1848. // finding the min and max X and Y:
  1849. $bbox_ref_x = $bbox_max_x = $c[0];
  1850. $bbox_ref_y = $bbox_max_y = $c[1];
  1851. for ($i = 2; $i < 8; $i += 2) {
  1852. $x_b = $c[$i];
  1853. if ($x_b < $bbox_ref_x) $bbox_ref_x = $x_b;
  1854. elseif ($bbox_max_x < $x_b) $bbox_max_x = $x_b;
  1855. $y_b = $c[$i+1];
  1856. if ($y_b < $bbox_ref_y) $bbox_ref_y = $y_b;
  1857. elseif ($bbox_max_y < $y_b) $bbox_max_y = $y_b;
  1858. }
  1859. $bbox_width = $bbox_max_x - $bbox_ref_x;
  1860. $bbox_height = $bbox_max_y - $bbox_ref_y;
  1861. if (!$draw_it) {
  1862. // Return the bounding box, rounded up (so it always contains the text):
  1863. return array((int)ceil($bbox_width), (int)ceil($bbox_height));
  1864. }
  1865. $interline_step = $font_height + $line_spacing; // Line-to-line step
  1866. // Calculate the offsets from the supplied reference point to the
  1867. // upper-left corner of the text.
  1868. // Start at the reference point at the upper left corner of the bounding
  1869. // box (bbox_ref_x, bbox_ref_y) then adjust it for the 9 point alignment.
  1870. // h,v_factor are 0,0 for top,left, .5,.5 for center,center, 1,1 for bottom,right.
  1871. // $off_x = $bbox_ref_x + $bbox_width * $h_factor - $x;
  1872. // $off_y = $bbox_ref_y + $bbox_height * $v_factor - $y;
  1873. // Then use that offset to calculate back to the supplied reference point x, y
  1874. // to get the text base point.
  1875. // $qx = $x - $off_x;
  1876. // $qy = $y - $off_y;
  1877. // Reduces to:
  1878. $qx = 2 * $x - $bbox_ref_x - $bbox_width * $h_factor;
  1879. $qy = 2 * $y - $bbox_ref_y - $bbox_height * $v_factor;
  1880. // Check for debug callback. Don't calculate bounding box unless it is wanted.
  1881. if ($this->GetCallback('debug_textbox')) {
  1882. // Calculate the orthogonal bounding box coordinates for debug testing.
  1883. // qx, qy is upper left corner relative to the text.
  1884. // Calculate px,py: upper left corner (absolute) of the bounding box.
  1885. // There are 4 equation sets for this, depending on the quadrant:
  1886. if ($sin_t > 0) {
  1887. if ($cos_t > 0) {
  1888. // Quadrant: 0d - 90d:
  1889. $px = $qx; $py = $qy - $total_width * $sin_t;
  1890. } else {
  1891. // Quadrant: 90d - 180d:
  1892. $px = $qx + $total_width * $cos_t; $py = $qy - $bbox_height;
  1893. }
  1894. } else {
  1895. if ($cos_t < 0) {
  1896. // Quadrant: 180d - 270d:
  1897. $px = $qx - $bbox_width; $py = $qy + $total_height * $cos_t;
  1898. } else {
  1899. // Quadrant: 270d - 360d:
  1900. $px = $qx + $total_height * $sin_t; $py = $qy;
  1901. }
  1902. }
  1903. $this->DoCallback('debug_textbox', $px, $py, $bbox_width, $bbox_height);
  1904. }
  1905. // Since alignment is applied after rotation, which parameter is used
  1906. // to control alignment of each line within the text box varies with
  1907. // the angle.
  1908. // Angle (degrees): Line alignment controlled by:
  1909. // -45 < angle <= 45 h_align
  1910. // 45 < angle <= 135 reversed v_align
  1911. // 135 < angle <= 225 reversed h_align
  1912. // 225 < angle <= 315 v_align
  1913. if ($cos_t >= $sin_t) {
  1914. if ($cos_t >= -$sin_t) $line_align_factor = $h_factor;
  1915. else $line_align_factor = $v_factor;
  1916. } else {
  1917. if ($cos_t >= -$sin_t) $line_align_factor = 1-$v_factor;
  1918. else $line_align_factor = 1-$h_factor;
  1919. }
  1920. // Now we have the start point, spacing and in-line alignment factor.
  1921. // We are finally ready to start drawing the text, line by line.
  1922. for ($i = 0; $i < $n_lines; $i++) {
  1923. // For drawing TTF text, the reference point is the left edge of the
  1924. // text baseline (not the lower left corner of the bounding box).
  1925. // The following also adjusts for horizontal (relative to
  1926. // the text) alignment of the current line within the box.
  1927. // What is happening is rotation of this vector by the text angle:
  1928. // (x = (total_width - line_width) * factor, y = font_height)
  1929. $width_factor = ($total_width - $line_widths[$i]) * $line_align_factor;
  1930. $rx = $qx + $r00 * $width_factor + $r01 * $font_height;
  1931. $ry = $qy + $r10 * $width_factor + $r11 * $font_height;
  1932. // Finally, draw the text:
  1933. ImageTTFText($this->img, $font_size, $angle, $rx, $ry, $color, $font_file, $lines[$i]);
  1934. // Step to position of next line.
  1935. // This is a rotation of (x=0,y=height+line_spacing) by $angle:
  1936. $qx += $r01 * $interline_step;
  1937. $qy += $r11 * $interline_step;
  1938. }
  1939. return TRUE;
  1940. }
  1941. /**
  1942. * Draws or returns the size of a text string
  1943. *
  1944. * This is intended for use by DrawText() and SizeText() exclusively. It hides the
  1945. * differences between GD and TTF text from those and higher level functions. It uses
  1946. * either ProcessTextTTF() or ProcessTextGD() to do the actual drawing or sizing.
  1947. *
  1948. * @param bool $draw_it True to draw the text, False to just return the orthogonal width and height
  1949. * @param string|array|null $font_id Text element name, empty or NULL for 'generic', or font array
  1950. * @param float $angle Text angle in degrees
  1951. * @param int $x Reference point X coordinate for the text (ignored if $draw_it is False)
  1952. * @param int $y Reference point Y coordinate for the text (ignored if $draw_it is False)
  1953. * @param int $color GD color index to use for drawing the text (ignored if $draw_it is False)
  1954. * @param string $text The text to draw or size (can have newlines \n within)
  1955. * @param string $halign Horizontal alignment: left | center | right (ignored if $draw_it is False)
  1956. * @param string $valign Vertical alignment: top | center | bottom (ignored if $draw_it is False)
  1957. * @return bool|int[] True, if drawing text; an array of ($width, $height) if not.
  1958. */
  1959. protected function ProcessText($draw_it, $font_id, $angle, $x, $y, $color, $text, $halign, $valign)
  1960. {
  1961. // Empty text case:
  1962. if ($text === '') {
  1963. if ($draw_it) return TRUE;
  1964. return array(0, 0);
  1965. }
  1966. // Calculate width and height offset factors using the alignment args:
  1967. if ($valign == 'top') $v_factor = 0;
  1968. elseif ($valign == 'center') $v_factor = 0.5;
  1969. else $v_factor = 1.0; // 'bottom'
  1970. if ($halign == 'left') $h_factor = 0;
  1971. elseif ($halign == 'center') $h_factor = 0.5;
  1972. else $h_factor = 1.0; // 'right'
  1973. // Preferred usage for $font_id is a text element name (see SetFont()), but for compatibility
  1974. // accept a font array too. For external (callback) usage, support a default font.
  1975. if (is_array($font_id)) $font = $font_id; // Use supplied array; deprecated
  1976. elseif (!empty($font_id) && isset($this->fonts[$font_id])) $font = $this->fonts[$font_id];
  1977. else $font = $this->fonts['generic']; // Fallback default, or font_id is empty.
  1978. if ($font['ttf']) {
  1979. return $this->ProcessTextTTF($draw_it, $font, $angle, $x, $y, $color, $text,
  1980. $h_factor, $v_factor);
  1981. }
  1982. return $this->ProcessTextGD($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor);
  1983. }
  1984. /**
  1985. * Draws a string of text on the plot
  1986. *
  1987. * Note: This function is mostly for internal use, and is not documented
  1988. * for public use. But it can be legitimately used from a PHPlot callback.
  1989. *
  1990. * @param string|array|null $which_font Text element name, empty or NULL for 'generic', or font array
  1991. * @param float $which_angle Text angle in degrees
  1992. * @param int $which_xpos Reference point X coordinate for the text
  1993. * @param int $which_ypos Reference point Y coordinate for the text
  1994. * @param int $which_color GD color index to use for drawing the text
  1995. * @param string $which_text The text to draw, with newlines (\n) between lines
  1996. * @param string $which_halign Horizontal alignment (relative to the image): left | center | right
  1997. * @param string $which_valign Vertical alignment (relative to the image): top | center | bottom
  1998. * @return bool True always
  1999. */
  2000. function DrawText($which_font, $which_angle, $which_xpos, $which_ypos, $which_color, $which_text,
  2001. $which_halign = 'left', $which_valign = 'bottom')
  2002. {
  2003. return $this->ProcessText(TRUE,
  2004. $which_font, $which_angle, $which_xpos, $which_ypos,
  2005. $which_color, $which_text, $which_halign, $which_valign);
  2006. }
  2007. /**
  2008. * Calculates the size of block of text
  2009. *
  2010. * The returned size is the orthogonal width and height of a bounding
  2011. * box aligned with the X and Y axes of the text. Only for angle=0 is
  2012. * this the actual width and height of the text block, but for any angle
  2013. * it is the amount of space needed to contain the text.
  2014. * Note: This function is mostly for internal use, and is not documented
  2015. * for public use. But it can be legitimately used from a PHPlot callback.
  2016. *
  2017. * @param string|array|null $which_font Text element name, empty or NULL for 'generic', or font array
  2018. * @param float $which_angle Text angle in degrees
  2019. * @param string $which_text The text to calculate size of
  2020. * @return int[] A two element array ($width, $height) of the text
  2021. */
  2022. function SizeText($which_font, $which_angle, $which_text)
  2023. {
  2024. // Color, position, and alignment are not used when calculating the size.
  2025. return $this->ProcessText(FALSE,
  2026. $which_font, $which_angle, 0, 0, 1, $which_text, '', '');
  2027. }
  2028. /////////////////////////////////////////////
  2029. /////////// INPUT / OUTPUT CONTROL
  2030. /////////////////////////////////////////////
  2031. /**
  2032. * Selects the graphic image format generated by DrawGraph()
  2033. *
  2034. * @param string $format The format to use: jpg | png | gif | wbmp
  2035. * @return bool True (False on error if an error handler returns True)
  2036. */
  2037. function SetFileFormat($format)
  2038. {
  2039. $asked = $this->CheckOption($format, 'jpg, png, gif, wbmp', __FUNCTION__);
  2040. if (!$asked) return FALSE;
  2041. switch ($asked) {
  2042. case 'jpg':
  2043. $format_test = IMG_JPG;
  2044. break;
  2045. case 'png':
  2046. $format_test = IMG_PNG;
  2047. break;
  2048. case 'gif':
  2049. $format_test = IMG_GIF;
  2050. break;
  2051. case 'wbmp':
  2052. $format_test = IMG_WBMP;
  2053. break;
  2054. }
  2055. if (!(imagetypes() & $format_test)) {
  2056. return $this->PrintError("SetFileFormat(): File format '$format' not supported");
  2057. }
  2058. $this->file_format = $asked;
  2059. return TRUE;
  2060. }
  2061. /**
  2062. * Sets an image file to be used as the image background
  2063. *
  2064. * @param string $input_file Path to the file to be used (jpeg, png or gif)
  2065. * @param string $mode Optional method for the background: centeredtile | tile | scale
  2066. * @return bool True (False on error if an error handler returns True)
  2067. */
  2068. function SetBgImage($input_file, $mode='centeredtile')
  2069. {
  2070. $this->bgmode = $this->CheckOption($mode, 'tile, centeredtile, scale', __FUNCTION__);
  2071. $this->bgimg = $input_file;
  2072. return (boolean)$this->bgmode;
  2073. }
  2074. /**
  2075. * Sets an image file to be used as the plot area background
  2076. *
  2077. * @param string $input_file Path to the file to be used (jpeg, png or gif)
  2078. * @param string $mode Optional method for the background: centeredtile | tile | scale
  2079. * @return bool True (False on error if an error handler returns True)
  2080. */
  2081. function SetPlotAreaBgImage($input_file, $mode='tile')
  2082. {
  2083. $this->plotbgmode = $this->CheckOption($mode, 'tile, centeredtile, scale', __FUNCTION__);
  2084. $this->plotbgimg = $input_file;
  2085. return (boolean)$this->plotbgmode;
  2086. }
  2087. /**
  2088. * Redirects PHPlot output to a file
  2089. *
  2090. * Note: Output file has no effect unless SetIsInline(TRUE) is called.
  2091. *
  2092. * @param string $which_output_file Pathname of the file to write the image data into
  2093. * @return bool True always
  2094. */
  2095. function SetOutputFile($which_output_file)
  2096. {
  2097. if (isset($which_output_file) && $which_output_file !== '')
  2098. $this->output_file = $which_output_file;
  2099. else
  2100. $this->output_file = NULL;
  2101. return TRUE;
  2102. }
  2103. /**
  2104. * Sets the output image to be inline, without HTTP headers
  2105. *
  2106. * This will suppress the Content-Type headers that would otherwise be sent.
  2107. *
  2108. * @param bool $which_ii True to suppress HTTP headers, False to include the headers
  2109. * @return bool True always
  2110. */
  2111. function SetIsInline($which_ii)
  2112. {
  2113. $this->is_inline = (bool)$which_ii;
  2114. return TRUE;
  2115. }
  2116. /**
  2117. * Gets the MIME type and GD output function name for the current file type
  2118. *
  2119. * @param string $mime_type Reference variable where the MIME type is returned
  2120. * @param string $output_f Reference variable where the GD output function name is returned
  2121. * @return bool True (False on error if an error handler returns True)
  2122. * @since 5.5.0
  2123. */
  2124. protected function GetImageType(&$mime_type, &$output_f)
  2125. {
  2126. switch ($this->file_format) {
  2127. case 'png':
  2128. $mime_type = 'image/png';
  2129. $output_f = 'imagepng';
  2130. break;
  2131. case 'jpg':
  2132. $mime_type = 'image/jpeg';
  2133. $output_f = 'imagejpeg';
  2134. break;
  2135. case 'gif':
  2136. $mime_type = 'image/gif';
  2137. $output_f = 'imagegif';
  2138. break;
  2139. case 'wbmp':
  2140. $mime_type = 'image/wbmp';
  2141. $output_f = 'imagewbmp';
  2142. break;
  2143. default:
  2144. // Report the error on PrintImage, because that is where this code used to be.
  2145. return $this->PrintError('PrintImage(): Please select an image type!');
  2146. }
  2147. return TRUE;
  2148. }
  2149. /**
  2150. * Tells the browser not to cache the image
  2151. *
  2152. * This is used by PrintImage, depending on SetBrowserCache(). It sends
  2153. * HTTP headers that discourage browser-side caching.
  2154. * Originally submitted by Thiemo Nagel. Modified to add more options based on mjpg-streamer.
  2155. *
  2156. * @return bool True always
  2157. * @since 5.8.0
  2158. */
  2159. protected function DisableCaching()
  2160. {
  2161. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  2162. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
  2163. header('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0');
  2164. header('Pragma: no-cache');
  2165. return TRUE;
  2166. }
  2167. /**
  2168. * Outputs the generated image to standard output or to a file
  2169. *
  2170. * This is automatically called by DrawGraph(), unless SetPrintImage(False) was used.
  2171. *
  2172. * @return bool True always
  2173. */
  2174. function PrintImage()
  2175. {
  2176. if (!$this->browser_cache && !$this->is_inline)
  2177. $this->DisableCaching();
  2178. // Get MIME type and GD output function name:
  2179. if (!$this->GetImageType($mime_type, $output_f)) return FALSE;
  2180. if (!$this->is_inline) {
  2181. Header("Content-type: $mime_type");
  2182. }
  2183. if ($this->is_inline && isset($this->output_file)) {
  2184. $output_f($this->img, $this->output_file);
  2185. } else {
  2186. $output_f($this->img);
  2187. }
  2188. return TRUE;
  2189. }
  2190. /**
  2191. * Returns the image data as raw data, base64 encoded, or data URL (see RFC2397)
  2192. *
  2193. * @param string $encoding Optional encoding to use: dataurl (default) | raw | base64
  2194. * @return string Encoded image data (False on error if error handler returns True)
  2195. * @since 5.5.0
  2196. */
  2197. function EncodeImage($encoding = 'dataurl')
  2198. {
  2199. $enc = $this->CheckOption($encoding, 'dataurl, raw, base64', __FUNCTION__);
  2200. if (!$enc || !$this->GetImageType($mime_type, $output_f)) return FALSE;
  2201. ob_start();
  2202. $output_f($this->img);
  2203. switch ($enc) {
  2204. case 'raw':
  2205. return ob_get_clean();
  2206. case 'base64':
  2207. return base64_encode(ob_get_clean());
  2208. default: // 'dataurl', checked above.
  2209. return "data:$mime_type;base64,\n" . chunk_split(base64_encode(ob_get_clean()));
  2210. }
  2211. }
  2212. /**
  2213. * Draws a text message on the image, replacing the plot
  2214. *
  2215. * This is used for PHPlot error handling, and is available for
  2216. * application-level error handling or other special purposes.
  2217. * Options (keys in $options) are: draw_background draw_border force_print
  2218. * reset_font text_color text_wrap wrap_width.
  2219. * Default option values were chosen for fail-safe error-handling.
  2220. *
  2221. * @param string $text Text of the message to display in the image
  2222. * @param string[] $options Optional associative array of control options
  2223. * @return bool True always
  2224. * @since 5.7.0
  2225. */
  2226. function DrawMessage($text, $options = NULL)
  2227. {
  2228. // Merge options with defaults, and set as local variables:
  2229. extract( array_merge( array(
  2230. 'draw_background' => FALSE, // Draw image background per SetBgImage(), SetBackgroundColor()
  2231. 'draw_border' => FALSE, // Draw image border as set with SetBorder*()
  2232. 'force_print' => TRUE, // Ignore SetPrintImage() setting and always output
  2233. 'reset_font' => TRUE, // Reset fonts (to avoid possible TTF error)
  2234. 'text_color' => '', // If not empty, text color specification
  2235. 'text_wrap' => TRUE, // Wrap the message text with wordwrap()
  2236. 'wrap_width' => 75, // Width in characters for wordwrap()
  2237. ), (array)$options));
  2238. // Do colors, background, and border:
  2239. if ($draw_border && !isset($this->ndx_i_border) || $draw_background && !isset($this->ndx_bg_color))
  2240. $this->SetBgColorIndexes();
  2241. if ($draw_background) { // User-specified background
  2242. $this->DrawBackground(TRUE); // TRUE means force overwriting of background
  2243. } else { // Default to plain white background
  2244. $bgcolor = imagecolorresolve($this->img, 255, 255, 255);
  2245. ImageFilledRectangle($this->img, 0, 0, $this->image_width, $this->image_height, $bgcolor);
  2246. }
  2247. if ($draw_border) $this->DrawImageBorder(TRUE);
  2248. if (empty($text_color)) $rgb = array(0, 0, 0);
  2249. else $rgb = $this->SetRGBColor($text_color);
  2250. $ndx_text_color = imagecolorresolve($this->img, $rgb[0], $rgb[1], $rgb[2]);
  2251. // Error images should reset fonts, to avoid chance of a TTF error when displaying an error.
  2252. if ($reset_font) $this->SetUseTTF(FALSE);
  2253. // Determine the space needed for the text, and center the text box within the image:
  2254. if ($text_wrap) $text = wordwrap($text, $wrap_width);
  2255. list($text_width, $text_height) = $this->SizeText('generic', 0, $text);
  2256. $x = max($this->safe_margin, ($this->image_width - $text_width) / 2);
  2257. $y = max($this->safe_margin, ($this->image_height - $text_height) / 2);
  2258. $this->DrawText('generic', 0, $x, $y, $ndx_text_color, $text, 'left', 'top');
  2259. if ($force_print || $this->print_image) $this->PrintImage();
  2260. return TRUE;
  2261. }
  2262. /**
  2263. * Handles a fatal error in PHPlot
  2264. *
  2265. * When a fatal error occurs (most often a parameter error in a function call),
  2266. * PHPlot will normally produce an image containing the error message,
  2267. * output the image, and then trigger a user-level error with the message.
  2268. * (The error message has to be presented as an image, because the browser is
  2269. * expecting an image.)
  2270. * If no error handler is set up, PHP will log the message and exit.
  2271. * If there is an error handler, and it returns TRUE, PrintError returns FALSE,
  2272. * and this will be passed back up to the calling code as a FALSE return.
  2273. *
  2274. * @param string $error_message Text of the error message
  2275. * @return bool False, but only if there is an error handler that returned TRUE.
  2276. */
  2277. protected function PrintError($error_message)
  2278. {
  2279. // Be sure not to loop recursively, e.g. PrintError - PrintImage - PrintError.
  2280. if (isset($this->in_error)) return FALSE;
  2281. $this->in_error = TRUE;
  2282. // Output an image containing the error message:
  2283. if (!$this->suppress_error_image) {
  2284. // img will be empty if the error occurs very early - e.g. when allocating the image.
  2285. if (!empty($this->img)) {
  2286. $this->DrawMessage($error_message);
  2287. } elseif (!$this->is_inline) {
  2288. Header('HTTP/1.0 500 Internal Server Error');
  2289. }
  2290. }
  2291. trigger_error($error_message, E_USER_ERROR);
  2292. // This is only reached if the error handler returns TRUE
  2293. unset($this->in_error);
  2294. return FALSE;
  2295. }
  2296. /**
  2297. * Enables or disables error image production on failure
  2298. *
  2299. * @param bool $error_image True to enable the error image, False to disable it.
  2300. * @return bool True always
  2301. * @since 5.5.0
  2302. */
  2303. function SetFailureImage($error_image)
  2304. {
  2305. $this->suppress_error_image = !$error_image;
  2306. return TRUE;
  2307. }
  2308. /**
  2309. * Begins a Motion-JPEG (or other type) plot stream
  2310. *
  2311. * @return bool True always
  2312. * @since 5.8.0
  2313. */
  2314. function StartStream()
  2315. {
  2316. $this->GetImageType($mime_type, $this->stream_output_f);
  2317. $this->stream_boundary = "PHPlot-Streaming-Frame"; // Arbitrary MIME boundary
  2318. $this->stream_frame_header = "\r\n--$this->stream_boundary\r\nContent-Type: $mime_type\r\n";
  2319. $this->DisableCaching(); // Send headers to disable browser-side caching
  2320. header("Content-type: multipart/x-mixed-replace; boundary=\"$this->stream_boundary\"");
  2321. return TRUE;
  2322. }
  2323. /**
  2324. * Ends a Motion-JPEG (or other type) plot stream
  2325. *
  2326. * @return bool True always
  2327. * @since 5.8.0
  2328. */
  2329. function EndStream()
  2330. {
  2331. echo "\r\n--$this->stream_boundary--\r\n";
  2332. flush();
  2333. return TRUE;
  2334. }
  2335. /**
  2336. * Outputs the generated plot as one frame in a plot stream
  2337. *
  2338. * @return bool True always
  2339. * @since 5.8.0
  2340. */
  2341. function PrintImageFrame()
  2342. {
  2343. ob_start();
  2344. call_user_func($this->stream_output_f, $this->img);
  2345. $size = ob_get_length();
  2346. $frame = ob_get_clean();
  2347. echo $this->stream_frame_header, "Content-Length: $size\r\n\r\n", $frame, "\r\n";
  2348. flush();
  2349. // This gets the next DrawGraph() to do background and titles again.
  2350. $this->done = array();
  2351. return TRUE;
  2352. }
  2353. /////////////////////////////////////////////
  2354. /////////// LABELS
  2355. /////////////////////////////////////////////
  2356. /**
  2357. * Positions and controls X data labels
  2358. *
  2359. * For vertical plots, these are X axis data labels, showing label strings from the data array.
  2360. * Accepted positions are: plotdown, plotup, both, none.
  2361. * For horizontal plots, these are X data value labels, show the data values.
  2362. * Accepted positions are: plotin, plotstack, none.
  2363. *
  2364. * @param string $which_xdlp Desired label position: plotdown | plotup | both | none | plotin | plotstack
  2365. * @return bool True (False on error if an error handler returns True)
  2366. */
  2367. function SetXDataLabelPos($which_xdlp)
  2368. {
  2369. $which_xdlp = $this->CheckOption($which_xdlp, 'plotdown, plotup, both, none, plotin, plotstack',
  2370. __FUNCTION__);
  2371. if (!$which_xdlp) return FALSE;
  2372. $this->x_data_label_pos = $which_xdlp;
  2373. return TRUE;
  2374. }
  2375. /**
  2376. * Positions and controls Y data labels
  2377. *
  2378. * For vertical plots, these are Y data value labels, showing the data values.
  2379. * Accepted positions are: plotin, plotstack, none.
  2380. * For horizontal plots, these are Y axis data labels, showing label strings from the data array.
  2381. * Accepted positions are: plotleft, plotright, both, none.
  2382. *
  2383. * @param string $which_ydlp Desired label position: plotleft | plotright | both | none | ...
  2384. * @return bool True (False on error if an error handler returns True)
  2385. */
  2386. function SetYDataLabelPos($which_ydlp)
  2387. {
  2388. $which_ydlp = $this->CheckOption($which_ydlp, 'plotleft, plotright, both, none, plotin, plotstack',
  2389. __FUNCTION__);
  2390. if (!$which_ydlp) return FALSE;
  2391. $this->y_data_label_pos = $which_ydlp;
  2392. return TRUE;
  2393. }
  2394. /**
  2395. * Positions the X tick labels
  2396. *
  2397. * @param string $which_xtlp Desired label position: plotdown | plotup | both | none | xaxis
  2398. * @return bool True (False on error if an error handler returns True)
  2399. */
  2400. function SetXTickLabelPos($which_xtlp)
  2401. {
  2402. $which_xtlp = $this->CheckOption($which_xtlp, 'plotdown, plotup, both, xaxis, none',
  2403. __FUNCTION__);
  2404. if (!$which_xtlp) return FALSE;
  2405. $this->x_tick_label_pos = $which_xtlp;
  2406. return TRUE;
  2407. }
  2408. /**
  2409. * Positions the Y tick labels
  2410. *
  2411. * @param string $which_ytlp Desired label position: plotleft | plotright | both | none | yaxis
  2412. * @return bool True (False on error if an error handler returns True)
  2413. */
  2414. function SetYTickLabelPos($which_ytlp)
  2415. {
  2416. $which_ytlp = $this->CheckOption($which_ytlp, 'plotleft, plotright, both, yaxis, none',
  2417. __FUNCTION__);
  2418. if (!$which_ytlp) return FALSE;
  2419. $this->y_tick_label_pos = $which_ytlp;
  2420. return TRUE;
  2421. }
  2422. /**
  2423. * Sets the formatting type for tick, data, or pie chart labels
  2424. *
  2425. * This implements SetXLabelType(), SetYLabelType(), SetXYDataLabelType(), SetYDataLabelType(),
  2426. * and part of SetPieLabelType(). Those functions combine their arguments into an array and
  2427. * pass the array to this function as $args.
  2428. *
  2429. * $mode='x' or 'y' set the type for tick labels, and the default type for data labels
  2430. * if they are not separately configured. $mode='xd' or 'yd' set the type for data labels.
  2431. * $mode='p' sets the type for pie chart labels.
  2432. *
  2433. * $args[0] sets the formatting type: 'data' | 'time' | 'printf' | 'custom' | empty.
  2434. * If this is missing or empty, the default formatting for $mode is restored.
  2435. * Additional values in $args[] depend on the formatting type. All further paramters except
  2436. * for the callback are optional.
  2437. * For type='data': $args[1] = precision, $args[2] = prefix, $args[3] = suffix.
  2438. * For type 'time': $args[1] = format string for strftime().
  2439. * For type 'printf': $args[1:3] = 1, 2, or 3 format strings for sprintf().
  2440. * For type 'custom': $args[1] = the callback (required), $args[2] = pass-through argument.
  2441. *
  2442. * @param string $mode Which label type to configure: x | y | xd | yd | p
  2443. * @param array $args Additional arguments controlling the format type
  2444. * @return bool True (False on error if an error handler returns True)
  2445. */
  2446. protected function SetLabelType($mode, $args)
  2447. {
  2448. if (!$this->CheckOption($mode, 'x, y, xd, yd, p', __FUNCTION__))
  2449. return FALSE;
  2450. $type = isset($args[0]) ? $args[0] : '';
  2451. $format = &$this->label_format[$mode]; // Shorthand reference to format storage variables
  2452. switch ($type) {
  2453. case 'data':
  2454. if (isset($args[1]))
  2455. $format['precision'] = $args[1];
  2456. elseif (!isset($format['precision']))
  2457. $format['precision'] = 1;
  2458. $format['prefix'] = isset($args[2]) ? $args[2] : '';
  2459. $format['suffix'] = isset($args[3]) ? $args[3] : '';
  2460. break;
  2461. case 'time':
  2462. if (isset($args[1]))
  2463. $format['time_format'] = $args[1];
  2464. elseif (!isset($format['time_format']))
  2465. $format['time_format'] = '%H:%M:%S';
  2466. break;
  2467. case 'printf':
  2468. if (isset($args[1]))
  2469. // Accept 1, 2, or 3 format strings (see FormatLabel)
  2470. $format['printf_format'] = array_slice($args, 1, 3);
  2471. elseif (!isset($format['printf_format']))
  2472. $format['printf_format'] = '%e';
  2473. break;
  2474. case 'custom':
  2475. if (isset($args[1])) {
  2476. $format['custom_callback'] = $args[1];
  2477. $format['custom_arg'] = isset($args[2]) ? $args[2] : NULL;
  2478. } else {
  2479. $type = ''; // Error, 'custom' without a function, set to no-format mode.
  2480. }
  2481. break;
  2482. case '':
  2483. case 'title': // Retained for backwards compatibility?
  2484. break;
  2485. default:
  2486. $this->CheckOption($type, 'data, time, printf, custom', __FUNCTION__);
  2487. $type = '';
  2488. }
  2489. $format['type'] = $type;
  2490. return (boolean)$type;
  2491. }
  2492. /**
  2493. * Sets formatting mode for X tick labels, and default for X data labels
  2494. *
  2495. * @param string $type Formatting mode: data | time | printf | custom, or '' to reset to default
  2496. * @param mixed $varargs One or more additional arguments that depend on $type
  2497. * @return bool True (False on error if an error handler returns True)
  2498. */
  2499. function SetXLabelType($type=NULL, $varargs=NULL) // Variable arguments
  2500. {
  2501. $args = func_get_args();
  2502. return $this->SetLabelType('x', $args);
  2503. }
  2504. /**
  2505. * Sets formatting mode for X data labels (overriding any mode set with SetXLabelType)
  2506. *
  2507. * @param string $type Formatting mode: data | time | printf | custom, or '' to reset to default
  2508. * @param mixed $varargs One or more additional arguments that depend on $type
  2509. * @return bool True (False on error if an error handler returns True)
  2510. * @since 5.1.0
  2511. */
  2512. function SetXDataLabelType($type=NULL, $varargs=NULL) // Variable arguments, named params are unused
  2513. {
  2514. $args = func_get_args();
  2515. return $this->SetLabelType('xd', $args);
  2516. }
  2517. /**
  2518. * Sets formatting mode for Y tick labels, and default for Y data labels
  2519. *
  2520. * @param string $type Formatting mode: data | time | printf | custom, or '' to reset to default
  2521. * @param mixed $varargs One or more additional arguments that depend on $type
  2522. * @return bool True (False on error if an error handler returns True)
  2523. */
  2524. function SetYLabelType($type=NULL, $varargs=NULL) // Variable arguments, named params are unused
  2525. {
  2526. $args = func_get_args();
  2527. return $this->SetLabelType('y', $args);
  2528. }
  2529. /**
  2530. * Sets formatting mode for Y data labels (overriding any mode set with SetYLabelType)
  2531. *
  2532. * @param string $type Formatting mode: data | time | printf | custom, or '' to reset to default
  2533. * @param mixed $varargs One or more additional arguments that depend on $type
  2534. * @return bool True (False on error if an error handler returns True)
  2535. * @since 5.1.0
  2536. */
  2537. function SetYDataLabelType($type=NULL, $varargs=NULL) // Variable arguments, named params are unused
  2538. {
  2539. $args = func_get_args();
  2540. return $this->SetLabelType('yd', $args);
  2541. }
  2542. /**
  2543. * Sets type and formatting mode for pie chart labels.
  2544. *
  2545. * @param string|string[] $source_ Label source keyword or array: percent | value | label | index | ''
  2546. * @param string $type Optional formatting mode: data | printf | custom
  2547. * @param mixed $varargs Zero or more additional arguments telling how to format the label
  2548. * @return bool True (False on error if an error handler returns True)
  2549. * @since 5.6.0
  2550. */
  2551. function SetPieLabelType($source_, $type=NULL, $varargs=NULL) // Variable arguments, named params unused
  2552. {
  2553. $args = func_get_args();
  2554. $source = array_shift($args);
  2555. if (empty($source)) {
  2556. $this->pie_label_source = NULL; // Restore default
  2557. $args = array(''); // See below - tells SetLabelType to do no formatting or default.
  2558. } else {
  2559. $this->pie_label_source = $this->CheckOptionArray($source, 'percent, value, label, index',
  2560. __FUNCTION__);
  2561. if (empty($this->pie_label_source)) return FALSE;
  2562. }
  2563. return $this->SetLabelType('p', $args);
  2564. }
  2565. /**
  2566. * Sets the date/time formatting string for X labels
  2567. *
  2568. * This does not enable date/time formatting. For that you need to use
  2569. * SetXLabelType('time'). But since you can pass the formatting string
  2570. * to SetXLabelType() also, there is no need to use SetXTimeFormat().
  2571. *
  2572. * @param string $which_xtf Formatting string to use (see PHP function strftime())
  2573. * @return bool True always
  2574. */
  2575. function SetXTimeFormat($which_xtf)
  2576. {
  2577. $this->label_format['x']['time_format'] = $which_xtf;
  2578. return TRUE;
  2579. }
  2580. /**
  2581. * Sets the date/time formatting string for Y labels
  2582. *
  2583. * This does not enable date/time formatting. For that you need to use
  2584. * SetYLabelType('time'). But since you can pass the formatting string
  2585. * to SetYLabelType() also, there is no need to use SetYTimeFormat().
  2586. *
  2587. * @param string $which_ytf Formatting string (see PHP function strftime())
  2588. * @return bool True always
  2589. */
  2590. function SetYTimeFormat($which_ytf)
  2591. {
  2592. $this->label_format['y']['time_format'] = $which_ytf;
  2593. return TRUE;
  2594. }
  2595. /**
  2596. * Sets the separators used when formatting number labels
  2597. *
  2598. * Separators are used with 'data' label formatting. The defaults
  2599. * are set from the system locale (if available).
  2600. *
  2601. * @param string $decimal_point The character to use as a decimal point
  2602. * @param string $thousands_sep The character to use as a thousands grouping separator
  2603. * @return bool True always
  2604. * @since 5.0.4
  2605. */
  2606. function SetNumberFormat($decimal_point, $thousands_sep)
  2607. {
  2608. $this->decimal_point = $decimal_point;
  2609. $this->thousands_sep = $thousands_sep;
  2610. return TRUE;
  2611. }
  2612. /**
  2613. * Sets the text angle for X tick labels, and the default angle for X data labels
  2614. *
  2615. * @param float $which_xla Desired angle for label text, in degrees
  2616. * @return bool True always
  2617. */
  2618. function SetXLabelAngle($which_xla)
  2619. {
  2620. $this->x_label_angle = $which_xla;
  2621. return TRUE;
  2622. }
  2623. /**
  2624. * Sets the text angle for Y tick labels
  2625. *
  2626. * Note: Unlike SetXLabelAngle(), this does not also apply to data labels.
  2627. *
  2628. * @param float $which_yla Desired angle for label text, in degrees
  2629. * @return bool True always
  2630. */
  2631. function SetYLabelAngle($which_yla)
  2632. {
  2633. $this->y_label_angle = $which_yla;
  2634. return TRUE;
  2635. }
  2636. /**
  2637. * Sets the text angle for X data labels (overriding an angle set with SetXLabelAngle)
  2638. *
  2639. * @param float $which_xdla Desired angle for label text, in degrees
  2640. * @return bool True always
  2641. * @since 5.1.0
  2642. */
  2643. function SetXDataLabelAngle($which_xdla)
  2644. {
  2645. $this->x_data_label_angle_u = $which_xdla;
  2646. return TRUE;
  2647. }
  2648. /**
  2649. * Sets the angle for Y data labels
  2650. *
  2651. * @param float $which_ydla Desired angle for label text, in degrees
  2652. * @return bool True always
  2653. * @since 5.1.0
  2654. */
  2655. function SetYDataLabelAngle($which_ydla)
  2656. {
  2657. $this->y_data_label_angle = $which_ydla;
  2658. return TRUE;
  2659. }
  2660. /////////////////////////////////////////////
  2661. /////////// MISC
  2662. /////////////////////////////////////////////
  2663. /**
  2664. * Checks the validity of an option (a multiple-choice function parameter)
  2665. *
  2666. * @param string $which_opt String to check, usually the provided value of a function argument
  2667. * @param string $which_acc String of accepted choices, lower-case, choices separated by comma space
  2668. * @param string $which_func Name of the calling function, for error messages, usually __FUNCTION__
  2669. * @return string|null Downcased/trimmed option value if valid; NULL on error if error handler returns
  2670. */
  2671. protected function CheckOption($which_opt, $which_acc, $which_func)
  2672. {
  2673. $asked = strtolower(trim($which_opt));
  2674. // Look for the supplied value in a comma/space separated list.
  2675. if (strpos(", $which_acc,", ", $asked,") !== FALSE)
  2676. return $asked;
  2677. $this->PrintError("$which_func(): '$which_opt' not in available choices: '$which_acc'.");
  2678. return NULL;
  2679. }
  2680. /**
  2681. * Checks the validity of an array of options (multiple-choice function parameters)
  2682. *
  2683. * This is used to validate arguments to functions that accept either a single value
  2684. * or an array of values (example: SetPlotBorderType).
  2685. *
  2686. * @param string|string[] $opt String or array of strings to check
  2687. * @param string $acc String of accepted choices, lower-case, choices separated by comma space
  2688. * @param string $func Name of the calling function, for error messages, usually __FUNCTION__
  2689. * @return string[]|null Downcased/trimmed option values if valid; NULL on error if error handler returns
  2690. * @since 5.1.2
  2691. */
  2692. protected function CheckOptionArray($opt, $acc, $func)
  2693. {
  2694. $opt_array = (array)$opt;
  2695. $result = array();
  2696. foreach ($opt_array as $option) {
  2697. $choice = $this->CheckOption($option, $acc, $func);
  2698. if (is_null($choice)) return NULL; // In case CheckOption error handler returns
  2699. $result[] = $choice;
  2700. }
  2701. return $result;
  2702. }
  2703. /**
  2704. * Checks for compatibility of the plot type and data type
  2705. *
  2706. * This is called by the plot-type-specific drawing functions, such as DrawBars().
  2707. * It checks to make sure that the current data type is supported by the
  2708. * drawing function.
  2709. *
  2710. * @param string $valid_types Valid data types, separated by comma space
  2711. * @return bool True if data type is valid; False on error if an error handler returns True
  2712. * @since 5.1.2
  2713. */
  2714. protected function CheckDataType($valid_types)
  2715. {
  2716. if (strpos(", $valid_types,", ", $this->data_type,") !== FALSE)
  2717. return TRUE;
  2718. $this->PrintError("Data type '$this->data_type' is not valid for '$this->plot_type' plots."
  2719. . " Supported data type(s): '$valid_types'");
  2720. return FALSE;
  2721. }
  2722. /**
  2723. * Decodes the data type into variables used to determine how to process a data array
  2724. *
  2725. * This sets the 'datetype_*' class variables, which are used by other functions
  2726. * that need to access the data array. This keeps the information about the meaning
  2727. * of each data type in a single place (the datatypes static array).
  2728. * @since 5.1.2
  2729. */
  2730. protected function DecodeDataType()
  2731. {
  2732. $v = &self::$datatypes[$this->data_type]; // Shortcut reference, already validated in SetDataType()
  2733. $this->datatype_implied = !empty($v['implied']); // X (Y for horizontal plots) is implied
  2734. $this->datatype_error_bars = !empty($v['error_bars']); // Has +error, -error values
  2735. $this->datatype_pie_single = !empty($v['pie_single']); // Single-row pie chart
  2736. $this->datatype_swapped_xy = !empty($v['swapped_xy']); // Horizontal plot with swapped X:Y
  2737. $this->datatype_yz = !empty($v['yz']); // Has a Z value for each Y
  2738. }
  2739. /**
  2740. * Validates the data array, making sure it is properly structured
  2741. *
  2742. * This function is used by DrawGraph() to make sure the data array is populated
  2743. * and each row is structured correctly, according to the data type.
  2744. *
  2745. * It also calculates data_columns, which is the maximum number of dependent
  2746. * variable values (usually Y) in the data array rows. (For pie charts, this is
  2747. * the number of slices.) It depends on the data_type, unlike records_per_group
  2748. * (which was previously used to pad style arrays, but is not accurate).
  2749. *
  2750. * Note error messages refer to the caller, the public DrawGraph().
  2751. *
  2752. * @return bool True (False on error if an error handler returns True)
  2753. * @since 5.1.3
  2754. */
  2755. protected function CheckDataArray()
  2756. {
  2757. // Test for missing image, which really should never happen.
  2758. if (!$this->img) {
  2759. return $this->PrintError('DrawGraph(): No image resource allocated');
  2760. }
  2761. // Test for missing or empty data array:
  2762. if (empty($this->data) || !is_array($this->data)) {
  2763. return $this->PrintError("DrawGraph(): No data array");
  2764. }
  2765. if ($this->total_records == 0) {
  2766. return $this->PrintError('DrawGraph(): Empty data set');
  2767. }
  2768. // Decode the data type into functional flags.
  2769. $this->DecodeDataType();
  2770. // Calculate the maximum number of dependent values per independent value
  2771. // (e.g. Y for each X), or the number of pie slices. Also validate the rows.
  2772. $skip = $this->datatype_implied ? 1 : 2; // Skip factor for data label and independent variable
  2773. if ($this->datatype_error_bars) {
  2774. $this->data_columns = (int)(($this->records_per_group - $skip) / 3);
  2775. // Validate the data array for error plots: (label, X, then groups of Y, +err, -err):
  2776. for ($i = 0; $i < $this->num_data_rows; $i++) {
  2777. if ($this->num_recs[$i] < $skip || ($this->num_recs[$i] - $skip) % 3 != 0)
  2778. return $this->PrintError("DrawGraph(): Invalid $this->data_type data array (row $i)");
  2779. }
  2780. } elseif ($this->datatype_pie_single) {
  2781. $this->data_columns = $this->num_data_rows; // Special case for this type of pie chart.
  2782. // Validate the data array for text-data-single pie charts. Requires 1 value per row.
  2783. for ($i = 0; $i < $this->num_data_rows; $i++) {
  2784. if ($this->num_recs[$i] != 2)
  2785. return $this->PrintError("DrawGraph(): Invalid $this->data_type data array (row $i)");
  2786. }
  2787. } elseif ($this->datatype_yz) {
  2788. $this->data_columns = (int)(($this->records_per_group - $skip) / 2); // (y, z) pairs
  2789. // Validate the data array for plots using X, Y, Z: (label, X, then pairs of Y, Z)
  2790. for ($i = 0; $i < $this->num_data_rows; $i++) {
  2791. if ($this->num_recs[$i] < $skip || ($this->num_recs[$i] - $skip) % 2 != 0)
  2792. return $this->PrintError("DrawGraph(): Invalid $this->data_type data array (row $i)");
  2793. }
  2794. } else {
  2795. $this->data_columns = $this->records_per_group - $skip;
  2796. // Validate the data array for non-error plots:
  2797. for ($i = 0; $i < $this->num_data_rows; $i++) {
  2798. if ($this->num_recs[$i] < $skip)
  2799. return $this->PrintError("DrawGraph(): Invalid $this->data_type data array (row $i)");
  2800. }
  2801. }
  2802. return TRUE;
  2803. }
  2804. /**
  2805. * Controls browser-side image caching
  2806. *
  2807. * @param bool $which_browser_cache True to allow the browser to cache the image, false to not allow
  2808. * @return bool True always
  2809. */
  2810. function SetBrowserCache($which_browser_cache)
  2811. {
  2812. $this->browser_cache = $which_browser_cache;
  2813. return TRUE;
  2814. }
  2815. /**
  2816. * Determines whether or not DrawGraph() automatically outputs the image when the plot is drawn
  2817. *
  2818. * @param bool $which_pi True to have DrawGraph() call PrintImage() when done, false to not output
  2819. * @return bool True always
  2820. */
  2821. function SetPrintImage($which_pi)
  2822. {
  2823. $this->print_image = $which_pi;
  2824. return TRUE;
  2825. }
  2826. /**
  2827. * Sets how much of a border is drawn around the plot area
  2828. *
  2829. * The argument can be a single value, or any array of values, indicating
  2830. * which sides should get a border. 'full' means all 4 sides.
  2831. *
  2832. * @param string|string[] $pdt Border control keyword(s): left|right|top|bottom|sides|none|full
  2833. * @return bool True (False on error if an error handler returns True)
  2834. */
  2835. function SetPlotBorderType($pbt)
  2836. {
  2837. $this->plot_border_type = $this->CheckOptionArray($pbt, 'left, right, top, bottom, sides, none, full',
  2838. __FUNCTION__);
  2839. return !empty($this->plot_border_type);
  2840. }
  2841. /**
  2842. * Sets the type of border drawn around the image
  2843. *
  2844. * @param string $sibt Border type: raised | solid | plain | none
  2845. * @return bool True (False on error if an error handler returns True)
  2846. */
  2847. function SetImageBorderType($sibt)
  2848. {
  2849. $this->image_border_type = $this->CheckOption($sibt, 'raised, plain, solid, none', __FUNCTION__);
  2850. return (boolean)$this->image_border_type;
  2851. }
  2852. /**
  2853. * Sets the width of the image border, if enabled
  2854. *
  2855. * @param int $width Image border width in pixels
  2856. * @return bool True always
  2857. * @since 5.1.2
  2858. */
  2859. function SetImageBorderWidth($width)
  2860. {
  2861. $this->image_border_width = $width;
  2862. return TRUE;
  2863. }
  2864. /**
  2865. * Enables or disables drawing of the plot area background color
  2866. *
  2867. * @param bool $dpab True to draw the plot area background color, false to not draw it
  2868. * @return bool True always
  2869. */
  2870. function SetDrawPlotAreaBackground($dpab)
  2871. {
  2872. $this->draw_plot_area_background = (bool)$dpab;
  2873. return TRUE;
  2874. }
  2875. /**
  2876. * Enables or disables drawing of the X (vertical) grid lines
  2877. *
  2878. * @param bool $dxg True to draw the X grid lines, false to not draw them; or NULL to restore default
  2879. * @return bool True always
  2880. */
  2881. function SetDrawXGrid($dxg = NULL)
  2882. {
  2883. $this->draw_x_grid = $dxg;
  2884. return TRUE;
  2885. }
  2886. /**
  2887. * Enables or disables drawing of the Y grid lines
  2888. *
  2889. * @param bool $dyg True to draw the Y grid lines, false to not draw them; or NULL to restore default
  2890. * @return bool True always
  2891. */
  2892. function SetDrawYGrid($dyg = NULL)
  2893. {
  2894. $this->draw_y_grid = $dyg;
  2895. return TRUE;
  2896. }
  2897. /**
  2898. * Selects dashed or solid grid lines
  2899. *
  2900. * @param bool $ddg True to draw the grid with dashed lines, false to use solid lines
  2901. * @return bool True always
  2902. */
  2903. function SetDrawDashedGrid($ddg)
  2904. {
  2905. $this->dashed_grid = (bool)$ddg;
  2906. return TRUE;
  2907. }
  2908. /**
  2909. * Enables or disables drawing of X data label lines
  2910. *
  2911. * @param bool $dxdl True to draw the X data label lines, false to not draw them
  2912. * @return bool True always
  2913. */
  2914. function SetDrawXDataLabelLines($dxdl)
  2915. {
  2916. $this->draw_x_data_label_lines = (bool)$dxdl;
  2917. return TRUE;
  2918. }
  2919. /**
  2920. * Enables or disables drawing of Y data label Lines (horizontal plots only)
  2921. *
  2922. * @param bool $dydl True to draw the Y data label lines, false to not draw them
  2923. * @return bool True always
  2924. * @since 6.0.0
  2925. */
  2926. function SetDrawYDataLabelLines($dydl)
  2927. {
  2928. $this->draw_y_data_label_lines = (bool)$dydl;
  2929. return TRUE;
  2930. }
  2931. /**
  2932. * Enables or disables drawing of borders around pie chart segments
  2933. *
  2934. * @param bool $dpb True to draw the pie chart segment borders, false to not draw them
  2935. * @return bool True always
  2936. * @since 6.0.0
  2937. */
  2938. function SetDrawPieBorders($dpb)
  2939. {
  2940. $this->draw_pie_borders = (bool)$dpb;
  2941. return TRUE;
  2942. }
  2943. /**
  2944. * Enables or disables drawing of data borders for plot types that support them
  2945. *
  2946. * For plot types which support data borders, such as 'bars', this enables
  2947. * or disables them. The default depends on the plot type.
  2948. *
  2949. * @param bool $ddb True to draw the data borders, false to not draw them
  2950. * @return bool True always
  2951. * @since 6.0.0
  2952. */
  2953. function SetDrawDataBorders($ddb)
  2954. {
  2955. $this->draw_data_borders = (bool)$ddb;
  2956. return TRUE;
  2957. }
  2958. /**
  2959. * Sets the main title text for the plot
  2960. *
  2961. * @param string $which_title The text to use for the main plot title. Can contain multiple lines
  2962. * @return bool True always
  2963. */
  2964. function SetTitle($which_title)
  2965. {
  2966. $this->title_txt = $which_title;
  2967. return TRUE;
  2968. }
  2969. /**
  2970. * Sets the X axis title, and optionally its position
  2971. *
  2972. * Sets the text to be displayed as the X axis title. Optionally, it
  2973. * also sets the position of the title and the axis itself: below the
  2974. * graph (the usual place), above the graph, both, or neither.
  2975. *
  2976. * @param string $which_xtitle The text string to use for the X axis title. Can contain multiple lines
  2977. * @param string $which_xpos Optional position for the X axis and title: plotdown plotup both none
  2978. * @return bool True (False on error if an error handler returns True)
  2979. */
  2980. function SetXTitle($which_xtitle, $which_xpos = 'plotdown')
  2981. {
  2982. if (!($which_xpos = $this->CheckOption($which_xpos, 'plotdown, plotup, both, none', __FUNCTION__)))
  2983. return FALSE;
  2984. if (($this->x_title_txt = $which_xtitle) === '')
  2985. $this->x_title_pos = 'none';
  2986. else
  2987. $this->x_title_pos = $which_xpos;
  2988. return TRUE;
  2989. }
  2990. /**
  2991. * Sets the Y axis title, and optionally its position
  2992. *
  2993. * Sets the text to be displayed as the Y axis title. Optionally, it
  2994. * also sets the position of the title and the axis itself: on the left
  2995. * side of the graph (the usual place), on the right side, both, or neither.
  2996. *
  2997. * @param string $which_ytitle The text string to use for the Y axis title. Can contain multiple lines
  2998. * @param string $which_ypos Optional position for the X axis and title: plotleft plotright both none
  2999. * @return bool True (False on error if an error handler returns True)
  3000. */
  3001. function SetYTitle($which_ytitle, $which_ypos = 'plotleft')
  3002. {
  3003. if (!($which_ypos = $this->CheckOption($which_ypos, 'plotleft, plotright, both, none', __FUNCTION__)))
  3004. return FALSE;
  3005. if (($this->y_title_txt = $which_ytitle) === '')
  3006. $this->y_title_pos = 'none';
  3007. else
  3008. $this->y_title_pos = $which_ypos;
  3009. return TRUE;
  3010. }
  3011. /**
  3012. * Sets the size of the drop shadow for bar and pie charts
  3013. *
  3014. * Sets the size in pixels of the drop shadow used to give bar and pie
  3015. * charts a 3-D look. The 3-D look can be disabled by setting the shading
  3016. * to zero.
  3017. *
  3018. * @param int $which_s Size of the drop shadow in pixels
  3019. * @return bool True always
  3020. */
  3021. function SetShading($which_s)
  3022. {
  3023. $this->shading = (int)$which_s;
  3024. return TRUE;
  3025. }
  3026. /**
  3027. * Selects the type of plot - how the data will be graphed
  3028. *
  3029. * @param string $which_pt The plot type, such as bars, lines, pie, ...
  3030. * @return bool True (False on error if an error handler returns True)
  3031. */
  3032. function SetPlotType($which_pt)
  3033. {
  3034. $avail_plot_types = implode(', ', array_keys(self::$plots)); // List of known plot types
  3035. $this->plot_type = $this->CheckOption($which_pt, $avail_plot_types, __FUNCTION__);
  3036. return (boolean)$this->plot_type;
  3037. }
  3038. /**
  3039. * Sets the position of the X axis
  3040. *
  3041. * @param float $pos Axis position as an integer Y world coordinate; '' or omit for default
  3042. * @return bool True always
  3043. */
  3044. function SetXAxisPosition($pos='')
  3045. {
  3046. $this->x_axis_position = ($pos === '') ? NULL : (int)$pos;
  3047. return TRUE;
  3048. }
  3049. /**
  3050. * Sets the position of the Y axis
  3051. *
  3052. * @param float $pos Axis position as an integer X world coordinate; '' or omit for default
  3053. * @return bool True always
  3054. */
  3055. function SetYAxisPosition($pos='')
  3056. {
  3057. $this->y_axis_position = ($pos === '') ? NULL : (int)$pos;
  3058. return TRUE;
  3059. }
  3060. /**
  3061. * Enables or disables drawing of the X axis line
  3062. *
  3063. * Note: This controls drawing of the axis line only, and not the ticks, labels, or grid.
  3064. *
  3065. * @param bool $draw True to draw the axis line, False to not draw it
  3066. * @return bool True always
  3067. * @since 5.3.0
  3068. */
  3069. function SetDrawXAxis($draw)
  3070. {
  3071. $this->suppress_x_axis = !$draw; // See DrawXAxis()
  3072. return TRUE;
  3073. }
  3074. /**
  3075. * Enables or disables drawing of the Y axis line
  3076. *
  3077. * Note: This controls drawing of the axis line only, and not the ticks, labels, or grid.
  3078. *
  3079. * @param bool $draw True to draw the axis line, False to not draw it
  3080. * @return bool True always
  3081. * @since 5.3.0
  3082. */
  3083. function SetDrawYAxis($draw)
  3084. {
  3085. $this->suppress_y_axis = !$draw; // See DrawYAxis()
  3086. return TRUE;
  3087. }
  3088. /**
  3089. * Selects linear or logarithmic scale for the X axis
  3090. *
  3091. * @param string $which_xst The scale type: linear | log
  3092. * @return bool True (False on error if an error handler returns True)
  3093. */
  3094. function SetXScaleType($which_xst)
  3095. {
  3096. $this->xscale_type = $this->CheckOption($which_xst, 'linear, log', __FUNCTION__);
  3097. return (boolean)$this->xscale_type;
  3098. }
  3099. /**
  3100. * Selects linear or logarithmic scale for the Y axis
  3101. *
  3102. * @param string $which_yst The scale type: linear | log
  3103. * @return bool True (False on error if an error handler returns True)
  3104. */
  3105. function SetYScaleType($which_yst)
  3106. {
  3107. $this->yscale_type = $this->CheckOption($which_yst, 'linear, log', __FUNCTION__);
  3108. return (boolean)$this->yscale_type;
  3109. }
  3110. /**
  3111. * Sets the precision for numerically formatted X labels
  3112. *
  3113. * Note: Use of the equivalent SetXLabelType('data', $which_prec) is preferred.
  3114. *
  3115. * @param int $which_prec Number of digits to display
  3116. * @return bool True (False on error if an error handler returns True)
  3117. */
  3118. function SetPrecisionX($which_prec)
  3119. {
  3120. return $this->SetXLabelType('data', $which_prec);
  3121. }
  3122. /**
  3123. * Sets the precision for numerically formatted Y labels
  3124. *
  3125. * Note: Use of the equivalent SetYLabelType('data', $which_prec) is preferred.
  3126. *
  3127. * @param int $which_prec Number of digits to display
  3128. * @return bool True (False on error if an error handler returns True)
  3129. */
  3130. function SetPrecisionY($which_prec)
  3131. {
  3132. return $this->SetYLabelType('data', $which_prec);
  3133. }
  3134. /**
  3135. * Sets the line width used for error bars
  3136. *
  3137. * @param int $which_seblw Desired width in pixels of the lines used to draw error bars
  3138. * @return bool True always
  3139. */
  3140. function SetErrorBarLineWidth($which_seblw)
  3141. {
  3142. $this->error_bar_line_width = $which_seblw;
  3143. return TRUE;
  3144. }
  3145. /**
  3146. * Sets the position for pie chart labels
  3147. *
  3148. * @param float $which_blp Label position factor (0 <= blp <= 1); 0 or False for no labels
  3149. * @return bool True always
  3150. */
  3151. function SetLabelScalePosition($which_blp)
  3152. {
  3153. $this->label_scale_position = $which_blp;
  3154. return TRUE;
  3155. }
  3156. /**
  3157. * Sets the size of the error bar tee
  3158. *
  3159. * @param int $which_ebs Length in pixels of the error bar "T"
  3160. * @return bool True always
  3161. */
  3162. function SetErrorBarSize($which_ebs)
  3163. {
  3164. $this->error_bar_size = $which_ebs;
  3165. return TRUE;
  3166. }
  3167. /**
  3168. * Selects the shape of the error bars
  3169. *
  3170. * @param string $which_ebs Error bar shape: tee | line
  3171. * @return bool True (False on error if an error handler returns True)
  3172. */
  3173. function SetErrorBarShape($which_ebs)
  3174. {
  3175. $this->error_bar_shape = $this->CheckOption($which_ebs, 'tee, line', __FUNCTION__);
  3176. return (boolean)$this->error_bar_shape;
  3177. }
  3178. /**
  3179. * Synchronizes the lengths of the point shapes and point sizes arrays
  3180. *
  3181. * This pads the smaller of $point_shapes[] and $point_sizes[], making them the same size.
  3182. * It is called just before drawing any plot that needs 'points'.
  3183. * @since 5.1.0
  3184. */
  3185. protected function CheckPointParams()
  3186. {
  3187. $ps = count($this->point_sizes);
  3188. $pt = count($this->point_shapes);
  3189. if ($ps < $pt) {
  3190. $this->pad_array($this->point_sizes, $pt);
  3191. $this->point_counts = $pt;
  3192. } elseif ($ps > $pt) {
  3193. $this->pad_array($this->point_shapes, $ps);
  3194. $this->point_counts = $ps;
  3195. } else {
  3196. $this->point_counts = $ps;
  3197. }
  3198. }
  3199. /**
  3200. * Selects the point shape for each data set
  3201. *
  3202. * Valid point shapes are known here and in DrawShape(). Includes: circle | dot | diamond | ...
  3203. * The point shape and point sizes arrays are synchronized before drawing a graph
  3204. * that uses points. See CheckPointParams()
  3205. *
  3206. * @param string|string[] $which_pt Array (or single value) of valid point shapes
  3207. * @return bool True (False on error if an error handler returns True)
  3208. */
  3209. function SetPointShapes($which_pt)
  3210. {
  3211. $this->point_shapes = $this->CheckOptionArray($which_pt, 'halfline, line, plus, cross, rect,'
  3212. . ' circle, dot, diamond, triangle, trianglemid, delta, yield, star, hourglass,'
  3213. . ' bowtie, target, box, home, up, down, none', __FUNCTION__);
  3214. return !empty($this->point_shapes);
  3215. }
  3216. /**
  3217. * Sets the point size for each data set
  3218. *
  3219. * The point shape and point sizes arrays are synchronized before drawing a graph
  3220. * that uses points. See CheckPointParams()
  3221. *
  3222. * @param string[]|string $which_ps Array (or single value) of point sizes in pixels
  3223. * @return bool True always
  3224. */
  3225. function SetPointSizes($which_ps)
  3226. {
  3227. if (is_array($which_ps)) {
  3228. // Use provided array:
  3229. $this->point_sizes = $which_ps;
  3230. } elseif (!is_null($which_ps)) {
  3231. // Make the single value into an array:
  3232. $this->point_sizes = array($which_ps);
  3233. }
  3234. return TRUE;
  3235. }
  3236. /**
  3237. * Sets whether lines should be broken at missing data, for 'lines' and 'squared' plots.
  3238. *
  3239. * @param bool $bl True to break the lines, false to connect around missing data
  3240. * @return bool True always
  3241. */
  3242. function SetDrawBrokenLines($bl)
  3243. {
  3244. $this->draw_broken_lines = (bool)$bl;
  3245. return TRUE;
  3246. }
  3247. /**
  3248. * Sets the data type, which defines the structure of the data array
  3249. *
  3250. * For a list of available data types, see the static arrays $datatypes and $datatypes_map.
  3251. *
  3252. * @param string $which_dt The data array format type: text-data | data-data | ...
  3253. * @return bool True (False on error if an error handler returns True)
  3254. */
  3255. function SetDataType($which_dt)
  3256. {
  3257. // Handle data type aliases - mostly for backward compatibility:
  3258. if (isset(self::$datatypes_map[$which_dt]))
  3259. $which_dt = self::$datatypes_map[$which_dt];
  3260. // Validate the datatype argument against the available data types:
  3261. $valid_data_types = implode(', ', array_keys(self::$datatypes));
  3262. $this->data_type = $this->CheckOption($which_dt, $valid_data_types, __FUNCTION__);
  3263. return (boolean)$this->data_type;
  3264. }
  3265. /**
  3266. * Sets the data array for plotting
  3267. *
  3268. * This copy the array of data values, converting rows to numerical indexes.
  3269. * It also validates that the array uses 0-based sequential integer indexes,
  3270. * and that each array value (row) is another array. Other validation is
  3271. * deferred to CheckDataArray().
  3272. *
  3273. * @param array $which_dv The data array, an array of row arrays, interpreted per SetDataType()
  3274. * @return bool True (False on error if an error handler returns True)
  3275. */
  3276. function SetDataValues($which_dv)
  3277. {
  3278. $this->num_data_rows = count($which_dv);
  3279. $this->total_records = 0;
  3280. $this->data = array();
  3281. $this->num_recs = array();
  3282. for ($i = 0; $i < $this->num_data_rows; $i++) {
  3283. if (!isset($which_dv[$i]) || !is_array($which_dv[$i])) {
  3284. return $this->PrintError("SetDataValues(): Invalid data array (row $i)");
  3285. }
  3286. $this->data[$i] = array_values($which_dv[$i]); // convert to numerical indices.
  3287. // Count size of each row, and total for the array.
  3288. $this->total_records += $this->num_recs[$i] = count($this->data[$i]);
  3289. }
  3290. // This is the size of the widest row in the data array
  3291. // Note records_per_group isn't used much anymore. See data_columns in CheckDataArray()
  3292. $this->records_per_group = empty($this->num_recs) ? 0 : max($this->num_recs);
  3293. return TRUE;
  3294. }
  3295. /**
  3296. * Pads the style arrays so they are large enough for the number of data sets
  3297. *
  3298. * The style arrays to be padded are line_widths, line_styles, data_colors, data_border_colors.
  3299. * This ensures they have at least $data_columns entries (maximum number of data sets), which
  3300. * simplifies the plot drawing functions.
  3301. * Other data color arrays are handled in the Need*Colors() functions instead (if needed).
  3302. *
  3303. * @return bool True always
  3304. */
  3305. protected function PadArrays()
  3306. {
  3307. $this->pad_array($this->line_widths, $this->data_columns);
  3308. $this->pad_array($this->line_styles, $this->data_columns);
  3309. $this->pad_array($this->ndx_data_colors, $this->data_columns);
  3310. $this->pad_array($this->ndx_data_border_colors, $this->data_columns);
  3311. return TRUE;
  3312. }
  3313. /**
  3314. * Pads an array with copies of itself until it reaches the given size
  3315. *
  3316. * pad_array only works on 0-based sequential integer indexed arrays. It also
  3317. * accepts a scalar, which is first converted to a single element array.
  3318. * Elements of the array are appended until it reaches the given size.
  3319. *
  3320. * @param array|mixed $arr Reference variable for the array (or scalar) to pad
  3321. * @param int $size Minimum size of the resulting array
  3322. */
  3323. protected function pad_array(&$arr, $size)
  3324. {
  3325. if (! is_array($arr)) {
  3326. $arr = array($arr);
  3327. }
  3328. $n = count($arr);
  3329. $base = 0;
  3330. while ($n < $size) $arr[$n++] = $arr[$base++];
  3331. }
  3332. /**
  3333. * Formats a floating point number, with decimal separator and thousands groups separator
  3334. *
  3335. * This is like PHP's number_format, but uses class variables for separators, and tries to
  3336. * get the separators from the current locale.
  3337. * Note: The locale is saved and reset after getting the values. This is needed due to an issue with
  3338. * PHP (see PHP bug 45365 and others): It uses a locale-specific decimal separator when converting
  3339. * numbers to strings, but fails to convert back if the separator is other than dot. This would cause
  3340. * pie chart labels to fail with "A non well formed numeric value encountered".
  3341. *
  3342. * @param float $number A floating point number to format
  3343. * @param int $decimals Number of decimal places in the result
  3344. * @return string The formatted result
  3345. */
  3346. protected function number_format($number, $decimals=0)
  3347. {
  3348. // Try to get the proper decimal and thousands separators if they are not already set.
  3349. if (!isset($this->decimal_point, $this->thousands_sep)) {
  3350. // Load locale-specific values from environment, unless disabled (for testing):
  3351. if (!$this->locale_override) {
  3352. $save_locale = @setlocale(LC_NUMERIC, '0');
  3353. @setlocale(LC_NUMERIC, '');
  3354. }
  3355. // Fetch locale settings:
  3356. $locale = @localeconv();
  3357. // Restore locale. (See note above.)
  3358. if (!empty($save_locale)) @setlocale(LC_NUMERIC, $save_locale);
  3359. if (isset($locale['decimal_point'], $locale['thousands_sep'])) {
  3360. $this->decimal_point = $locale['decimal_point'];
  3361. $this->thousands_sep = $locale['thousands_sep'];
  3362. } else {
  3363. // Locale information not available.
  3364. $this->decimal_point = '.';
  3365. $this->thousands_sep = ',';
  3366. }
  3367. }
  3368. return number_format($number, $decimals, $this->decimal_point, $this->thousands_sep);
  3369. }
  3370. /**
  3371. * Registers a callback (hook) function
  3372. *
  3373. * See the $callbacks array (class property) for the available callback names
  3374. *
  3375. * @param string $reason A pre-defined name where a callback can be defined
  3376. * @param callback $function Function or method to register for callback
  3377. * @param mixed $arg Optional opaque argument to supply to the callback function when called
  3378. * @return bool True if the callback reason is valid, else False
  3379. * @since 5.0.4
  3380. */
  3381. function SetCallback($reason, $function, $arg = NULL)
  3382. {
  3383. // Use array_key_exists because valid reason keys have NULL as value.
  3384. if (!array_key_exists($reason, $this->callbacks))
  3385. return FALSE;
  3386. $this->callbacks[$reason] = array($function, $arg);
  3387. return TRUE;
  3388. }
  3389. /**
  3390. * Returns the current callback function registered for the given reason
  3391. *
  3392. * Note you can safely test the return value with a simple 'if', as no valid
  3393. * function name evaluates to false. PHPlot uses if (GetCallback(...)) to
  3394. * to avoid preparing arguments to an unused callback.
  3395. *
  3396. * @param string $reason A pre-defined name where a callback can be defined
  3397. * @return callback|false The current callback for the reason; False if none or invalid
  3398. * @since 5.0.4
  3399. */
  3400. function GetCallback($reason)
  3401. {
  3402. if (isset($this->callbacks[$reason]))
  3403. return $this->callbacks[$reason][0];
  3404. return FALSE;
  3405. }
  3406. /**
  3407. * Un-registers any callback registered for the given reason
  3408. *
  3409. * Note: A True return means $reason is valid; it does not mean a callback
  3410. * was actually registered for that reason.
  3411. *
  3412. * @param string $reason A pre-defined name where a callback can be defined
  3413. * @return bool True if it was a valid callback reason, else False
  3414. * @since 5.0.4
  3415. */
  3416. function RemoveCallback($reason)
  3417. {
  3418. if (!array_key_exists($reason, $this->callbacks))
  3419. return FALSE;
  3420. $this->callbacks[$reason] = NULL;
  3421. return TRUE;
  3422. }
  3423. /**
  3424. * Invokes a callback function, if one is registered
  3425. *
  3426. * Callbacks are called like this: callback_function($image, $passthru, [$arg,...])
  3427. * Here $passthru is the argument specified when the callback was defined by SetCallback()
  3428. * and is under control of the application. $arg... is zero or more additional arguments
  3429. * specified when then callback is called. These are under control of PHPlot itself.
  3430. *
  3431. * @param string $reason A string naming one of the pre-defined callback reasons
  3432. * @param mixed $varargs Zero or more additional arguments to be passed to the callback
  3433. * @return mixed Whatever value is returned by the callback function (if any)
  3434. */
  3435. protected function DoCallback($reason, $varargs = NULL)
  3436. {
  3437. if (!isset($this->callbacks[$reason]))
  3438. return;
  3439. $args = func_get_args();
  3440. // Make the argument vector $args[] look like: $image, $passthru, [$arg...]
  3441. list($function, $args[0]) = $this->callbacks[$reason];
  3442. array_unshift($args, $this->img);
  3443. return call_user_func_array($function, $args);
  3444. }
  3445. /**
  3446. * Allocates colors for the image background and image border
  3447. *
  3448. * This is separate from SetColorIndexes() below so that DrawMessage can use it.
  3449. *
  3450. * @since 5.7.0
  3451. */
  3452. protected function SetBgColorIndexes()
  3453. {
  3454. $this->ndx_bg_color = $this->GetColorIndex($this->bg_color); // Background first
  3455. $this->ndx_plot_bg_color = $this->GetColorIndex($this->plot_bg_color);
  3456. if ($this->image_border_type != 'none') {
  3457. $this->ndx_i_border = $this->GetColorIndex($this->i_border);
  3458. $this->ndx_i_border_dark = $this->GetDarkColorIndex($this->i_border);
  3459. }
  3460. }
  3461. /**
  3462. * Allocates all the colors needed for the plot
  3463. *
  3464. * This is called by DrawGraph to allocate the colors needed for the plot. Each selectable
  3465. * color has already been validated, parsed into an array (r,g,b,a), and stored into a member
  3466. * variable. Now the GD color indexes are assigned and stored into the ndx_*_color variables.
  3467. * This is deferred here to avoid allocating unneeded colors and to avoid order dependencies,
  3468. * especially with the transparent color.
  3469. *
  3470. * For drawing data elements, only the main data colors and border colors are allocated here.
  3471. * Dark colors and error bar colors are allocated by Need*Color() functions.
  3472. * (Data border colors default to just black, so there is no cost to always allocating.)
  3473. *
  3474. * Data color allocation works as follows. If there is a data_color callback, then allocate all
  3475. * defined data colors (because the callback can use them however it wants). Otherwise, only allocate
  3476. * the number of colors that will be used. This is the larger of the number of data sets and the
  3477. * number of legend lines.
  3478. *
  3479. * @since 5.2.0
  3480. */
  3481. protected function SetColorIndexes()
  3482. {
  3483. $this->SetBgColorIndexes(); // Background and border colors
  3484. // Handle defaults for X and Y title colors.
  3485. $this->ndx_title_color = $this->GetColorIndex($this->title_color);
  3486. $this->ndx_x_title_color = $this->GetColorIndex($this->x_title_color, $this->ndx_title_color);
  3487. $this->ndx_y_title_color = $this->GetColorIndex($this->y_title_color, $this->ndx_title_color);
  3488. // General text color, which is the default color for tick and data labels unless overridden.
  3489. $this->ndx_text_color = $this->GetColorIndex($this->text_color);
  3490. $this->ndx_ticklabel_color = $this->GetColorIndex($this->ticklabel_color, $this->ndx_text_color);
  3491. $this->ndx_datalabel_color = $this->GetColorIndex($this->datalabel_color, $this->ndx_text_color);
  3492. $this->ndx_dvlabel_color = $this->GetColorIndex($this->dvlabel_color, $this->ndx_datalabel_color);
  3493. $this->ndx_grid_color = $this->GetColorIndex($this->grid_color);
  3494. $this->ndx_light_grid_color = $this->GetColorIndex($this->light_grid_color);
  3495. $this->ndx_tick_color = $this->GetColorIndex($this->tick_color);
  3496. // Pie label and border colors default to grid color, for historical reasons (PHPlot <= 5.6.1)
  3497. $this->ndx_pielabel_color = $this->GetColorIndex($this->pielabel_color, $this->ndx_grid_color);
  3498. $this->ndx_pieborder_color = $this->GetColorIndex($this->pieborder_color, $this->ndx_grid_color);
  3499. // Maximum number of data & border colors to allocate:
  3500. if ($this->GetCallback('data_color')) {
  3501. $n_data = count($this->data_colors); // Need all of them
  3502. $n_border = count($this->data_border_colors);
  3503. } else {
  3504. $n_data = max($this->data_columns, empty($this->legend) ? 0 : count($this->legend));
  3505. $n_border = $n_data; // One border color per data color
  3506. }
  3507. // Allocate main data colors. For other colors used for data, see the functions which follow.
  3508. $this->ndx_data_colors = $this->GetColorIndexArray($this->data_colors, $n_data);
  3509. $this->ndx_data_border_colors = $this->GetColorIndexArray($this->data_border_colors, $n_border);
  3510. // Legend colors: background defaults to image background, text defaults to general text color.
  3511. $this->ndx_legend_bg_color = $this->GetColorIndex($this->legend_bg_color, $this->ndx_bg_color);
  3512. $this->ndx_legend_text_color = $this->GetColorIndex($this->legend_text_color, $this->ndx_text_color);
  3513. // Set up a color as transparent, if SetTransparentColor was used.
  3514. if (!empty($this->transparent_color)) {
  3515. imagecolortransparent($this->img, $this->GetColorIndex($this->transparent_color));
  3516. }
  3517. }
  3518. /**
  3519. * Allocates dark-shade data colors used for shading
  3520. *
  3521. * This is called if needed by graph drawing functions that need shading.
  3522. *
  3523. * @since 5.2.0
  3524. */
  3525. protected function NeedDataDarkColors()
  3526. {
  3527. // This duplicates the calculation in SetColorIndexes() for number of data colors to allocate.
  3528. if ($this->GetCallback('data_color')) {
  3529. $n_data = count($this->data_colors);
  3530. } else {
  3531. $n_data = max($this->data_columns, empty($this->legend) ? 0 : count($this->legend));
  3532. }
  3533. $this->ndx_data_dark_colors = $this->GetDarkColorIndexArray($this->data_colors, $n_data);
  3534. $this->pad_array($this->ndx_data_dark_colors, $this->data_columns);
  3535. }
  3536. /**
  3537. * Allocates error bar colors
  3538. *
  3539. * This is called if needed by graph drawing functions that draw error bars.
  3540. *
  3541. * @since 5.2.0
  3542. */
  3543. protected function NeedErrorBarColors()
  3544. {
  3545. // This is similar to the calculation in SetColorIndexes() for number of data colors to allocate.
  3546. if ($this->GetCallback('data_color')) {
  3547. $n_err = count($this->error_bar_colors);
  3548. } else {
  3549. $n_err = max($this->data_columns, empty($this->legend) ? 0 : count($this->legend));
  3550. }
  3551. $this->ndx_error_bar_colors = $this->GetColorIndexArray($this->error_bar_colors, $n_err);
  3552. $this->pad_array($this->ndx_error_bar_colors, $this->data_columns);
  3553. }
  3554. /**
  3555. * Selects the best alignment for text, based on its vector angle from a point
  3556. *
  3557. * This picks one of 8 alignments (horizontal = left, center, or right; vertical = top, center
  3558. * or bottom; but never center/center) for text that needs to be close to a point but directed
  3559. * away from the point. The angle of the vector from the reference point determines the alignment.
  3560. *
  3561. * How it works: Picture a unit circle with 16 slices of 22.5 degrees each.
  3562. * Draw horizontal lines at the 22.5 degree and -22.5 degree positions on the circle.
  3563. * Text above the upper line will have 'bottom' vertical alignment; below the lower line will
  3564. * have 'top' vertical alignment, and between the lines will have 'center' vertical alignment.
  3565. * Horizontal alignment is similar, using +/- 22.5 degrees from vertical.
  3566. *
  3567. * @param float $sin_t sin() of the angle of the text offset from a reference point
  3568. * @param float $cos_t cos() of the angle of the text offset from a reference point
  3569. * @param string $h_align Reference variable to get the horizontal alignment, for DrawText()
  3570. * @param string $v_align Reference variable to get the vertical alignment, for DrawText()
  3571. * @param bool $reverse True to reverse the alignment, e.g. for text inside an ellipse
  3572. * @since 5.6.0
  3573. */
  3574. protected function GetTextAlignment($sin_t, $cos_t, &$h_align, &$v_align, $reverse = FALSE)
  3575. {
  3576. if ($reverse) { // Return the opposite alignment, align(T-180) vs align(T)
  3577. $sin_t = -$sin_t; // sin(T-180) = -sin(T)
  3578. $cos_t = -$cos_t; // cos(T-180) = -cos(T)
  3579. }
  3580. if ($sin_t >= 0.383) $v_align = 'bottom'; // 0.383 = sin(22.5 degrees)
  3581. elseif ($sin_t >= -0.383) $v_align = 'center';
  3582. else $v_align = 'top';
  3583. if ($cos_t >= 0.383) $h_align = 'left'; // 0.383 = cos(90 - 22.5 degrees)
  3584. elseif ($cos_t >= -0.383) $h_align = 'center';
  3585. else $h_align = 'right';
  3586. }
  3587. /**
  3588. * Determines if and where to draw Data Value Labels
  3589. *
  3590. * This is called by plot drawing functions that support Data Value Labels (other
  3591. * than bars and stackedbars, which have their own way of doing it). If those
  3592. * labels are on, it returns True and sets 4 keys in $dvl[] which are used by
  3593. * DrawDataValueLabel to position the label: x_offset, y_offset = pixel offsets
  3594. * for the label; h_align, v_align = text alignment choices.
  3595. * It uses two member variables: data_value_label_angle and data_value_label_distance
  3596. * to define the vector to the label.
  3597. *
  3598. * @param string $label_control Label position control; either $x_data_label_pos or $y_data_label_pos
  3599. * @param array $dvl Reference argument for result parameters for DrawDataValueLabel()
  3600. * @return bool False if data value labels are off; True if on and $dvl is set
  3601. * @since 5.3.0
  3602. */
  3603. protected function CheckDataValueLabels($label_control, &$dvl)
  3604. {
  3605. if ($label_control != 'plotin')
  3606. return FALSE; // No data value labels
  3607. $angle = deg2rad($this->data_value_label_angle);
  3608. $cos = cos($angle);
  3609. $sin = sin($angle);
  3610. $dvl['x_offset'] = (int)($this->data_value_label_distance * $cos);
  3611. $dvl['y_offset'] = -(int)($this->data_value_label_distance * $sin); // Y is reversed (device coords)
  3612. // Choose text alignment based on angle:
  3613. $this->GetTextAlignment($sin, $cos, $dvl['h_align'], $dvl['v_align']);
  3614. return TRUE;
  3615. }
  3616. /**
  3617. * Enables or disables automatic pie chart size calculation
  3618. *
  3619. * If autosize is disabled, PHPlot uses the full plot area (as PHPlot-5.5.0
  3620. * and earlier always did). Note the flag pie_full_size is unset by default,
  3621. * and stores the complement of $enable.
  3622. *
  3623. * @param bool $enable True to enable automatic size calculation, False to use the maximum area
  3624. * @return bool True always
  3625. * @since 5.6.0
  3626. */
  3627. function SetPieAutoSize($enable)
  3628. {
  3629. $this->pie_full_size = !$enable;
  3630. return TRUE;
  3631. }
  3632. /**
  3633. * Sets the starting angle for pie chart segments
  3634. *
  3635. * @param float $angle Starting angle in degrees
  3636. * @return bool True always
  3637. * @since 6.0.0
  3638. */
  3639. function SetPieStartAngle($angle)
  3640. {
  3641. $this->pie_start_angle = $angle;
  3642. return TRUE;
  3643. }
  3644. /**
  3645. * Sets the direction for pie chart segments
  3646. *
  3647. * @param string $which Direction for pie segments: clockwise | cw | counterclockwise | ccw
  3648. * @return bool True (False on error if an error handler returns True)
  3649. * @since 6.0.0
  3650. */
  3651. function SetPieDirection($which)
  3652. {
  3653. $control = $this->CheckOption($which, 'clockwise, cw, counterclockwise, ccw', __FUNCTION__);
  3654. if (empty($control)) return FALSE;
  3655. $this->pie_direction_cw = ($control == 'clockwise' || $control == 'cw');
  3656. return TRUE;
  3657. }
  3658. //////////////////////////////////////////////////////////
  3659. /////////// DATA ANALYSIS, SCALING AND TRANSLATION
  3660. //////////////////////////////////////////////////////////
  3661. /**
  3662. * Analyzes the data array and calculates the minimum and maximum values
  3663. *
  3664. * In this function, IV refers to the independent variable, and DV the dependent
  3665. * variable. For vertical plots (most common), IV is X and DV is Y. For
  3666. * horizontal plots (swapped X/Y), IV is Y and DV is X. At the end of the
  3667. * function, IV and DV ranges get assigned into X or Y variables.
  3668. *
  3669. * The data type mostly determines the data array structure, but some plot types
  3670. * do special things such as sum the values in a row. This information is in the
  3671. * plots[] array.
  3672. *
  3673. * This calculates min_x, max_x, min_y, and max_y. It also calculates two arrays
  3674. * data_min[] and data_max[] with per-row min and max values. These are used for
  3675. * data label lines. For vertical plots, these are the Y range for each X. For
  3676. * vertical (swapped X/Y) plots, they are the X range for each Y. For X/Y/Z
  3677. * plots, it also calculates min_z and max_z.
  3678. *
  3679. * @return bool True always
  3680. */
  3681. protected function FindDataLimits()
  3682. {
  3683. // Does this plot type need special processing of the data values?
  3684. $sum_vals = !empty(self::$plots[$this->plot_type]['sum_vals']); // Add up values in each row
  3685. $abs_vals = !empty(self::$plots[$this->plot_type]['abs_vals']); // Take absolute values
  3686. // Initialize arrays which track the min/max per-row dependent values:
  3687. $this->data_min = array();
  3688. $this->data_max = array();
  3689. // Independent values are in the data array or assumed?
  3690. if ($this->datatype_implied) {
  3691. // Range for text-data is 0.5 to num_data_rows-0.5. Add 0.5 fixed margins on each side.
  3692. $all_iv = array(0, $this->num_data_rows);
  3693. } else {
  3694. $all_iv = array(); // Calculated below
  3695. }
  3696. // For X/Y/Z plots, make sure these are not left over from a previous plot.
  3697. if ($this->datatype_yz)
  3698. $this->min_z = $this->max_z = NULL;
  3699. // Process all rows of data:
  3700. for ($i = 0; $i < $this->num_data_rows; $i++) {
  3701. $n_vals = $this->num_recs[$i];
  3702. $j = 1; // Skips label at [0]
  3703. if (!$this->datatype_implied) {
  3704. $all_iv[] = (double)$this->data[$i][$j++];
  3705. }
  3706. if ($sum_vals) {
  3707. $all_dv = array(0, 0); // One limit is 0, other calculated below
  3708. } else {
  3709. $all_dv = array();
  3710. }
  3711. while ($j < $n_vals) {
  3712. if (is_numeric($val = $this->data[$i][$j++])) {
  3713. if ($this->datatype_error_bars) {
  3714. $all_dv[] = $val + (double)$this->data[$i][$j++];
  3715. $all_dv[] = $val - (double)$this->data[$i][$j++];
  3716. } else {
  3717. if ($abs_vals) {
  3718. $val = abs($val); // Use absolute values
  3719. }
  3720. if ($sum_vals) {
  3721. $all_dv[1] += $val; // Sum of values
  3722. } else {
  3723. $all_dv[] = $val; // List of all values
  3724. }
  3725. if ($this->datatype_yz) {
  3726. $z = $this->data[$i][$j++]; // Note Z is required if Y is present.
  3727. if (!isset($this->min_z) || $z < $this->min_z) $this->min_z = $z;
  3728. if (!isset($this->max_z) || $z > $this->max_z) $this->max_z = $z;
  3729. }
  3730. }
  3731. } else { // Missing DV value
  3732. if ($this->datatype_error_bars) $j += 2;
  3733. elseif ($this->datatype_yz) $j++;
  3734. }
  3735. }
  3736. if (!empty($all_dv)) {
  3737. $this->data_min[$i] = min($all_dv); // Store per-row DV range
  3738. $this->data_max[$i] = max($all_dv);
  3739. }
  3740. }
  3741. if ($this->datatype_swapped_xy) {
  3742. // Assign min and max for swapped X/Y plots: IV=Y and DV=X
  3743. $this->min_y = min($all_iv);
  3744. $this->max_y = max($all_iv);
  3745. if (empty($this->data_min)) { // Guard against regressive case: No X at all
  3746. $this->min_x = 0;
  3747. $this->max_x = 0;
  3748. } else {
  3749. $this->min_x = min($this->data_min); // Store global X range
  3750. $this->max_x = max($this->data_max);
  3751. }
  3752. } else {
  3753. // Assign min and max for normal plots: IV=X and DV=Y
  3754. $this->min_x = min($all_iv);
  3755. $this->max_x = max($all_iv);
  3756. if (empty($this->data_min)) { // Guard against regressive case: No Y at all
  3757. $this->min_y = 0;
  3758. $this->max_y = 0;
  3759. } else {
  3760. $this->min_y = min($this->data_min); // Store global Y range
  3761. $this->max_y = max($this->data_max);
  3762. }
  3763. }
  3764. // For X/Y/Z plots, make sure these are set. If there are no valid data values,
  3765. // they will be unset, so set them here to prevent undefined property warnings.
  3766. if ($this->datatype_yz && !isset($this->min_z)) { // Means max_z is also unset
  3767. $this->max_z = $this->min_z = 0; // Actual values do not matter.
  3768. }
  3769. if ($this->GetCallback('debug_scale')) {
  3770. $this->DoCallback('debug_scale', __FUNCTION__, array(
  3771. 'min_x' => $this->min_x, 'min_y' => $this->min_y,
  3772. 'max_x' => $this->max_x, 'max_y' => $this->max_y,
  3773. 'min_z' => isset($this->min_z) ? $this->min_z : '',
  3774. 'max_z' => isset($this->max_z) ? $this->max_z : ''));
  3775. }
  3776. return TRUE;
  3777. }
  3778. /**
  3779. * Calculates the plot area margin size and related positions and offsets
  3780. *
  3781. * Calculates the title sizes: title_height, x_title_height, and y_title_width.
  3782. * These are local, not class variables, since they are only used here.
  3783. * The X and Y title size variables are 0 if there is no corresponding title.
  3784. *
  3785. * Calculates the tick label and axis data label offsets, relative to the plot
  3786. * area: x_label_top_offset, x_label_bot_offset, x_label_axis_offset,
  3787. * y_label_left_offset, y_label_right_offset, and y_label_axis_offset.
  3788. *
  3789. * Calculates the title position offsets, relative to the plot area:
  3790. * x_title_top_offset, x_title_bot_offset, y_title_left_offset, and
  3791. * y_title_left_offset. Also calculates the main title offset, which is relative
  3792. * to the top of the image.
  3793. *
  3794. * Finally, calculates the plot area margins using the above to figure out how
  3795. * much space outside the plot area is needed. The class variables are:
  3796. * y_top_margin, y_bot_margin, x_left_margin, and x_right_margin. All 4 margins
  3797. * are calculated, but only those not set with SetPlotAreaPixels() or
  3798. * SetMarginsPixels() are stored into the class variables.
  3799. *
  3800. * A plot with $minimize True, such as a pie chart, does not have an X or Y axis
  3801. * or X/Y titles, and so can use more of the image space.
  3802. *
  3803. * A picture of the locations of elements and spacing can be found in the
  3804. * PHPlot Reference Manual.
  3805. *
  3806. * @param bool $maximize If True, use full image area (less margins and title space)
  3807. * @return bool True always
  3808. */
  3809. protected function CalcMargins($maximize)
  3810. {
  3811. // This is the line-to-line or line-to-text spacing:
  3812. $gap = $this->safe_margin;
  3813. // Initial margin on each side takes into account a possible image border.
  3814. // For compatibility, if border is 1 or 2, don't increase the margins.
  3815. $base_margin = max($gap, $this->GetImageBorderWidth() + 3);
  3816. $this->title_offset = $base_margin; // For use in DrawTitle
  3817. // Minimum margin on each side. This reduces the chance that the
  3818. // right-most tick label (for example) will run off the image edge
  3819. // if there are no titles on that side.
  3820. $min_margin = 2 * $gap + $base_margin;
  3821. // Calculate the title sizes (main here, axis titles below):
  3822. list($unused, $title_height) = $this->SizeText('title', 0, $this->title_txt);
  3823. // Special case for maximum area usage with no X/Y titles or labels, only main title:
  3824. if ($maximize) {
  3825. if (!isset($this->x_left_margin))
  3826. $this->x_left_margin = $base_margin;
  3827. if (!isset($this->x_right_margin))
  3828. $this->x_right_margin = $base_margin;
  3829. if (!isset($this->y_top_margin)) {
  3830. $this->y_top_margin = $base_margin;
  3831. if ($title_height > 0)
  3832. $this->y_top_margin += $title_height + $gap;
  3833. }
  3834. if (!isset($this->y_bot_margin))
  3835. $this->y_bot_margin = $base_margin;
  3836. return TRUE;
  3837. }
  3838. list($unused, $x_title_height) = $this->SizeText('x_title', 0, $this->x_title_txt);
  3839. list($y_title_width, $unused) = $this->SizeText('y_title', 90, $this->y_title_txt);
  3840. // For X/Y tick and label position of 'xaxis' or 'yaxis', determine if the axis happens to be
  3841. // on an edge of a plot. If it is, we need to account for the margins there.
  3842. if ($this->x_axis_position <= $this->plot_min_y)
  3843. $x_axis_pos = 'bottom';
  3844. elseif ($this->x_axis_position >= $this->plot_max_y)
  3845. $x_axis_pos = 'top';
  3846. else
  3847. $x_axis_pos = 'none';
  3848. if ($this->y_axis_position <= $this->plot_min_x)
  3849. $y_axis_pos = 'left';
  3850. elseif ($this->y_axis_position >= $this->plot_max_x)
  3851. $y_axis_pos = 'right';
  3852. else
  3853. $y_axis_pos = 'none';
  3854. // Calculate the heights for X tick and data labels, and the max (used if they are overlaid):
  3855. $x_data_label_height = ($this->x_data_label_pos == 'none') ? 0 : $this->CalcMaxDataLabelSize('x');
  3856. $x_tick_label_height = ($this->x_tick_label_pos == 'none') ? 0 : $this->CalcMaxTickLabelSize('x');
  3857. $x_max_label_height = max($x_data_label_height, $x_tick_label_height);
  3858. // Calculate the space needed above and below the plot for X tick and X data labels:
  3859. // Above the plot:
  3860. $tick_labels_above = ($this->x_tick_label_pos == 'plotup' || $this->x_tick_label_pos == 'both'
  3861. || ($this->x_tick_label_pos == 'xaxis' && $x_axis_pos == 'top'));
  3862. $data_labels_above = ($this->x_data_label_pos == 'plotup' || $this->x_data_label_pos == 'both');
  3863. if ($tick_labels_above) {
  3864. if ($data_labels_above) {
  3865. $label_height_above = $x_max_label_height;
  3866. } else {
  3867. $label_height_above = $x_tick_label_height;
  3868. }
  3869. } elseif ($data_labels_above) {
  3870. $label_height_above = $x_data_label_height;
  3871. } else {
  3872. $label_height_above = 0;
  3873. }
  3874. // Below the plot:
  3875. $tick_labels_below = ($this->x_tick_label_pos == 'plotdown' || $this->x_tick_label_pos == 'both'
  3876. || ($this->x_tick_label_pos == 'xaxis' && $x_axis_pos == 'bottom'));
  3877. $data_labels_below = ($this->x_data_label_pos == 'plotdown' || $this->x_data_label_pos == 'both');
  3878. if ($tick_labels_below) {
  3879. if ($data_labels_below) {
  3880. $label_height_below = $x_max_label_height;
  3881. } else {
  3882. $label_height_below = $x_tick_label_height;
  3883. }
  3884. } elseif ($data_labels_below) {
  3885. $label_height_below = $x_data_label_height;
  3886. } else {
  3887. $label_height_below = 0;
  3888. }
  3889. // Calculate the width for Y tick and data labels, if on, and the max:
  3890. // Note CalcMaxDataLabelSize('y') returns 0 except for swapped X/Y plots.
  3891. $y_data_label_width = ($this->y_data_label_pos == 'none') ? 0 : $this->CalcMaxDataLabelSize('y');
  3892. $y_tick_label_width = ($this->y_tick_label_pos == 'none') ? 0 : $this->CalcMaxTickLabelSize('y');
  3893. $y_max_label_width = max($y_data_label_width, $y_tick_label_width);
  3894. // Calculate the space needed left and right of the plot for Y tick and Y data labels:
  3895. // (Y data labels here are for swapped X/Y plots such has horizontal bars)
  3896. // Left of the plot:
  3897. $tick_labels_left = ($this->y_tick_label_pos == 'plotleft' || $this->y_tick_label_pos == 'both'
  3898. || ($this->y_tick_label_pos == 'yaxis' && $y_axis_pos == 'left'));
  3899. $data_labels_left = ($this->y_data_label_pos == 'plotleft' || $this->y_data_label_pos == 'both');
  3900. if ($tick_labels_left) {
  3901. if ($data_labels_left) {
  3902. $label_width_left = $y_max_label_width;
  3903. } else {
  3904. $label_width_left = $y_tick_label_width;
  3905. }
  3906. } elseif ($data_labels_left) {
  3907. $label_width_left = $y_data_label_width;
  3908. } else {
  3909. $label_width_left = 0;
  3910. }
  3911. // Right of the plot:
  3912. $tick_labels_right = ($this->y_tick_label_pos == 'plotright' || $this->y_tick_label_pos == 'both'
  3913. || ($this->y_tick_label_pos == 'yaxis' && $y_axis_pos == 'right'));
  3914. $data_labels_right = ($this->y_data_label_pos == 'plotright' || $this->y_data_label_pos == 'both');
  3915. if ($tick_labels_right) {
  3916. if ($data_labels_right) {
  3917. $label_width_right = $y_max_label_width;
  3918. } else {
  3919. $label_width_right = $y_tick_label_width;
  3920. }
  3921. } elseif ($data_labels_right) {
  3922. $label_width_right = $y_data_label_width;
  3923. } else {
  3924. $label_width_right = 0;
  3925. }
  3926. ///////// Calculate margins:
  3927. // Calculating Top and Bottom margins:
  3928. // y_top_margin: Main title, Upper X title, X ticks and tick labels, and X data labels:
  3929. // y_bot_margin: Lower title, ticks and tick labels, and data labels:
  3930. $top_margin = $base_margin;
  3931. $bot_margin = $base_margin;
  3932. $this->x_title_top_offset = $gap;
  3933. $this->x_title_bot_offset = $gap;
  3934. // Space for main title?
  3935. if ($title_height > 0)
  3936. $top_margin += $title_height + $gap;
  3937. // Reserve space for X title, above and/or below as needed:
  3938. if ($x_title_height > 0 && ($pos = $this->x_title_pos) != 'none') {
  3939. if ($pos == 'plotup' || $pos == 'both')
  3940. $top_margin += $x_title_height + $gap;
  3941. if ($pos == 'plotdown' || $pos == 'both')
  3942. $bot_margin += $x_title_height + $gap;
  3943. }
  3944. // Space for X Labels above the plot?
  3945. if ($label_height_above > 0) {
  3946. $top_margin += $label_height_above + $gap;
  3947. $this->x_title_top_offset += $label_height_above + $gap;
  3948. }
  3949. // Space for X Labels below the plot?
  3950. if ($label_height_below > 0) {
  3951. $bot_margin += $label_height_below + $gap;
  3952. $this->x_title_bot_offset += $label_height_below + $gap;
  3953. }
  3954. // Space for X Ticks above the plot?
  3955. if ($this->x_tick_pos == 'plotup' || $this->x_tick_pos == 'both'
  3956. || ($this->x_tick_pos == 'xaxis' && $x_axis_pos == 'top')) {
  3957. $top_margin += $this->x_tick_length;
  3958. $this->x_label_top_offset = $this->x_tick_length + $gap;
  3959. $this->x_title_top_offset += $this->x_tick_length;
  3960. } else {
  3961. // No X Ticks above the plot:
  3962. $this->x_label_top_offset = $gap;
  3963. }
  3964. // Space for X Ticks below the plot?
  3965. if ($this->x_tick_pos == 'plotdown' || $this->x_tick_pos == 'both'
  3966. || ($this->x_tick_pos == 'xaxis' && $x_axis_pos == 'bottom')) {
  3967. $bot_margin += $this->x_tick_length;
  3968. $this->x_label_bot_offset = $this->x_tick_length + $gap;
  3969. $this->x_title_bot_offset += $this->x_tick_length;
  3970. } else {
  3971. // No X Ticks below the plot:
  3972. $this->x_label_bot_offset = $gap;
  3973. }
  3974. // Label offsets for on-axis ticks:
  3975. if ($this->x_tick_pos == 'xaxis') {
  3976. $this->x_label_axis_offset = $this->x_tick_length + $gap;
  3977. } else {
  3978. $this->x_label_axis_offset = $gap;
  3979. }
  3980. // Calculating Left and Right margins:
  3981. // x_left_margin: Left Y title, Y ticks and tick labels:
  3982. // x_right_margin: Right Y title, Y ticks and tick labels:
  3983. $left_margin = $base_margin;
  3984. $right_margin = $base_margin;
  3985. $this->y_title_left_offset = $gap;
  3986. $this->y_title_right_offset = $gap;
  3987. // Reserve space for Y title, on left and/or right as needed:
  3988. if ($y_title_width > 0 && ($pos = $this->y_title_pos) != 'none') {
  3989. if ($pos == 'plotleft' || $pos == 'both')
  3990. $left_margin += $y_title_width + $gap;
  3991. if ($pos == 'plotright' || $pos == 'both')
  3992. $right_margin += $y_title_width + $gap;
  3993. }
  3994. // Space for Y Labels left of the plot?
  3995. if ($label_width_left > 0) {
  3996. $left_margin += $label_width_left + $gap;
  3997. $this->y_title_left_offset += $label_width_left + $gap;
  3998. }
  3999. // Space for Y Labels right of the plot?
  4000. if ($label_width_right > 0) {
  4001. $right_margin += $label_width_right + $gap;
  4002. $this->y_title_right_offset += $label_width_right + $gap;
  4003. }
  4004. // Space for Y Ticks left of plot?
  4005. if ($this->y_tick_pos == 'plotleft' || $this->y_tick_pos == 'both'
  4006. || ($this->y_tick_pos == 'yaxis' && $y_axis_pos == 'left')) {
  4007. $left_margin += $this->y_tick_length;
  4008. $this->y_label_left_offset = $this->y_tick_length + $gap;
  4009. $this->y_title_left_offset += $this->y_tick_length;
  4010. } else {
  4011. // No Y Ticks left of plot:
  4012. $this->y_label_left_offset = $gap;
  4013. }
  4014. // Space for Y Ticks right of plot?
  4015. if ($this->y_tick_pos == 'plotright' || $this->y_tick_pos == 'both'
  4016. || ($this->y_tick_pos == 'yaxis' && $y_axis_pos == 'right')) {
  4017. $right_margin += $this->y_tick_length;
  4018. $this->y_label_right_offset = $this->y_tick_length + $gap;
  4019. $this->y_title_right_offset += $this->y_tick_length;
  4020. } else {
  4021. // No Y Ticks right of plot:
  4022. $this->y_label_right_offset = $gap;
  4023. }
  4024. // Label offsets for on-axis ticks:
  4025. if ($this->x_tick_pos == 'yaxis') {
  4026. $this->y_label_axis_offset = $this->y_tick_length + $gap;
  4027. } else {
  4028. $this->y_label_axis_offset = $gap;
  4029. }
  4030. // Apply the minimum margins and store in the object.
  4031. // Do not set margins which were user-defined (see note at top of function).
  4032. if (!isset($this->y_top_margin))
  4033. $this->y_top_margin = max($min_margin, $top_margin);
  4034. if (!isset($this->y_bot_margin))
  4035. $this->y_bot_margin = max($min_margin, $bot_margin);
  4036. if (!isset($this->x_left_margin))
  4037. $this->x_left_margin = max($min_margin, $left_margin);
  4038. if (!isset($this->x_right_margin))
  4039. $this->x_right_margin = max($min_margin, $right_margin);
  4040. if ($this->GetCallback('debug_scale')) {
  4041. // (Too bad compact() doesn't work on class member variables...)
  4042. $this->DoCallback('debug_scale', __FUNCTION__, array(
  4043. 'label_height_above' => $label_height_above,
  4044. 'label_height_below' => $label_height_below,
  4045. 'label_width_left' => $label_width_left,
  4046. 'label_width_right' => $label_width_right,
  4047. 'x_tick_length' => $this->x_tick_length,
  4048. 'y_tick_length' => $this->y_tick_length,
  4049. 'x_left_margin' => $this->x_left_margin,
  4050. 'x_right_margin' => $this->x_right_margin,
  4051. 'y_top_margin' => $this->y_top_margin,
  4052. 'y_bot_margin' => $this->y_bot_margin,
  4053. 'x_label_top_offset' => $this->x_label_top_offset,
  4054. 'x_label_bot_offset' => $this->x_label_bot_offset,
  4055. 'y_label_left_offset' => $this->y_label_left_offset,
  4056. 'y_label_right_offset' => $this->y_label_right_offset,
  4057. 'x_title_top_offset' => $this->x_title_top_offset,
  4058. 'x_title_bot_offset' => $this->x_title_bot_offset,
  4059. 'y_title_left_offset' => $this->y_title_left_offset,
  4060. 'y_title_right_offset' => $this->y_title_right_offset));
  4061. }
  4062. return TRUE;
  4063. }
  4064. /**
  4065. * Calculates the plot area (in pixels) from the margins
  4066. *
  4067. * This does the deferred calculation of class variables plot_area,
  4068. * plot_area_width, and plot_area_height. The margins might come
  4069. * from SetMarginsPixels(), SetPlotAreaPixels(), or CalcMargins().
  4070. *
  4071. * @return bool True always
  4072. * @since 5.0.5
  4073. */
  4074. protected function CalcPlotAreaPixels()
  4075. {
  4076. $this->plot_area = array($this->x_left_margin, $this->y_top_margin,
  4077. $this->image_width - $this->x_right_margin,
  4078. $this->image_height - $this->y_bot_margin);
  4079. $this->plot_area_width = $this->plot_area[2] - $this->plot_area[0];
  4080. $this->plot_area_height = $this->plot_area[3] - $this->plot_area[1];
  4081. $this->DoCallback('debug_scale', __FUNCTION__, $this->plot_area);
  4082. return TRUE;
  4083. }
  4084. /**
  4085. * Sets the margins around the plot area
  4086. *
  4087. * This determines the plot area, equivalent to SetPlotAreaPixels()
  4088. * but instead of giving the plot area size, you give the margin sizes.
  4089. *
  4090. * @param int $which_lm Left margin in pixels; omit or NULL to auto-calculate
  4091. * @param int $which_rm Right margin in pixels; omit or NULL to auto-calculate
  4092. * @param int $which_tm Top margin in pixels; omit or NULL to auto-calculate
  4093. * @param int $which_bm Bottom margin in pixels; omit or NULL to auto-calculate
  4094. * @return bool True always
  4095. */
  4096. function SetMarginsPixels($which_lm = NULL, $which_rm = NULL, $which_tm = NULL, $which_bm = NULL)
  4097. {
  4098. $this->x_left_margin = $which_lm;
  4099. $this->x_right_margin = $which_rm;
  4100. $this->y_top_margin = $which_tm;
  4101. $this->y_bot_margin = $which_bm;
  4102. return TRUE;
  4103. }
  4104. /**
  4105. * Sets the limits for the plot area, in device coordinates
  4106. *
  4107. * This determines the plot area, equivalent to SetMarginsPixels()
  4108. * but instead of giving the margin sizes, you give the plot area size,
  4109. *
  4110. * This stores the margins, not the area. That may seem odd, but the idea is
  4111. * to make SetPlotAreaPixels and SetMarginsPixels two ways to accomplish the
  4112. * same thing, and the deferred calculations in CalcMargins and
  4113. * CalcPlotAreaPixels don't need to know which was used.
  4114. *
  4115. * @param int $x1 Top left corner X coordinate in pixels; omit or NULL to auto-calculate
  4116. * @param int $y1 Top left corner Y coordinate in pixels; omit or NULL to auto-calculate
  4117. * @param int $x2 Bottom right corner X coordinate in pixels; omit or NULL to auto-calculate
  4118. * @param int $y2 Bottom right corner Y coordinate in pixels; omit or NULL to auto-calculate
  4119. * @return bool True always
  4120. */
  4121. function SetPlotAreaPixels($x1 = NULL, $y1 = NULL, $x2 = NULL, $y2 = NULL)
  4122. {
  4123. $this->x_left_margin = $x1;
  4124. $this->x_right_margin = isset($x2) ? $this->image_width - $x2 : NULL;
  4125. $this->y_top_margin = $y1;
  4126. $this->y_bot_margin = isset($y2) ? $this->image_height - $y2 : NULL;
  4127. return TRUE;
  4128. }
  4129. /**
  4130. * Calculates an appropriate tick increment in 'decimal' mode
  4131. *
  4132. * This is used by CalcStep(). It returns the largest value that is 1, 2, or 5
  4133. * times an integer power of 10, and which divides the data range into no fewer
  4134. * than min_ticks tick intervals.
  4135. *
  4136. * @param float $range The data range (max - min), already checked as > 0
  4137. * @param int $min_ticks Smallest number of intervals allowed, already checked > 0
  4138. * @return float The calculated tick increment
  4139. * @since 6.0.0
  4140. */
  4141. protected function CalcStep125($range, $min_ticks)
  4142. {
  4143. $v = log10($range / $min_ticks);
  4144. $vi = (int)floor($v);
  4145. $tick_step = pow(10, $vi);
  4146. $f = $v - $vi;
  4147. if ($f > 0.69897) $tick_step *= 5; // Note 0.69897 = log10(5)
  4148. elseif ($f > 0.301) $tick_step *= 2; // Note 0.30103 = log10(2), truncated to fix edge cases
  4149. return $tick_step;
  4150. }
  4151. /**
  4152. * Calculates an appropriate tick increment in 'date/time' mode
  4153. *
  4154. * This is used by CalcStep() when the axis values use date/time units.
  4155. * Unlike in CalcStep125(), there is no equation to compute this, so an array
  4156. * $datetime_steps is used. The values are "natural" time intervals, keeping
  4157. * the ratio between adjacent entries <= 2.5 (so that max_ticks <= 2.5*min_ticks).
  4158. * For seconds or minutes, it uses: 1 2 5 10 15 30. For hours, it uses 1 2 4 8 12
  4159. * 24 48 96 and 168 (=7 days). Above that, it falls back to CalcStep125 using days.
  4160. *
  4161. * @param float $range The data range (max - min), already checked as > 0
  4162. * @param int $min_ticks Smallest number of intervals allowed, already checked > 0
  4163. * @return int The calculated tick increment. This will always be >= 1 second
  4164. * @since 6.0.0
  4165. */
  4166. protected function CalcStepDatetime($range, $min_ticks)
  4167. {
  4168. static $datetime_steps = array(1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600,
  4169. 7200, 14400, 28800, 43200, 86400, 172800, 345600, 604800);
  4170. static $datetime_limit = 1512000; // 1 week times 2.5, in seconds.
  4171. if ($range < $min_ticks) {
  4172. $tick_step = 1; // Range is too small; minimum interval is 1 second.
  4173. } elseif (($tick_limit = $range / $min_ticks) <= $datetime_limit) {
  4174. // Find the biggest value in the table <= tick_limit (which is the
  4175. // exact interval which would give min_ticks steps):
  4176. foreach ($datetime_steps as $v) {
  4177. if ($v <= $tick_limit) $tick_step = $v;
  4178. else break;
  4179. }
  4180. } else {
  4181. // Use the numeric-mode algorithm to find a 1,2,5*10**n solution, in units of days.
  4182. $tick_step = $this->CalcStep125($range / 86400, $min_ticks) * 86400;
  4183. }
  4184. return $tick_step;
  4185. }
  4186. /**
  4187. * Calculates an appropriate tick increment in 'binary' mode
  4188. *
  4189. * This is used by CalcStep(). It returns the largest power of 2 that divides
  4190. * the range into at least min_ticks intervals.
  4191. * Note: This contains an ugly work-around to a round-off problem. Using
  4192. * floor(log2(2^N)) should produce N for all integer N, but with glibc, it turns
  4193. * out that log2(8) is slightly < 3, and similar for a few other values (64, 4096,
  4194. * 8192). So they truncate to N-1. Other tested values, and all negative values,
  4195. * and all values on Windows, were found to truncate with floor() in the right
  4196. * direction. The adjustment below makes all values N=-50 to 50 truncate correctly.
  4197. *
  4198. * @param float $range The data range (max - min), already checked as > 0
  4199. * @param int $min_ticks Smallest number of intervals allowed, already checked > 0
  4200. * @return float The calculated tick increment
  4201. * @since 6.0.0
  4202. */
  4203. protected function CalcStepBinary($range, $min_ticks)
  4204. {
  4205. $log2 = log($range / $min_ticks, 2);
  4206. if ($log2 > 0) $log2 *= 1.000001; // See note above
  4207. return pow(2, (int)floor($log2));
  4208. }
  4209. /**
  4210. * Calculates an ideal tick increment for a given range
  4211. *
  4212. * This is only used when neither Set[XY]TickIncrement nor SetNum[XY]Ticks was used.
  4213. *
  4214. * @param string $which Which axis to calculate for. Must be 'x' or 'y'
  4215. * @param float $range The data range (max - min), already checked as > 0
  4216. * @return float The tick increment, using one of 3 methods depending on the 'tick_mode'
  4217. * @since 6.0.0
  4218. */
  4219. protected function CalcStep($which, $range)
  4220. {
  4221. // Get tick control variables: min_ticks, tick_mode, tick_inc_integer.
  4222. extract($this->tickctl[$which]);
  4223. // If tick_mode is null, default to decimal mode unless the axis uses date/time formatting:
  4224. if (!isset($tick_mode)) {
  4225. if (isset($this->label_format[$which]['type']) && $this->label_format[$which]['type'] == 'time')
  4226. $tick_mode = 'date';
  4227. else
  4228. $tick_mode = 'decimal';
  4229. }
  4230. // Use proper mode to calculate the tick increment, with integer override option.
  4231. if ($tick_mode == 'date') {
  4232. $tick_step = $this->CalcStepDatetime($range, $min_ticks);
  4233. } elseif ($tick_inc_integer && $range <= $min_ticks) {
  4234. $tick_step = 1; // Whole integer ticks selected but range is too small.
  4235. } elseif ($tick_mode == 'binary') {
  4236. $tick_step = $this->CalcStepBinary($range, $min_ticks);
  4237. } else {
  4238. $tick_step = $this->CalcStep125($range, $min_ticks);
  4239. }
  4240. return $tick_step;
  4241. }
  4242. /**
  4243. * Initializes range variables for CalcPlotRange()
  4244. *
  4245. * This is a helper for CalcPlotRange(), which calls it 4 times, to initialize
  4246. * each end of the range for each axis. It also sets flags to indicate
  4247. * whether automatic adjustment of the range end is needed.
  4248. *
  4249. * @param float $plot_limit Reference to (possibly unset) plot_min_[xy] or plot_max_[xy]
  4250. * @param bool $implied True if this is the implied variable (X for vertical plots)
  4251. * @param float $data_limit Actual data limit at this end: one of min_x, max_x, etc.
  4252. * @return array Array with (initial value of the range limit, adjustment flag)
  4253. * @since 6.0.0
  4254. */
  4255. protected function CalcRangeInit(&$plot_limit, $implied, $data_limit)
  4256. {
  4257. if (isset($plot_limit) && $plot_limit !== '') {
  4258. // Use the user-supplied value, and do no further adjustments.
  4259. return array($plot_limit, FALSE);
  4260. }
  4261. // Start with the actual data range. Set adjustment flag TRUE unless the range was implied.
  4262. return array($data_limit, !$implied);
  4263. }
  4264. /**
  4265. * Checks for a positive plot area range, and adjust if necessary
  4266. *
  4267. * This makes sure that the X or Y plot range is positive. The tick increment and
  4268. * other calculations cannot handle negative or zero range, so we need to do
  4269. * something to prevent it. There are 2 general cases: 1) automatic range, and
  4270. * data is 'flat' (all same value). 2) One side of range given in
  4271. * SetPlotAreaWorld(), and all the data is on the wrong side of that.
  4272. *
  4273. * Note that values specified in SetPlotAreaWorld() are never adjusted, even if it
  4274. * means an empty plot (because all the data is outside the range).
  4275. *
  4276. * Called by CalcPlotRange() after CalcRangeInit() applies the defaults.
  4277. *
  4278. * @param string $which Which axis: 'x' or 'y', used only for reporting
  4279. * @param float $plot_min Reference variable for the low end limit, changed if necessary
  4280. * @param float $plot_max Reference variable for the high end limit, changed if necessary
  4281. * @param bool $adjust_min True means $plot_min was auto-calculated, and may be adjusted
  4282. * @param bool $adjust_max True means $plot_max was auto-calculated, and may be adjusted
  4283. * @return bool True (False on error if an error handler returns True)
  4284. * @since 6.0.0
  4285. */
  4286. protected function CheckPlotRange($which, &$plot_min, &$plot_max, $adjust_min, $adjust_max)
  4287. {
  4288. if ($plot_min < $plot_max)
  4289. return TRUE; // No adjustment needed.
  4290. // Bad range, plot_min >= plot_max, needs fixing.
  4291. if ($adjust_max && $adjust_min) {
  4292. // Both min and max are calculated, so either or both can be adjusted.
  4293. // It should not be possible that plot_min > plot_max here, but check it to be safe:
  4294. if ($plot_max != $plot_min)
  4295. return $this->PrintError("SetPlotAreaWorld(): Inverse auto $which range error");
  4296. if ($plot_max == 0.0) {
  4297. // All 0. Use the arbitrary range 0:10
  4298. $plot_max = 10;
  4299. } elseif ($plot_min > 0) {
  4300. // All same positive value. Use the range 0:10 (or larger).
  4301. $plot_min = 0;
  4302. $plot_max = max($plot_max, 10);
  4303. } else {
  4304. // All same negative value. Use the range -10:0 (or larger).
  4305. $plot_min = min($plot_min, -10);
  4306. $plot_max = 0;
  4307. }
  4308. } elseif ($adjust_max) { // Equivalent to: ($adjust_max && !$adjust_min)
  4309. // Max is calculated, min was set, so adjust max
  4310. if ($plot_min < 0) $plot_max = 0;
  4311. else $plot_max = $plot_min + 10;
  4312. } elseif ($adjust_min) { // Equivalent to: (!$adjust_max && $adjust_min)
  4313. // Min is calculated, max was set, so adjust min
  4314. if ($plot_max > 0) $plot_min = 0;
  4315. else $plot_min = $plot_max - 10;
  4316. } else { // Equivalent to: (!$adjust_max && !$adjust_min)
  4317. // Both limits are set. This should never happen, since SetPlotAreaWorld stops it.
  4318. return $this->PrintError("SetPlotAreaWorld(): Inverse $which range error");
  4319. }
  4320. return TRUE;
  4321. }
  4322. /**
  4323. * Gets the plot range end adjustment factor
  4324. *
  4325. * This is a helper for CalcPlotRange(). If $adjust is already set, it is left
  4326. * alone, otherwise it uses the current plot type to apply a default setting.
  4327. *
  4328. * @param string $which Which axis to calculate for. Must be 'x' or 'y'
  4329. * @param float $adjust Reference variable for the range end adjustment factor, NULL or already set
  4330. * @since 6.0.0
  4331. */
  4332. protected function GetRangeEndAdjust($which, &$adjust)
  4333. {
  4334. if (isset($adjust)) return; // Already set, nothing to do
  4335. // The plot type can customize how an end adjustment is applied:
  4336. if (empty(self::$plots[$this->plot_type]['adjust_type'])) {
  4337. // Default (adjust_type missing or 0) means pad the dependent variable axis only.
  4338. $adjust = ($which == 'x' XOR $this->datatype_swapped_xy) ? 0 : 0.03;
  4339. } else {
  4340. switch (self::$plots[$this->plot_type]['adjust_type']) {
  4341. case 1:
  4342. // Adjust type = 1 means add extra padding to both X and Y axis ends
  4343. $adjust = 0.03;
  4344. break;
  4345. case 2:
  4346. // Adjust type = 2 means do not add extra padding to either axis.
  4347. $adjust = 0;
  4348. break;
  4349. }
  4350. }
  4351. }
  4352. /**
  4353. * Calculates the plot range and tick increment for X or Y
  4354. *
  4355. * This is a helper for CalcPlotAreaWorld(). It returns the plot range (plot_min
  4356. * and plot_max), and the tick increment, for the X or Y axis. Priority is given
  4357. * to user-set values with SetPlotAreaWorld() and Set[XY]TickIncrement(), but if
  4358. * these were defaulted then values are automatically calculated.
  4359. *
  4360. * @param string $which Which axis to calculate for. Must be 'x' or 'y'
  4361. * @return float[] Array of (tick_increment, plot_min, plot_max) or FALSE on handled error
  4362. * @since 6.0.0
  4363. */
  4364. protected function CalcPlotRange($which)
  4365. {
  4366. // Independent variable is X in the usual vertical plots; Y in horizontal plots:
  4367. $independent_variable = ($this->datatype_swapped_xy XOR $which == 'x');
  4368. // 'implied' means this is a non-explicitly given independent variable, e.g. X in 'text-data'.
  4369. $implied = $this->datatype_implied && $independent_variable;
  4370. // Initialize the range (plot_min : plot_max) and get the adjustment flags:
  4371. list($plot_min, $adjust_min) =
  4372. $this->CalcRangeInit($this->{"plot_min_$which"}, $implied, $this->{"min_$which"});
  4373. list($plot_max, $adjust_max) =
  4374. $this->CalcRangeInit($this->{"plot_max_$which"}, $implied, $this->{"max_$which"});
  4375. // Get local copies of variables used for range adjustment: adjust_{mode,amount} zero_magnet
  4376. extract($this->rangectl[$which]);
  4377. $this->GetRangeEndAdjust($which, $adjust_amount); // Apply default to $adjust_amount if needed
  4378. // Get local copies of other variables for X or Y:
  4379. if ($which == 'x') {
  4380. $num_ticks = $this->num_x_ticks;
  4381. $tick_inc = $this->x_tick_inc_u;
  4382. // Tick anchor is only used in 'T' adjust mode, where no tick anchor means anchor at 0.
  4383. $tick_anchor = isset($this->x_tick_anchor) ? $this->x_tick_anchor : 0;
  4384. } else {
  4385. $num_ticks = $this->num_y_ticks;
  4386. $tick_inc = $this->y_tick_inc_u;
  4387. $tick_anchor = isset($this->y_tick_anchor) ? $this->y_tick_anchor : 0;
  4388. }
  4389. // Validate the range, which must be positive. Adjusts plot_min and plot_max if necessary.
  4390. if (!$this->CheckPlotRange($which, $plot_min, $plot_max, $adjust_min, $adjust_max))
  4391. return FALSE;
  4392. // Adjust the min and max values, if flagged above for adjustment.
  4393. // Notes: (zero_magnet / (1 - zero_magnet)) is just a way to map a control with range 0:1
  4394. // into the range 0:infinity (with zero_magnet==1 handled as a special case).
  4395. // (plot_max / (plot_max - plot_min)) compares the range after plot_min would be set
  4396. // to zero with the original range. Similar for negative data: (plot_min / (plot_min - plot_max))
  4397. // compares the range with plot_max=0 to the original range.
  4398. $range = $plot_max - $plot_min;
  4399. // When all data > 0, test to see if the zero magnet is strong enough to pull the min down to zero:
  4400. if ($adjust_min && $plot_min > 0 && $zero_magnet > 0 && ($zero_magnet == 1.0 ||
  4401. $plot_max / $range < $zero_magnet / (1 - $zero_magnet))) {
  4402. $plot_min = 0;
  4403. $range = $plot_max;
  4404. }
  4405. // Similar to above, but for negative data: zero magnet pulls max up to zero:
  4406. if ($adjust_max && $plot_max < 0 && $zero_magnet > 0 && ($zero_magnet == 1.0 ||
  4407. -$plot_min / $range < $zero_magnet / (1 - $zero_magnet))) {
  4408. $plot_max = 0;
  4409. $range = 0 - $plot_min;
  4410. }
  4411. // Calculate the tick increment, if it wasn't set using Set[XY]TickIncrement().
  4412. $num_ticks_override = FALSE;
  4413. if (empty($tick_inc)) {
  4414. if (empty($num_ticks)) {
  4415. // Calculate a reasonable tick increment, based on the current plot area limits
  4416. $tick_inc = $this->CalcStep($which, $range);
  4417. } else {
  4418. // Number of ticks was provided: use exactly that.
  4419. // Adjustment is below, after range is calculated using mode 'R':
  4420. $adjust_mode = 'R';
  4421. $num_ticks_override = TRUE;
  4422. }
  4423. }
  4424. // Adjust the lower bound, if necessary, using one of 3 modes:
  4425. if ($adjust_min && $plot_min != 0) {
  4426. // Mode 'R' and basis for other modes: Extend the limit by a percentage of the
  4427. // plot range, but only when the data is negative (to leave room below for labels).
  4428. if ($plot_min < 0)
  4429. $plot_min -= $adjust_amount * $range;
  4430. if ($adjust_mode == 'T') {
  4431. // Mode 'T': Adjust to previous tick mark, taking tick anchor into account.
  4432. $pm = $tick_anchor + $tick_inc * floor(($plot_min - $tick_anchor) / $tick_inc);
  4433. // Don't allow the tick anchor adjustment to result in the range end moving across 0:
  4434. $plot_min = (($plot_min >= 0) === ($pm >= 0)) ? $pm : 0;
  4435. } elseif ($adjust_mode == 'I') {
  4436. // Mode 'I': Adjust to previous integer:
  4437. $plot_min = floor($plot_min);
  4438. }
  4439. }
  4440. // Adjust the upper bound, if necessary, using one of 3 modes:
  4441. if ($adjust_max && $plot_max != 0) {
  4442. // Mode 'R' and basis for other modes: Extend the limit by a percentage of the
  4443. // plot range, but only when the max is positive (leaves room above for labels).
  4444. if ($plot_max > 0)
  4445. $plot_max += $adjust_amount * $range;
  4446. if ($adjust_mode == 'T') {
  4447. // Mode 'T': Adjust to next tick mark, taking tick anchor into account:
  4448. $pm = $tick_anchor + $tick_inc * ceil(($plot_max - $tick_anchor) / $tick_inc);
  4449. // Don't allow the tick anchor adjustment to result in the range end moving across 0:
  4450. $plot_max = (($plot_max >= 0) === ($pm >= 0)) ? $pm : 0;
  4451. } elseif ($adjust_mode == 'I') {
  4452. // Mode 'I': Adjustment to next higher integer.
  4453. $plot_max = ceil($plot_max);
  4454. }
  4455. }
  4456. // Calculate the tick increment for the case where number of ticks was given:
  4457. if ($num_ticks_override) {
  4458. $tick_inc = ($plot_max - $plot_min) / $num_ticks;
  4459. }
  4460. // Check log scale range - plot_min and plot_max must be > 0.
  4461. if ($which == 'y' && $this->yscale_type == 'log' || $which == 'x' && $this->xscale_type == 'log') {
  4462. if ($plot_min <= 0) $plot_min = 1;
  4463. if ($plot_max <= 0) {
  4464. // Note: Error message names the public function, not this function.
  4465. return $this->PrintError("SetPlotAreaWorld(): Invalid $which range for log scale");
  4466. }
  4467. }
  4468. // Final error check to ensure the range is positive.
  4469. if ($plot_min >= $plot_max) $plot_max = $plot_min + 1;
  4470. // Return the calculated values. (Note these get stored back into class variables.)
  4471. return array($tick_inc, $plot_min, $plot_max);
  4472. }
  4473. /**
  4474. * Calculates the World Coordinate limits of the plot area, and the tick increments
  4475. *
  4476. * This is called by DrawGraph(), after FindDataLimits() determines the data
  4477. * limits, to calculate the plot area scale and tick increments. The plot range
  4478. * and increment are related, which is why they are calculated together.
  4479. *
  4480. * The plot range variables (plot_min_x, plot_max_x, plot_min_y, plot_max_y) are
  4481. * calculated if necessary, then stored back into the object ('sticky' for
  4482. * multiple plots on an image).
  4483. *
  4484. * The tick increments (x_tick_inc, y_tick_inc) are calculated. These default to
  4485. * the user-set values (x_tick_inc_u, y_tick_inc_u) but we keep the effective
  4486. * values separate so that they can be recalculated for a second plot (which may
  4487. * have a different data range).
  4488. *
  4489. * @return bool True, unless an handled error occurred in a called function
  4490. * @since 5.0.5
  4491. */
  4492. protected function CalcPlotAreaWorld()
  4493. {
  4494. list($this->x_tick_inc, $this->plot_min_x, $this->plot_max_x) = $this->CalcPlotRange('x');
  4495. list($this->y_tick_inc, $this->plot_min_y, $this->plot_max_y) = $this->CalcPlotRange('y');
  4496. if ($this->GetCallback('debug_scale')) {
  4497. $this->DoCallback('debug_scale', __FUNCTION__, array(
  4498. 'plot_min_x' => $this->plot_min_x, 'plot_min_y' => $this->plot_min_y,
  4499. 'plot_max_x' => $this->plot_max_x, 'plot_max_y' => $this->plot_max_y,
  4500. 'x_tick_inc' => $this->x_tick_inc, 'y_tick_inc' => $this->y_tick_inc));
  4501. }
  4502. return isset($this->x_tick_inc, $this->y_tick_inc); // Pass thru FALSE return from CalcPlotRange()
  4503. }
  4504. /**
  4505. * Overrides automatic data scaling to device coordinates
  4506. *
  4507. * This fixes one or more ends of the range of the plot to specific
  4508. * value(s), given in World Coordinates.
  4509. * Any limit not set or set to NULL will be calculated in
  4510. * CalcPlotAreaWorld(). If both ends of either X or Y range are
  4511. * supplied, the range is validated to ensure min < max.
  4512. *
  4513. * @param float $xmin X data range minimum; omit or NULL to auto-calculate
  4514. * @param float $ymin Y data range minimum; omit or NULL to auto-calculate
  4515. * @param float $xmax X data range maximum; omit or NULL to auto-calculate
  4516. * @param float $ymax Y data range maximum; omit or NULL to auto-calculate
  4517. * @return bool True (False on error if an error handler returns True)
  4518. */
  4519. function SetPlotAreaWorld($xmin=NULL, $ymin=NULL, $xmax=NULL, $ymax=NULL)
  4520. {
  4521. $this->plot_min_x = $xmin;
  4522. $this->plot_max_x = $xmax;
  4523. $this->plot_min_y = $ymin;
  4524. $this->plot_max_y = $ymax;
  4525. if (isset($xmin) && isset($xmax) && $xmin >= $xmax) $bad = 'X';
  4526. elseif (isset($ymin) && isset($ymax) && $ymin >= $ymax) $bad = 'Y';
  4527. else return TRUE;
  4528. return $this->PrintError("SetPlotAreaWorld(): $bad range error - min >= max");
  4529. }
  4530. /**
  4531. * Calculates sizes of bars for bars and stackedbars plots
  4532. *
  4533. * This calculates the following class variables, which control the size and
  4534. * spacing of bars in vertical and horizontal 'bars' and 'stackedbars' plots:
  4535. * record_bar_width (allocated width for each bar, including gaps),
  4536. * actual_bar_width (actual drawn width of each bar), and
  4537. * bar_adjust_gap (gap on each side of each bar, 0 if they touch).
  4538. *
  4539. * Note that when $verticals is False, the bars are horizontal, but the same
  4540. * variable names are used. Think of "bar_width" as being the width if you
  4541. * are standing on the Y axis looking towards positive X.
  4542. *
  4543. * @param bool $stacked If true, this is a stacked bar plot (1 bar per group)
  4544. * @param bool $verticals If false, this is a horizontal bar plot
  4545. * @return bool True always
  4546. */
  4547. protected function CalcBarWidths($stacked, $verticals)
  4548. {
  4549. // group_width is the width of a group, including padding
  4550. if ($verticals) {
  4551. $group_width = $this->plot_area_width / $this->num_data_rows;
  4552. } else {
  4553. $group_width = $this->plot_area_height / $this->num_data_rows;
  4554. }
  4555. // Number of bar spaces in the group, including actual bars and bar_extra_space extra:
  4556. if ($stacked) {
  4557. $num_spots = 1 + $this->bar_extra_space;
  4558. } else {
  4559. $num_spots = $this->data_columns + $this->bar_extra_space;
  4560. }
  4561. // record_bar_width is the width of each bar's allocated area.
  4562. // If bar_width_adjust=1 this is the width of the bar, otherwise
  4563. // the bar is centered inside record_bar_width.
  4564. // The equation is:
  4565. // group_frac_width * group_width = record_bar_width * num_spots
  4566. $this->record_bar_width = $this->group_frac_width * $group_width / $num_spots;
  4567. // Note that the extra space due to group_frac_width and bar_extra_space will be
  4568. // evenly divided on each side of the group: the drawn bars are centered in the group.
  4569. // Within each bar's allocated space, if bar_width_adjust=1 the bar fills the
  4570. // space, otherwise it is centered.
  4571. // This is the actual drawn bar width:
  4572. $this->actual_bar_width = $this->record_bar_width * $this->bar_width_adjust;
  4573. // This is the gap on each side of the bar (0 if bar_width_adjust=1):
  4574. $this->bar_adjust_gap = ($this->record_bar_width - $this->actual_bar_width) / 2;
  4575. if ($this->GetCallback('debug_scale')) {
  4576. $this->DoCallback('debug_scale', __FUNCTION__, array(
  4577. 'record_bar_width' => $this->record_bar_width,
  4578. 'actual_bar_width' => $this->actual_bar_width,
  4579. 'bar_adjust_gap' => $this->bar_adjust_gap));
  4580. }
  4581. return TRUE;
  4582. }
  4583. /**
  4584. * Calculates the X and Y axis positions in world coordinates
  4585. *
  4586. * This validates or calculates the class variables x_axis_position and
  4587. * y_axis_position. Note x_axis_position is the Y value where the X axis
  4588. * goes; y_axis_position is the X value where the Y axis goes.
  4589. * If they were set by the user, they are used as-is, unless they are
  4590. * outside the data range. If they are not set, they are calculated here.
  4591. *
  4592. * For vertical plots, the X axis defaults to Y=0 if that is inside the plot
  4593. * range, else whichever of the top or bottom that has the smallest absolute
  4594. * value (that is, the value closest to 0). The Y axis defaults to the left
  4595. * edge. For horizontal plots, the axis roles and defaults are switched.
  4596. *
  4597. * @return bool True always
  4598. * @since 5.0.5
  4599. */
  4600. protected function CalcAxisPositions()
  4601. {
  4602. // Validate user-provided X axis position, or calculate a default if not provided:
  4603. if (isset($this->x_axis_position)) {
  4604. // Force user-provided X axis position to be within the plot range:
  4605. $this->x_axis_position = min(max($this->plot_min_y, $this->x_axis_position), $this->plot_max_y);
  4606. } elseif ($this->yscale_type == 'log') {
  4607. // Always use 1 for X axis position on log scale plots.
  4608. $this->x_axis_position = 1;
  4609. } elseif ($this->datatype_swapped_xy || $this->plot_min_y > 0) {
  4610. // Horizontal plot, or Vertical Plot with all Y > 0: Place X axis on the bottom.
  4611. $this->x_axis_position = $this->plot_min_y;
  4612. } elseif ($this->plot_max_y < 0) {
  4613. // Vertical plot with all Y < 0, so place the X axis at the top.
  4614. $this->x_axis_position = $this->plot_max_y;
  4615. } else {
  4616. // Vertical plot range includes Y=0, so place X axis at 0.
  4617. $this->x_axis_position = 0;
  4618. }
  4619. // Validate user-provided Y axis position, or calculate a default if not provided:
  4620. if (isset($this->y_axis_position)) {
  4621. // Force user-provided Y axis position to be within the plot range:
  4622. $this->y_axis_position = min(max($this->plot_min_x, $this->y_axis_position), $this->plot_max_x);
  4623. } elseif ($this->xscale_type == 'log') {
  4624. // Always use 1 for Y axis position on log scale plots.
  4625. $this->y_axis_position = 1;
  4626. } elseif (!$this->datatype_swapped_xy || $this->plot_min_x > 0) {
  4627. // Vertical plot, or Horizontal Plot with all X > 0: Place Y axis on left side.
  4628. $this->y_axis_position = $this->plot_min_x;
  4629. } elseif ($this->plot_max_x < 0) {
  4630. // Horizontal plot with all X < 0, so place the Y axis on the right side.
  4631. $this->y_axis_position = $this->plot_max_x;
  4632. } else {
  4633. // Horizontal plot range includes X=0: place Y axis at 0.
  4634. $this->y_axis_position = 0;
  4635. }
  4636. if ($this->GetCallback('debug_scale')) {
  4637. $this->DoCallback('debug_scale', __FUNCTION__, array(
  4638. 'x_axis_position' => $this->x_axis_position,
  4639. 'y_axis_position' => $this->y_axis_position));
  4640. }
  4641. return TRUE;
  4642. }
  4643. /**
  4644. * Calculates parameters for transforming world coordinates to pixel coordinates
  4645. *
  4646. * This calculates xscale, yscale, plot_origin_x, and plot_origin_y, which map
  4647. * world coordinate space into the plot area. These are used by xtr() and ytr()
  4648. *
  4649. * @return bool True always
  4650. */
  4651. protected function CalcTranslation()
  4652. {
  4653. if ($this->plot_max_x - $this->plot_min_x == 0) { // Check for div by 0
  4654. $this->xscale = 0;
  4655. } else {
  4656. if ($this->xscale_type == 'log') {
  4657. $this->xscale = $this->plot_area_width /
  4658. (log10($this->plot_max_x) - log10($this->plot_min_x));
  4659. } else {
  4660. $this->xscale = $this->plot_area_width / ($this->plot_max_x - $this->plot_min_x);
  4661. }
  4662. }
  4663. if ($this->plot_max_y - $this->plot_min_y == 0) { // Check for div by 0
  4664. $this->yscale = 0;
  4665. } else {
  4666. if ($this->yscale_type == 'log') {
  4667. $this->yscale = $this->plot_area_height /
  4668. (log10($this->plot_max_y) - log10($this->plot_min_y));
  4669. } else {
  4670. $this->yscale = $this->plot_area_height / ($this->plot_max_y - $this->plot_min_y);
  4671. }
  4672. }
  4673. // GD defines x = 0 at left and y = 0 at TOP so -/+ respectively
  4674. if ($this->xscale_type == 'log') {
  4675. $this->plot_origin_x = $this->plot_area[0] - ($this->xscale * log10($this->plot_min_x) );
  4676. } else {
  4677. $this->plot_origin_x = $this->plot_area[0] - ($this->xscale * $this->plot_min_x);
  4678. }
  4679. if ($this->yscale_type == 'log') {
  4680. $this->plot_origin_y = $this->plot_area[3] + ($this->yscale * log10($this->plot_min_y));
  4681. } else {
  4682. $this->plot_origin_y = $this->plot_area[3] + ($this->yscale * $this->plot_min_y);
  4683. }
  4684. // Convert axis positions to device coordinates:
  4685. $this->y_axis_x_pixels = $this->xtr($this->y_axis_position);
  4686. $this->x_axis_y_pixels = $this->ytr($this->x_axis_position);
  4687. if ($this->GetCallback('debug_scale')) {
  4688. $this->DoCallback('debug_scale', __FUNCTION__, array(
  4689. 'xscale' => $this->xscale, 'yscale' => $this->yscale,
  4690. 'plot_origin_x' => $this->plot_origin_x, 'plot_origin_y' => $this->plot_origin_y,
  4691. 'y_axis_x_pixels' => $this->y_axis_x_pixels,
  4692. 'x_axis_y_pixels' => $this->x_axis_y_pixels));
  4693. }
  4694. return TRUE;
  4695. }
  4696. /**
  4697. * Translates an X world coordinate value into a pixel coordinate value
  4698. *
  4699. * @param float $x_world X world coordinate value to translate
  4700. * @return int Translated X device (pixel) coordinate
  4701. * @deprecated Public use discouraged; use GetDeviceXY() instead
  4702. */
  4703. function xtr($x_world)
  4704. {
  4705. if ($this->xscale_type == 'log') {
  4706. $x_pixels = $this->plot_origin_x + log10($x_world) * $this->xscale ;
  4707. } else {
  4708. $x_pixels = $this->plot_origin_x + $x_world * $this->xscale ;
  4709. }
  4710. return round($x_pixels);
  4711. }
  4712. /**
  4713. * Translates a Y world coordinate value into a pixel coordinate value
  4714. *
  4715. * @param float $y_world Y world coordinate value to translate
  4716. * @return int Translated Y device (pixel) coordinate
  4717. * @deprecated Public use discouraged; use GetDeviceXY() instead
  4718. */
  4719. function ytr($y_world)
  4720. {
  4721. if ($this->yscale_type == 'log') {
  4722. //minus because GD defines y = 0 at top. doh!
  4723. $y_pixels = $this->plot_origin_y - log10($y_world) * $this->yscale ;
  4724. } else {
  4725. $y_pixels = $this->plot_origin_y - $y_world * $this->yscale ;
  4726. }
  4727. return round($y_pixels);
  4728. }
  4729. /**
  4730. * Translates world coordinates into device coordinates
  4731. *
  4732. * This is a public interface to xtr() and ytr(), which are left as public
  4733. * for historical reasons but deprecated for public use. It maps (x,y) in
  4734. * world coordinates to (x,y) into device (pixel) coordinates. Typical usage
  4735. * is: list($x_pixel, $y_pixel) = $plot->GetDeviceXY($x_world, $y_world)
  4736. *
  4737. * Note: This only works after scaling has been set up, which happens in
  4738. * DrawGraph(). So it is only useful from a drawing callback, or if
  4739. * SetPrintImage(False) was used and after DrawGraph().
  4740. *
  4741. * @param float $x_world X world coordinate value to translate
  4742. * @param float $y_world Y world coordinate value to translate
  4743. * @return int[] Array of ($x, $y) device coordinates; False on error if error handler returns True
  4744. * @since 5.1.0
  4745. */
  4746. function GetDeviceXY($x_world, $y_world)
  4747. {
  4748. if (!isset($this->xscale)) {
  4749. return $this->PrintError("GetDeviceXY() was called before translation factors were calculated");
  4750. }
  4751. return array($this->xtr($x_world), $this->ytr($y_world));
  4752. }
  4753. /**
  4754. * Gets the tick mark parameters
  4755. *
  4756. * This is used by DrawXTicks(), DrawYTicks(), and CalcMaxTickLabelSize().
  4757. * It returns the parameters needed to draw tick marks: start value, end value,
  4758. * and step. Note CalcTicks() used to but no longer actually does the
  4759. * calculations. That is done in CalcPlotAreaWorld().
  4760. *
  4761. * @param string $which Which axis to calculate tick parameters for. Must be 'x' or 'y'
  4762. * @return float[] Array of (tick_start, tick_end, tick_step)
  4763. * @since 5.0.5
  4764. */
  4765. protected function CalcTicks($which)
  4766. {
  4767. if ($which == 'x') {
  4768. $tick_step = $this->x_tick_inc;
  4769. $anchor = &$this->x_tick_anchor; // Reference used because it might not be set.
  4770. $plot_max = $this->plot_max_x;
  4771. $plot_min = $this->plot_min_x;
  4772. $skip_lo = $this->skip_left_tick;
  4773. $skip_hi = $this->skip_right_tick;
  4774. } else { // Assumed 'y'
  4775. $tick_step = $this->y_tick_inc;
  4776. $anchor = &$this->y_tick_anchor;
  4777. $plot_max = $this->plot_max_y;
  4778. $plot_min = $this->plot_min_y;
  4779. $skip_lo = $this->skip_bottom_tick;
  4780. $skip_hi = $this->skip_top_tick;
  4781. }
  4782. // To avoid losing a final tick mark due to round-off errors, push tick_end out slightly.
  4783. $tick_start = (double)$plot_min;
  4784. $tick_end = (double)$plot_max + ($plot_max - $plot_min) / 10000.0;
  4785. // If a tick anchor was given, adjust the start of the range so the anchor falls
  4786. // at an exact tick mark (or would, if it was within range).
  4787. if (isset($anchor))
  4788. $tick_start = $anchor - $tick_step * floor(($anchor - $tick_start) / $tick_step);
  4789. // Lastly, adjust for option to skip left/bottom or right/top tick marks:
  4790. if ($skip_lo)
  4791. $tick_start += $tick_step;
  4792. if ($skip_hi)
  4793. $tick_end -= $tick_step;
  4794. if ($this->GetCallback('debug_scale'))
  4795. $this->DoCallback('debug_scale', __FUNCTION__,
  4796. compact('which', 'tick_start', 'tick_end', 'tick_step'));
  4797. return array($tick_start, $tick_end, $tick_step);
  4798. }
  4799. /**
  4800. * Calculates the size of the biggest tick label
  4801. *
  4802. * This is used by CalcMargins() to figure out how much margin space is needed
  4803. * for the tick labels.
  4804. * For 'x' ticks, it returns the height (delta Y) of the tallest label.
  4805. * For 'y' ticks, it returns the width (delta X) of the widest label.
  4806. *
  4807. * @param string $which Which axis to calculate for. Must be 'x' or 'y'
  4808. * @return float The needed tick label width (for Y) or height (for X)
  4809. * @since 5.0.5
  4810. */
  4811. protected function CalcMaxTickLabelSize($which)
  4812. {
  4813. list($tick_start, $tick_end, $tick_step) = $this->CalcTicks($which);
  4814. $angle = ($which == 'x') ? $this->x_label_angle : $this->y_label_angle;
  4815. $font_id = $which . '_label'; // Use x_label or y_label font.
  4816. $max_width = 0;
  4817. $max_height = 0;
  4818. // Loop over ticks, same as DrawXTicks and DrawYTicks:
  4819. // Avoid cumulative round-off errors from $val += $delta
  4820. $n = 0;
  4821. $tick_val = $tick_start;
  4822. while ($tick_val <= $tick_end) {
  4823. $tick_label = $this->FormatLabel($which, $tick_val);
  4824. list($width, $height) = $this->SizeText($font_id, $angle, $tick_label);
  4825. if ($width > $max_width) $max_width = $width;
  4826. if ($height > $max_height) $max_height = $height;
  4827. $tick_val = $tick_start + ++$n * $tick_step;
  4828. }
  4829. if ($this->GetCallback('debug_scale')) {
  4830. $this->DoCallback('debug_scale', __FUNCTION__, array(
  4831. 'which' => $which, 'height' => $max_height, 'width' => $max_width));
  4832. }
  4833. if ($which == 'x')
  4834. return $max_height;
  4835. return $max_width;
  4836. }
  4837. /**
  4838. * Calculates the size of the biggest axis data label
  4839. *
  4840. * This is used by CalcMargins() to figure out how much margin space is needed
  4841. * for the axis data labels.
  4842. * For X axis labels, it returns the height (delta Y) of the tallest label.
  4843. * For Y axis labels, it returns the width (delta X) of the widest label.
  4844. *
  4845. * There can be at most one set of axis data labels. For vertical plots, these
  4846. * are X axis data labels, and go along the top or bottom or both. For horizontal
  4847. * plots, these are Y axis data labels, and go along the left or right or both.
  4848. * CalcMaxDataLabelSize(axis) returns 0 if data labels do not apply to that axis.
  4849. * To do this, it needs to check the plottype flag indicating swapped X/Y.
  4850. *
  4851. * @param string $which Which axis to calculate for. Must be 'x' or 'y'
  4852. * @return float The needed axis data label width (for Y) or height (for X)
  4853. * @since 5.0.5
  4854. */
  4855. protected function CalcMaxDataLabelSize($which = 'x')
  4856. {
  4857. // Shortcut: Y data labels for vertical plots, and X data labels for horizontal plots,
  4858. // are inside the plot, rather than along the axis lines, and so take up no margin space.
  4859. if ($which == 'y' XOR $this->datatype_swapped_xy)
  4860. return 0;
  4861. $angle = ($which == 'x') ? $this->x_data_label_angle : $this->y_data_label_angle;
  4862. $font_id = $which . '_label'; // Use x_label or y_label font.
  4863. $format_code = $which . 'd'; // Use format code 'xd' or 'yd'
  4864. $max_width = 0;
  4865. $max_height = 0;
  4866. // Loop over all data labels and find the biggest:
  4867. for ($i = 0; $i < $this->num_data_rows; $i++) {
  4868. $label = $this->FormatLabel($format_code, $this->data[$i][0], $i);
  4869. list($width, $height) = $this->SizeText($font_id, $angle, $label);
  4870. if ($width > $max_width) $max_width = $width;
  4871. if ($height > $max_height) $max_height = $height;
  4872. }
  4873. if ($this->GetCallback('debug_scale')) {
  4874. $this->DoCallback('debug_scale', __FUNCTION__, array(
  4875. 'height' => $max_height, 'width' => $max_width));
  4876. }
  4877. if ($this->datatype_swapped_xy)
  4878. return $max_width;
  4879. return $max_height;
  4880. }
  4881. /**
  4882. * Determines if there are any non-empty data labels in the data array
  4883. *
  4884. * This is used by CheckLabels() to determine if data labels are available.
  4885. *
  4886. * @return bool True if all data labels are empty, else False.
  4887. * @since 5.1.2
  4888. */
  4889. protected function CheckLabelsAllEmpty()
  4890. {
  4891. for ($i = 0; $i < $this->num_data_rows; $i++)
  4892. if ($this->data[$i][0] !== '') return FALSE;
  4893. return TRUE;
  4894. }
  4895. /**
  4896. * Checks and sets label parameters
  4897. *
  4898. * This handles deferred processing for label positioning and other label-related
  4899. * parameters. It sets defaults for label angles, and applies defaults to X and Y
  4900. * tick and data label positions.
  4901. *
  4902. * @return bool True always
  4903. * @since 5.1.0
  4904. */
  4905. protected function CheckLabels()
  4906. {
  4907. // Default for X data label angle is a special case (different from Y).
  4908. if ($this->x_data_label_angle_u === '')
  4909. $this->x_data_label_angle = $this->x_label_angle; // Not set with SetXDataLabelAngle()
  4910. else
  4911. $this->x_data_label_angle = $this->x_data_label_angle_u; // Set with SetXDataLabelAngle()
  4912. // X Label position fixups, for x_data_label_pos and x_tick_label_pos:
  4913. if ($this->datatype_swapped_xy) {
  4914. // Just apply defaults - there is no position conflict for X labels.
  4915. if (!isset($this->x_tick_label_pos))
  4916. $this->x_tick_label_pos = 'plotdown';
  4917. if (!isset($this->x_data_label_pos))
  4918. $this->x_data_label_pos = 'none';
  4919. } else {
  4920. // Apply defaults but do not allow conflict between tick and data labels.
  4921. if (isset($this->x_data_label_pos)) {
  4922. if (!isset($this->x_tick_label_pos)) {
  4923. // Case: data_label_pos is set, tick_label_pos needs a default:
  4924. if ($this->x_data_label_pos == 'none')
  4925. $this->x_tick_label_pos = 'plotdown';
  4926. else
  4927. $this->x_tick_label_pos = 'none';
  4928. }
  4929. } elseif (isset($this->x_tick_label_pos)) {
  4930. // Case: tick_label_pos is set, data_label_pos needs a default:
  4931. if ($this->x_tick_label_pos == 'none')
  4932. $this->x_data_label_pos = 'plotdown';
  4933. else
  4934. $this->x_data_label_pos = 'none';
  4935. } else {
  4936. // Case: Neither tick_label_pos nor data_label_pos is set.
  4937. // We do not want them to be both on (as PHPlot used to do in this case).
  4938. // Turn on data labels if any were supplied, else tick labels.
  4939. if ($this->CheckLabelsAllEmpty()) {
  4940. $this->x_data_label_pos = 'none';
  4941. $this->x_tick_label_pos = 'plotdown';
  4942. } else {
  4943. $this->x_data_label_pos = 'plotdown';
  4944. $this->x_tick_label_pos = 'none';
  4945. }
  4946. }
  4947. }
  4948. // Y Label position fixups, for y_data_label_pos and y_tick_label_pos:
  4949. if (!$this->datatype_swapped_xy) {
  4950. // Just apply defaults - there is no position conflict.
  4951. if (!isset($this->y_tick_label_pos))
  4952. $this->y_tick_label_pos = 'plotleft';
  4953. if (!isset($this->y_data_label_pos))
  4954. $this->y_data_label_pos = 'none';
  4955. } else {
  4956. // Apply defaults but do not allow conflict between tick and data labels.
  4957. if (isset($this->y_data_label_pos)) {
  4958. if (!isset($this->y_tick_label_pos)) {
  4959. // Case: data_label_pos is set, tick_label_pos needs a default:
  4960. if ($this->y_data_label_pos == 'none')
  4961. $this->y_tick_label_pos = 'plotleft';
  4962. else
  4963. $this->y_tick_label_pos = 'none';
  4964. }
  4965. } elseif (isset($this->y_tick_label_pos)) {
  4966. // Case: tick_label_pos is set, data_label_pos needs a default:
  4967. if ($this->y_tick_label_pos == 'none')
  4968. $this->y_data_label_pos = 'plotleft';
  4969. else
  4970. $this->y_data_label_pos = 'none';
  4971. } else {
  4972. // Case: Neither tick_label_pos nor data_label_pos is set.
  4973. // Turn on data labels if any were supplied, else tick labels.
  4974. if ($this->CheckLabelsAllEmpty()) {
  4975. $this->y_data_label_pos = 'none';
  4976. $this->y_tick_label_pos = 'plotleft';
  4977. } else {
  4978. $this->y_data_label_pos = 'plotleft';
  4979. $this->y_tick_label_pos = 'none';
  4980. }
  4981. }
  4982. }
  4983. return TRUE;
  4984. }
  4985. /**
  4986. * Formats a value for use as a tick, data, or pie chart label
  4987. *
  4988. * @param string $which_pos Which format controls to use: x | y | xd | yd | p (tick, data, pie)
  4989. * @param mixed $which_lab The value of the label to be formatted (usually a float)
  4990. * @param mixed $varargs Zero or more additional arguments to pass to a custom format function
  4991. * @return string The formatted label value (original value if no formatting is enabled)
  4992. */
  4993. protected function FormatLabel($which_pos, $which_lab, $varargs=NULL) // Variable additional arguments
  4994. {
  4995. // Assign a reference shortcut to the label format controls, default xd,yd to x,y.
  4996. if ($which_pos == 'xd' && empty($this->label_format['xd']))
  4997. $which_pos = 'x';
  4998. elseif ($which_pos == 'yd' && empty($this->label_format['yd']))
  4999. $which_pos = 'y';
  5000. $format = &$this->label_format[$which_pos];
  5001. // Don't format empty strings (especially as time or numbers), or if no type was set.
  5002. if ($which_lab !== '' && !empty($format['type'])) {
  5003. switch ($format['type']) {
  5004. case 'title': // Note: This is obsolete
  5005. $which_lab = @ $this->data[$which_lab][0];
  5006. break;
  5007. case 'data':
  5008. $which_lab = $format['prefix']
  5009. . $this->number_format($which_lab, $format['precision'])
  5010. . $this->data_units_text // Obsolete
  5011. . $format['suffix'];
  5012. break;
  5013. case 'time':
  5014. $which_lab = strftime($format['time_format'], $which_lab);
  5015. break;
  5016. case 'printf':
  5017. if (!is_array($format['printf_format'])) {
  5018. $use_format = $format['printf_format'];
  5019. } else {
  5020. // Select from 1, 2, or 3 formats based on the sign of the value (like spreadsheets).
  5021. // With 2 formats, use [0] for >= 0, [1] for < 0.
  5022. // With 3 formats, use [0] for > 0, [1] for < 0, [2] for = 0.
  5023. $n_formats = count($format['printf_format']);
  5024. if ($n_formats == 3 && $which_lab == 0) {
  5025. $use_format = $format['printf_format'][2];
  5026. } elseif ($n_formats > 1 && $which_lab < 0) {
  5027. $use_format = $format['printf_format'][1];
  5028. $which_lab = -$which_lab; // Format the absolute value
  5029. } else $use_format = $format['printf_format'][0];
  5030. }
  5031. $which_lab = sprintf($use_format, $which_lab);
  5032. break;
  5033. case 'custom':
  5034. // Build argument vector: (text, custom_callback_arg, other_args...)
  5035. $argv = func_get_args();
  5036. $argv[0] = $which_lab;
  5037. $argv[1] = $format['custom_arg'];
  5038. $which_lab = call_user_func_array($format['custom_callback'], $argv);
  5039. break;
  5040. }
  5041. }
  5042. return $which_lab;
  5043. }
  5044. /**
  5045. * Sets range tuning parameters for X or Y
  5046. *
  5047. * This implements TuneXAutoRange() and TuneYAutoRange(). Note that
  5048. * parameter values are checked, but invalid values are silently ignored.
  5049. *
  5050. * @param string $which Which axis to adjust parameters for: 'x' or 'y'
  5051. * @param float $zero_magnet Zero magnet value, NULL to ignore
  5052. * @param string $adjust_mode Range extension mode, NULL to ignore
  5053. * @param float $adjust_amount Range extension amount, NULL to ignore
  5054. * @return bool True always
  5055. * @since 6.0.0
  5056. */
  5057. protected function TuneAutoRange($which, $zero_magnet, $adjust_mode, $adjust_amount)
  5058. {
  5059. if (isset($zero_magnet) && $zero_magnet >= 0 && $zero_magnet <= 1.0)
  5060. $this->rangectl[$which]['zero_magnet'] = $zero_magnet;
  5061. if (isset($adjust_mode) && strpos('TRI', $adjust_mode[0]) !== FALSE)
  5062. $this->rangectl[$which]['adjust_mode'] = $adjust_mode;
  5063. if (isset($adjust_amount) && $adjust_amount >= 0)
  5064. $this->rangectl[$which]['adjust_amount'] = $adjust_amount;
  5065. return TRUE;
  5066. }
  5067. /**
  5068. * Adjusts tuning parameters for X axis range calculation
  5069. *
  5070. * See TuneAutoRange() above, which implements this function.
  5071. *
  5072. * @param float $zero_magnet Optional X axis zero magnet value, controlling range extension to include 0
  5073. * @param string $adjust_mode Optional X axis range extension mode: T | R | I (Tick, Range, Integer)
  5074. * @param float $adjust_amount Optional X axis range extension amount
  5075. * @return bool True always
  5076. * @since 6.0.0
  5077. */
  5078. function TuneXAutoRange($zero_magnet = NULL, $adjust_mode = NULL, $adjust_amount = NULL)
  5079. {
  5080. return $this->TuneAutoRange('x', $zero_magnet, $adjust_mode, $adjust_amount);
  5081. }
  5082. /**
  5083. * Adjusts tuning parameters for Y axis range calculation
  5084. *
  5085. * See TuneAutoRange() above, which implements this function.
  5086. *
  5087. * @param float $zero_magnet Optional Y axis zero magnet value, controlling range extension to include 0
  5088. * @param string $adjust_mode Optional Y axis range extension mode: T | R | I (Tick, Range, Integer)
  5089. * @param float $adjust_amount Optional Y axis range extension amount
  5090. * @return bool True always
  5091. * @since 6.0.0
  5092. */
  5093. function TuneYAutoRange($zero_magnet = NULL, $adjust_mode = NULL, $adjust_amount = NULL)
  5094. {
  5095. return $this->TuneAutoRange('y', $zero_magnet, $adjust_mode, $adjust_amount);
  5096. }
  5097. /**
  5098. * Sets tick tuning parameters for X or Y
  5099. *
  5100. * This implements TuneXAutoTicks() and TuneYAutoTicks().
  5101. *
  5102. * @param string $which Which axis to adjust parameters for: 'x' or 'y'
  5103. * @param int $min_ticks Minimum number of tick intervals
  5104. * @param string $tick_mode Tick increment calculation mode
  5105. * @param bool $tick_inc_integer True to always use integer tick increments
  5106. * @return bool True (False on error if an error handler returns True)
  5107. * @since 6.0.0
  5108. */
  5109. protected function TuneAutoTicks($which, $min_ticks, $tick_mode, $tick_inc_integer)
  5110. {
  5111. if (isset($min_ticks) && $min_ticks > 0)
  5112. $this->tickctl[$which]['min_ticks'] = (integer)$min_ticks;
  5113. if (isset($tick_mode)) {
  5114. $tick_mode = $this->CheckOption($tick_mode, 'decimal, binary, date',
  5115. 'Tune' . strtoupper($which) . 'AutoTicks');
  5116. if (!$tick_mode)
  5117. return FALSE;
  5118. $this->tickctl[$which]['tick_mode'] = $tick_mode;
  5119. }
  5120. if (isset($tick_inc_integer))
  5121. $this->tickctl[$which]['tick_inc_integer'] = (bool)$tick_inc_integer;
  5122. return TRUE;
  5123. }
  5124. /**
  5125. * Adjusts tuning parameters for X axis tick increment calculation
  5126. *
  5127. * See TuneAutoTicks() above, which implements this function.
  5128. *
  5129. * @param int $min_ticks Minimum number of tick intervals along the axis
  5130. * @param string $tick_mode Tick increment calculation mode: decimal | binary | date
  5131. * @param bool $tick_inc_integer True to always use integer tick increments, false to allow fractions
  5132. * @return bool True (False on error if an error handler returns True)
  5133. * @since 6.0.0
  5134. */
  5135. function TuneXAutoTicks($min_ticks = NULL, $tick_mode = NULL, $tick_inc_integer = NULL)
  5136. {
  5137. return $this->TuneAutoTicks('x', $min_ticks, $tick_mode, $tick_inc_integer);
  5138. }
  5139. /**
  5140. * Adjusts tuning parameters for Y axis tick increment calculation
  5141. *
  5142. * See TuneAutoTicks() above, which implements this function.
  5143. *
  5144. * @param int $min_ticks Minimum number of tick intervals along the axis
  5145. * @param string $tick_mode Tick increment calculation mode: decimal | binary | date
  5146. * @param bool $tick_inc_integer True to always use integer tick increments, false to allow fractions
  5147. * @return bool True (False on error if an error handler returns True)
  5148. * @since 6.0.0
  5149. */
  5150. function TuneYAutoTicks($min_ticks = NULL, $tick_mode = NULL, $tick_inc_integer = NULL)
  5151. {
  5152. return $this->TuneAutoTicks('y', $min_ticks, $tick_mode, $tick_inc_integer);
  5153. }
  5154. /////////////////////////////////////////////
  5155. /////////////// TICKS
  5156. /////////////////////////////////////////////
  5157. /**
  5158. * Sets the length of the interval between X ticks
  5159. *
  5160. * @param float $which_ti X tick increment in world coordinates; omit or '' for default auto-calculate
  5161. * @return bool True always
  5162. */
  5163. function SetXTickIncrement($which_ti='')
  5164. {
  5165. $this->x_tick_inc_u = $which_ti;
  5166. return TRUE;
  5167. }
  5168. /**
  5169. * Sets the length of the interval between Y ticks
  5170. *
  5171. * @param float $which_ti Y tick increment in world coordinates; omit or '' for default auto-calculate
  5172. * @return bool True always
  5173. */
  5174. function SetYTickIncrement($which_ti='')
  5175. {
  5176. $this->y_tick_inc_u = $which_ti;
  5177. return TRUE;
  5178. }
  5179. /**
  5180. * Sets the number of X tick intervals
  5181. *
  5182. * @param int $which_nt Number of X tick intervals; omit or '' for default auto-calculate
  5183. * @return bool True always
  5184. */
  5185. function SetNumXTicks($which_nt='')
  5186. {
  5187. $this->num_x_ticks = $which_nt;
  5188. return TRUE;
  5189. }
  5190. /**
  5191. * Sets the number of Y tick intervals
  5192. *
  5193. * @param int $which_nt Number of Y tick intervals; omit or '' for default auto-calculate
  5194. * @return bool True always
  5195. */
  5196. function SetNumYTicks($which_nt='')
  5197. {
  5198. $this->num_y_ticks = $which_nt;
  5199. return TRUE;
  5200. }
  5201. /**
  5202. * Positions the X tick marks (above the plot, below, both above and below; at the X axis, or suppressed)
  5203. *
  5204. * @param string $which_tp Tick mark position: plotdown | plotup | both | xaxis | none
  5205. * @return bool True (False on error if an error handler returns True)
  5206. */
  5207. function SetXTickPos($which_tp)
  5208. {
  5209. $this->x_tick_pos = $this->CheckOption($which_tp, 'plotdown, plotup, both, xaxis, none',
  5210. __FUNCTION__);
  5211. return (boolean)$this->x_tick_pos;
  5212. }
  5213. /**
  5214. * Positions the Y tick marks (left, right, or both sides; at the Y axis, or suppressed)
  5215. *
  5216. * @param string $which_tp Tick mark position: plotleft | plotright | both | yaxis | none
  5217. * @return bool True (False on error if an error handler returns True)
  5218. */
  5219. function SetYTickPos($which_tp)
  5220. {
  5221. $this->y_tick_pos = $this->CheckOption($which_tp, 'plotleft, plotright, both, yaxis, none',
  5222. __FUNCTION__);
  5223. return (boolean)$this->y_tick_pos;
  5224. }
  5225. /**
  5226. * Suppress the top Y axis tick mark and label
  5227. *
  5228. * @param bool $skip True to skip the tick mark and label; false to draw them
  5229. * @return bool True always
  5230. */
  5231. function SetSkipTopTick($skip)
  5232. {
  5233. $this->skip_top_tick = (bool)$skip;
  5234. return TRUE;
  5235. }
  5236. /**
  5237. * Suppress the bottom Y axis tick mark and label
  5238. *
  5239. * @param bool $skip True to skip the tick mark and label; false to draw them
  5240. * @return bool True always
  5241. */
  5242. function SetSkipBottomTick($skip)
  5243. {
  5244. $this->skip_bottom_tick = (bool)$skip;
  5245. return TRUE;
  5246. }
  5247. /**
  5248. * Suppress the left-most (first) X axis tick mark and label
  5249. *
  5250. * @param bool $skip True to skip the tick mark and label; false to draw them
  5251. * @return bool True always
  5252. */
  5253. function SetSkipLeftTick($skip)
  5254. {
  5255. $this->skip_left_tick = (bool)$skip;
  5256. return TRUE;
  5257. }
  5258. /**
  5259. * Suppress the right-most (last) X axis tick mark and label
  5260. *
  5261. * @param bool $skip True to skip the tick mark and label; false to draw them
  5262. * @return bool True always
  5263. */
  5264. function SetSkipRightTick($skip)
  5265. {
  5266. $this->skip_right_tick = (bool)$skip;
  5267. return TRUE;
  5268. }
  5269. /**
  5270. * Sets the outer length of X tick marks (the part that sticks out from the plot area)
  5271. *
  5272. * @param int $which_xln Outer length of the tick marks, in pixels
  5273. * @return bool True always
  5274. */
  5275. function SetXTickLength($which_xln)
  5276. {
  5277. $this->x_tick_length = $which_xln;
  5278. return TRUE;
  5279. }
  5280. /**
  5281. * Sets the outer length of Y tick marks (the part that sticks out from the plot area)
  5282. *
  5283. * @param int $which_yln Outer length of the tick marks, in pixels
  5284. * @return bool True always
  5285. */
  5286. function SetYTickLength($which_yln)
  5287. {
  5288. $this->y_tick_length = $which_yln;
  5289. return TRUE;
  5290. }
  5291. /**
  5292. * Sets the crossing length of X tick marks (the part that sticks into the plot area)
  5293. *
  5294. * @param int $which_xc Crossing length of the tick marks, in pixels
  5295. * @return bool True always
  5296. */
  5297. function SetXTickCrossing($which_xc)
  5298. {
  5299. $this->x_tick_cross = $which_xc;
  5300. return TRUE;
  5301. }
  5302. /**
  5303. * Sets the crossing length of Y tick marks (the part that sticks into the plot area)
  5304. *
  5305. * @param int $which_yc Crossing length of the tick marks, in pixels
  5306. * @return bool True always
  5307. */
  5308. function SetYTickCrossing($which_yc)
  5309. {
  5310. $this->y_tick_cross = $which_yc;
  5311. return TRUE;
  5312. }
  5313. /**
  5314. * Sets an anchor point for X tick marks
  5315. *
  5316. * A tick anchor forces a tick mark at that exact value (if the data range were extended to include it).
  5317. *
  5318. * @param float $xta Tick anchor position in World Coordinates; omit or NULL for no anchor
  5319. * @return bool True always
  5320. * @since 5.4.0
  5321. */
  5322. function SetXTickAnchor($xta = NULL)
  5323. {
  5324. $this->x_tick_anchor = $xta;
  5325. return TRUE;
  5326. }
  5327. /**
  5328. * Sets an anchor point for Y tick marks
  5329. *
  5330. * A tick anchor forces a tick mark at that exact value (if the data range were extended to include it).
  5331. *
  5332. * @param float $yta Tick anchor position in World Coordinates; omit or NULL for no anchor
  5333. * @return bool True always
  5334. * @since 5.4.0
  5335. */
  5336. function SetYTickAnchor($yta = NULL)
  5337. {
  5338. $this->y_tick_anchor = $yta;
  5339. return TRUE;
  5340. }
  5341. /////////////////////////////////////////////
  5342. //////////////////// GENERIC DRAWING
  5343. /////////////////////////////////////////////
  5344. /**
  5345. * Fills the image background, with a tiled image file or solid color
  5346. *
  5347. * @param bool $overwrite True to do it even if already done, False or omit to do once only
  5348. * @return bool True always
  5349. */
  5350. protected function DrawBackground($overwrite=FALSE)
  5351. {
  5352. // Check if background should be drawn:
  5353. if (empty($this->done['background']) || $overwrite) {
  5354. if (isset($this->bgimg)) { // If bgimg is defined, use it
  5355. $this->tile_img($this->bgimg, 0, 0, $this->image_width, $this->image_height, $this->bgmode);
  5356. } else { // Else use solid color
  5357. ImageFilledRectangle($this->img, 0, 0, $this->image_width, $this->image_height,
  5358. $this->ndx_bg_color);
  5359. }
  5360. $this->done['background'] = TRUE;
  5361. }
  5362. return TRUE;
  5363. }
  5364. /**
  5365. * Fills the plot area background, with a tiled image file or solid color
  5366. *
  5367. * @return bool True always
  5368. */
  5369. protected function DrawPlotAreaBackground()
  5370. {
  5371. if (isset($this->plotbgimg)) {
  5372. $this->tile_img($this->plotbgimg, $this->plot_area[0], $this->plot_area[1],
  5373. $this->plot_area_width, $this->plot_area_height, $this->plotbgmode);
  5374. } elseif ($this->draw_plot_area_background) {
  5375. ImageFilledRectangle($this->img, $this->plot_area[0], $this->plot_area[1],
  5376. $this->plot_area[2], $this->plot_area[3], $this->ndx_plot_bg_color);
  5377. }
  5378. return TRUE;
  5379. }
  5380. /**
  5381. * Tiles an image from a file onto the plot image (for backgrounds)
  5382. *
  5383. * @param string $file Filename of the picture to be used as tile
  5384. * @param int $xorig X device coordinate of where the tile is to begin
  5385. * @param int $yorig Y device coordinate of where the tile is to begin
  5386. * @param int $width Width of the area to be tiled
  5387. * @param int $height Height of the area to be tiled
  5388. * @param string $mode Tiling mode: centeredtile | tile | scale
  5389. * @return bool True (False on error if an error handler returns True)
  5390. *
  5391. */
  5392. protected function tile_img($file, $xorig, $yorig, $width, $height, $mode)
  5393. {
  5394. $im = $this->GetImage($file, $tile_width, $tile_height);
  5395. if (!$im)
  5396. return FALSE; // GetImage already produced an error message.
  5397. if ($mode == 'scale') {
  5398. imagecopyresampled($this->img, $im, $xorig, $yorig, 0, 0, $width, $height,
  5399. $tile_width, $tile_height);
  5400. return TRUE;
  5401. }
  5402. if ($mode == 'centeredtile') {
  5403. $x0 = - floor($tile_width/2); // Make the tile look better
  5404. $y0 = - floor($tile_height/2);
  5405. } else { // Accept anything else as $mode == 'tile'
  5406. $x0 = 0;
  5407. $y0 = 0;
  5408. }
  5409. // Draw the tile onto a temporary image first.
  5410. $tmp = imagecreate($width, $height);
  5411. if (! $tmp)
  5412. return $this->PrintError('tile_img(): Could not create image resource.');
  5413. for ($x = $x0; $x < $width; $x += $tile_width)
  5414. for ($y = $y0; $y < $height; $y += $tile_height)
  5415. imagecopy($tmp, $im, $x, $y, 0, 0, $tile_width, $tile_height);
  5416. // Copy the temporary image onto the final one.
  5417. imagecopy($this->img, $tmp, $xorig, $yorig, 0,0, $width, $height);
  5418. // Free resources
  5419. imagedestroy($tmp);
  5420. imagedestroy($im);
  5421. return TRUE;
  5422. }
  5423. /**
  5424. * Returns the width of the image border, for CalcMargins() and DrawImageBorder().
  5425. *
  5426. * @return int Border width in pixels, 0 for no borders
  5427. * @since 5.1.2
  5428. */
  5429. protected function GetImageBorderWidth()
  5430. {
  5431. if ($this->image_border_type == 'none')
  5432. return 0; // No border
  5433. if (!empty($this->image_border_width))
  5434. return $this->image_border_width; // Specified border width
  5435. if ($this->image_border_type == 'raised')
  5436. return 2; // Default for raised border is 2 pixels.
  5437. return 1; // Default for other border types is 1 pixel.
  5438. }
  5439. /**
  5440. * Draws a border around the final image
  5441. *
  5442. * This draws a border around the image, if enabled by SetImageBorderType().
  5443. * Note: type 'plain' draws a flat border using the dark shade of the border color.
  5444. * This probably should have been written to use the actual border color, but
  5445. * it is too late to fix it without changing plot appearances. Therefore a
  5446. * new type 'solid' was added to use the SetImageBorderColor color.
  5447. *
  5448. * @param bool $overwrite True to do it even if already done, False or omit to do once only
  5449. * @return bool True (False on error if an error handler returns True)
  5450. *
  5451. */
  5452. protected function DrawImageBorder($overwrite=FALSE)
  5453. {
  5454. // Check if border should be drawn:
  5455. if ($this->image_border_type == 'none' || !(empty($this->done['border']) || $overwrite))
  5456. return TRUE;
  5457. $width = $this->GetImageBorderWidth();
  5458. $color1 = $this->ndx_i_border;
  5459. $color2 = $this->ndx_i_border_dark;
  5460. $ex = $this->image_width - 1;
  5461. $ey = $this->image_height - 1;
  5462. switch ($this->image_border_type) {
  5463. case 'raised':
  5464. // Top and left lines use border color, right and bottom use the darker shade.
  5465. // Drawing order matters in the upper right and lower left corners.
  5466. for ($i = 0; $i < $width; $i++, $ex--, $ey--) {
  5467. imageline($this->img, $i, $i, $ex, $i, $color1); // Top
  5468. imageline($this->img, $ex, $i, $ex, $ey, $color2); // Right
  5469. imageline($this->img, $i, $i, $i, $ey, $color1); // Left
  5470. imageline($this->img, $i, $ey, $ex, $ey, $color2); // Bottom
  5471. }
  5472. break;
  5473. case 'plain': // See note above re colors
  5474. $color1 = $color2;
  5475. // Fall through
  5476. case 'solid':
  5477. for ($i = 0; $i < $width; $i++, $ex--, $ey--) {
  5478. imagerectangle($this->img, $i, $i, $ex, $ey, $color1);
  5479. }
  5480. break;
  5481. default:
  5482. return $this->PrintError(
  5483. "DrawImageBorder(): unknown image_border_type: '$this->image_border_type'");
  5484. }
  5485. $this->done['border'] = TRUE; // Border should only be drawn once per image.
  5486. return TRUE;
  5487. }
  5488. /**
  5489. * Draws the main plot title
  5490. *
  5491. * @return bool True always
  5492. */
  5493. protected function DrawTitle()
  5494. {
  5495. if (!empty($this->done['title']) || $this->title_txt === '')
  5496. return TRUE;
  5497. // Center of the image:
  5498. $xpos = $this->image_width / 2;
  5499. // Place it at almost at the top
  5500. $ypos = $this->title_offset;
  5501. $this->DrawText('title', 0, $xpos, $ypos, $this->ndx_title_color, $this->title_txt, 'center', 'top');
  5502. $this->done['title'] = TRUE;
  5503. return TRUE;
  5504. }
  5505. /**
  5506. * Draws the X axis title, on the top or bottom (or both) of the plot area
  5507. *
  5508. * @return bool True always
  5509. */
  5510. protected function DrawXTitle()
  5511. {
  5512. if ($this->x_title_pos == 'none')
  5513. return TRUE;
  5514. // Center of the plot
  5515. $xpos = ($this->plot_area[2] + $this->plot_area[0]) / 2;
  5516. // Upper title
  5517. if ($this->x_title_pos == 'plotup' || $this->x_title_pos == 'both') {
  5518. $ypos = $this->plot_area[1] - $this->x_title_top_offset;
  5519. $this->DrawText('x_title', 0, $xpos, $ypos, $this->ndx_x_title_color,
  5520. $this->x_title_txt, 'center', 'bottom');
  5521. }
  5522. // Lower title
  5523. if ($this->x_title_pos == 'plotdown' || $this->x_title_pos == 'both') {
  5524. $ypos = $this->plot_area[3] + $this->x_title_bot_offset;
  5525. $this->DrawText('x_title', 0, $xpos, $ypos, $this->ndx_x_title_color,
  5526. $this->x_title_txt, 'center', 'top');
  5527. }
  5528. return TRUE;
  5529. }
  5530. /**
  5531. * Draws the Y axis title, on the left or right side (or both) of the plot area
  5532. *
  5533. * @return bool True always
  5534. */
  5535. protected function DrawYTitle()
  5536. {
  5537. if ($this->y_title_pos == 'none')
  5538. return TRUE;
  5539. // Center the title vertically to the plot area
  5540. $ypos = ($this->plot_area[3] + $this->plot_area[1]) / 2;
  5541. if ($this->y_title_pos == 'plotleft' || $this->y_title_pos == 'both') {
  5542. $xpos = $this->plot_area[0] - $this->y_title_left_offset;
  5543. $this->DrawText('y_title', 90, $xpos, $ypos, $this->ndx_y_title_color,
  5544. $this->y_title_txt, 'right', 'center');
  5545. }
  5546. if ($this->y_title_pos == 'plotright' || $this->y_title_pos == 'both') {
  5547. $xpos = $this->plot_area[2] + $this->y_title_right_offset;
  5548. $this->DrawText('y_title', 90, $xpos, $ypos, $this->ndx_y_title_color,
  5549. $this->y_title_txt, 'left', 'center');
  5550. }
  5551. return TRUE;
  5552. }
  5553. /**
  5554. * Draws the X axis, including ticks and labels, and vertical grid lines
  5555. *
  5556. * @return bool True always
  5557. */
  5558. protected function DrawXAxis()
  5559. {
  5560. // Draw ticks, labels and grid
  5561. $this->DrawXTicks();
  5562. //Draw X Axis at Y = x_axis_y_pixels, unless suppressed (See SetXAxisPosition)
  5563. if (!$this->suppress_x_axis) {
  5564. ImageLine($this->img, $this->plot_area[0]+1, $this->x_axis_y_pixels,
  5565. $this->plot_area[2]-1, $this->x_axis_y_pixels, $this->ndx_grid_color);
  5566. }
  5567. return TRUE;
  5568. }
  5569. /**
  5570. * Draws the Y axis, including ticks and labels, and horizontal grid lines
  5571. *
  5572. * This draws the Y axis and grid lines. It must be called before DrawXAxis() to avoid
  5573. * having a horizontal grid line overwrite the X axis.
  5574. *
  5575. * @return bool True always
  5576. */
  5577. protected function DrawYAxis()
  5578. {
  5579. // Draw ticks, labels and grid
  5580. $this->DrawYTicks();
  5581. // Draw Y axis at X = y_axis_x_pixels, unless suppressed (See SetYAxisPosition)
  5582. if (!$this->suppress_y_axis) {
  5583. ImageLine($this->img, $this->y_axis_x_pixels, $this->plot_area[1],
  5584. $this->y_axis_x_pixels, $this->plot_area[3], $this->ndx_grid_color);
  5585. }
  5586. return TRUE;
  5587. }
  5588. /**
  5589. * Draws one X tick mark and its tick label
  5590. *
  5591. * @param float $x X value for the label
  5592. * @param int $x_pixels X device coordinate for this tick mark
  5593. * @return bool True always
  5594. * @since 5.0.5
  5595. */
  5596. protected function DrawXTick($x, $x_pixels)
  5597. {
  5598. // Ticks on X axis
  5599. if ($this->x_tick_pos == 'xaxis') {
  5600. ImageLine($this->img, $x_pixels, $this->x_axis_y_pixels - $this->x_tick_cross,
  5601. $x_pixels, $this->x_axis_y_pixels + $this->x_tick_length, $this->ndx_tick_color);
  5602. }
  5603. // Ticks on top of the Plot Area
  5604. if ($this->x_tick_pos == 'plotup' || $this->x_tick_pos == 'both') {
  5605. ImageLine($this->img, $x_pixels, $this->plot_area[1] - $this->x_tick_length,
  5606. $x_pixels, $this->plot_area[1] + $this->x_tick_cross, $this->ndx_tick_color);
  5607. }
  5608. // Ticks on bottom of Plot Area
  5609. if ($this->x_tick_pos == 'plotdown' || $this->x_tick_pos == 'both') {
  5610. ImageLine($this->img, $x_pixels, $this->plot_area[3] + $this->x_tick_length,
  5611. $x_pixels, $this->plot_area[3] - $this->x_tick_cross, $this->ndx_tick_color);
  5612. }
  5613. if ($this->x_tick_label_pos != 'none') {
  5614. $x_label = $this->FormatLabel('x', $x);
  5615. // Label on X axis
  5616. if ($this->x_tick_label_pos == 'xaxis') {
  5617. $this->DrawText('x_label', $this->x_label_angle,
  5618. $x_pixels, $this->x_axis_y_pixels + $this->x_label_axis_offset,
  5619. $this->ndx_ticklabel_color, $x_label, 'center', 'top');
  5620. }
  5621. // Label on top of the plot area
  5622. if ($this->x_tick_label_pos == 'plotup' || $this->x_tick_label_pos == 'both') {
  5623. $this->DrawText('x_label', $this->x_label_angle,
  5624. $x_pixels, $this->plot_area[1] - $this->x_label_top_offset,
  5625. $this->ndx_ticklabel_color, $x_label, 'center', 'bottom');
  5626. }
  5627. // Label on bottom of the plot area
  5628. if ($this->x_tick_label_pos == 'plotdown' || $this->x_tick_label_pos == 'both') {
  5629. $this->DrawText('x_label', $this->x_label_angle,
  5630. $x_pixels, $this->plot_area[3] + $this->x_label_bot_offset,
  5631. $this->ndx_ticklabel_color, $x_label, 'center', 'top');
  5632. }
  5633. }
  5634. return TRUE;
  5635. }
  5636. /**
  5637. * Draws one Y tick mark and its tick label
  5638. *
  5639. * @param float $y Y value for the label
  5640. * @param int $y_pixels Y device coordinate for this tick mark
  5641. * @return bool True always
  5642. * @since 5.8.0
  5643. */
  5644. protected function DrawYTick($y, $y_pixels)
  5645. {
  5646. // Ticks on Y axis
  5647. if ($this->y_tick_pos == 'yaxis') {
  5648. ImageLine($this->img, $this->y_axis_x_pixels - $this->y_tick_length, $y_pixels,
  5649. $this->y_axis_x_pixels + $this->y_tick_cross, $y_pixels, $this->ndx_tick_color);
  5650. }
  5651. // Ticks to the left of the Plot Area
  5652. if (($this->y_tick_pos == 'plotleft') || ($this->y_tick_pos == 'both') ) {
  5653. ImageLine($this->img, $this->plot_area[0] - $this->y_tick_length, $y_pixels,
  5654. $this->plot_area[0] + $this->y_tick_cross, $y_pixels, $this->ndx_tick_color);
  5655. }
  5656. // Ticks to the right of the Plot Area
  5657. if (($this->y_tick_pos == 'plotright') || ($this->y_tick_pos == 'both') ) {
  5658. ImageLine($this->img, $this->plot_area[2] + $this->y_tick_length, $y_pixels,
  5659. $this->plot_area[2] - $this->y_tick_cross, $y_pixels, $this->ndx_tick_color);
  5660. }
  5661. if ($this->y_tick_label_pos != 'none') {
  5662. $y_label = $this->FormatLabel('y', $y);
  5663. // Labels on Y axis
  5664. if ($this->y_tick_label_pos == 'yaxis') {
  5665. $this->DrawText('y_label', $this->y_label_angle,
  5666. $this->y_axis_x_pixels - $this->y_label_axis_offset, $y_pixels,
  5667. $this->ndx_ticklabel_color, $y_label, 'right', 'center');
  5668. }
  5669. // Labels to the left of the plot area
  5670. if ($this->y_tick_label_pos == 'plotleft' || $this->y_tick_label_pos == 'both') {
  5671. $this->DrawText('y_label', $this->y_label_angle,
  5672. $this->plot_area[0] - $this->y_label_left_offset, $y_pixels,
  5673. $this->ndx_ticklabel_color, $y_label, 'right', 'center');
  5674. }
  5675. // Labels to the right of the plot area
  5676. if ($this->y_tick_label_pos == 'plotright' || $this->y_tick_label_pos == 'both') {
  5677. $this->DrawText('y_label', $this->y_label_angle,
  5678. $this->plot_area[2] + $this->y_label_right_offset, $y_pixels,
  5679. $this->ndx_ticklabel_color, $y_label, 'left', 'center');
  5680. }
  5681. }
  5682. return TRUE;
  5683. }
  5684. /**
  5685. * Draws the vertical grid lines, the X axis tick marks, and X axis tick labels
  5686. *
  5687. * @return bool True always
  5688. */
  5689. protected function DrawXTicks()
  5690. {
  5691. // Set color for solid, or flag for dashed line:
  5692. $style = $this->SetDashedStyle($this->ndx_light_grid_color, $this->dashed_grid);
  5693. // Draw grids lines?
  5694. $draw_grid = $this->GetGridSetting('x');
  5695. // Calculate the tick start, end, and step:
  5696. list($x_start, $x_end, $delta_x) = $this->CalcTicks('x');
  5697. // Loop, avoiding cumulative round-off errors from $x += $delta_x
  5698. for ($n = 0; ($x = $x_start + $n * $delta_x) <= $x_end; $n++) {
  5699. $x_pixels = $this->xtr($x);
  5700. // Draw vertical grid line:
  5701. if ($draw_grid) {
  5702. ImageLine($this->img, $x_pixels, $this->plot_area[1], $x_pixels, $this->plot_area[3], $style);
  5703. }
  5704. // Draw tick mark and tick label:
  5705. $this->DrawXTick($x, $x_pixels);
  5706. }
  5707. return TRUE;
  5708. }
  5709. /**
  5710. * Draws the horizontal grid lines, the Y axis tick marks, and Y axis tick labels
  5711. *
  5712. * @return bool True always
  5713. */
  5714. protected function DrawYTicks()
  5715. {
  5716. // Set color for solid, or flag for dashed line:
  5717. $style = $this->SetDashedStyle($this->ndx_light_grid_color, $this->dashed_grid);
  5718. // Draw grids lines?
  5719. $draw_grid = $this->GetGridSetting('y');
  5720. // Calculate the tick start, end, and step:
  5721. list($y_start, $y_end, $delta_y) = $this->CalcTicks('y');
  5722. // Loop, avoiding cumulative round-off errors from $y += $delta_y
  5723. for ($n = 0; ($y = $y_start + $n * $delta_y) <= $y_end; $n++) {
  5724. $y_pixels = $this->ytr($y);
  5725. // Draw horizontal grid line:
  5726. if ($draw_grid) {
  5727. ImageLine($this->img, $this->plot_area[0]+1, $y_pixels, $this->plot_area[2]-1,
  5728. $y_pixels, $style);
  5729. }
  5730. // Draw tick mark and tick label:
  5731. $this->DrawYTick($y, $y_pixels);
  5732. }
  5733. return TRUE;
  5734. }
  5735. /**
  5736. * Draws the border around the plot area
  5737. *
  5738. * This draws the plot border, as set by SetPlotBorderType(). The
  5739. * plot_border_type can be unset/NULL, a scaler, or an array. If unset or null,
  5740. * the default is used ('sides' if the plot includes axes, 'none' if not).
  5741. *
  5742. * @param bool $draw_axes True or omit to draw the X axis and Y axis, false to not (for pie charts)
  5743. * @return bool True always
  5744. */
  5745. protected function DrawPlotBorder($draw_axes = TRUE)
  5746. {
  5747. // Force plot_border_type to array and apply defaults.
  5748. if (isset($this->plot_border_type)) {
  5749. $pbt = (array)$this->plot_border_type;
  5750. } elseif ($draw_axes) $pbt = array('sides');
  5751. else return TRUE; // Default to no border for plots without axes (e.g. pie charts)
  5752. $sides = 0; // Bitmap: 1=left 2=top 4=right 8=bottom
  5753. $map = array('left' => 1, 'plotleft' => 1, 'right' => 4, 'plotright' => 4, 'top' => 2,
  5754. 'bottom' => 8, 'both' => 5, 'sides' => 5, 'full' => 15, 'none' => 0);
  5755. foreach ($pbt as $option) $sides |= $map[$option];
  5756. if ($sides == 15) { // Border on all 4 sides
  5757. imagerectangle($this->img, $this->plot_area[0], $this->plot_area[1],
  5758. $this->plot_area[2], $this->plot_area[3], $this->ndx_grid_color);
  5759. } else {
  5760. if ($sides & 1) // Left
  5761. imageline($this->img, $this->plot_area[0], $this->plot_area[1],
  5762. $this->plot_area[0], $this->plot_area[3], $this->ndx_grid_color);
  5763. if ($sides & 2) // Top
  5764. imageline($this->img, $this->plot_area[0], $this->plot_area[1],
  5765. $this->plot_area[2], $this->plot_area[1], $this->ndx_grid_color);
  5766. if ($sides & 4) // Right
  5767. imageline($this->img, $this->plot_area[2], $this->plot_area[1],
  5768. $this->plot_area[2], $this->plot_area[3], $this->ndx_grid_color);
  5769. if ($sides & 8) // Bottom
  5770. imageline($this->img, $this->plot_area[0], $this->plot_area[3],
  5771. $this->plot_area[2], $this->plot_area[3], $this->ndx_grid_color);
  5772. }
  5773. return TRUE;
  5774. }
  5775. /**
  5776. * Draws the data value label associated with a point in the plot
  5777. *
  5778. * The labels drawn by this function are those that show the value (usually
  5779. * the Y value) of the data point. They are drawn within the plot area,
  5780. * not to be confused with axis data labels.
  5781. *
  5782. * The $dvl parameter array can contain these keys:
  5783. * h_align v_align : Selects from 9-point text alignment (default center, center);
  5784. * x_offset y_offset : Text position offsets, in device coordinates (default 0,0);
  5785. * min_width min_height : Suppress the text if it will not fit (default null,null = no check).
  5786. * See also CheckDataValueLabels() which sets some of these.
  5787. *
  5788. * @param string $x_or_y Which labels: x | y, used to select font, angle, formatting
  5789. * @param int $row Identifies the row of the data point (for custom label formatting)
  5790. * @param int $column Identifies the column of the data point (for custom label formatting)
  5791. * @param float $x_world X world coordinate of the base point
  5792. * @param float $y_world Y world coordinate of the base point
  5793. * @param mixed $text The text to draw after formatting with FormatLabel()
  5794. * @param mixed[] $dvl Associative array with additional label position controls (see above)
  5795. * @return bool True, if the text was drawn, or False, if it will not fit
  5796. * @since 5.1.3
  5797. */
  5798. protected function DrawDataValueLabel($x_or_y, $row, $column, $x_world, $y_world, $text, $dvl)
  5799. {
  5800. if ($x_or_y == 'x') {
  5801. $angle = $this->x_data_label_angle;
  5802. $font_id = 'x_label';
  5803. $formatted_text = $this->FormatLabel('xd', $text, $row, $column);
  5804. } else { // Assumed 'y'
  5805. $angle = $this->y_data_label_angle;
  5806. $font_id = 'y_label';
  5807. $formatted_text = $this->FormatLabel('yd', $text, $row, $column);
  5808. }
  5809. // Assign defaults and then extract control variables from $dvl:
  5810. $x_offset = $y_offset = 0;
  5811. $h_align = $v_align = 'center';
  5812. extract($dvl);
  5813. // Check to see if the text fits in the available space, if requested.
  5814. if (isset($min_width) || isset($min_height)) {
  5815. list($width, $height) = $this->SizeText($font_id, $angle, $formatted_text);
  5816. if ((isset($min_width) && ($min_width - $width) < 2)
  5817. || (isset($min_height) && ($min_height - $height) < 2))
  5818. return FALSE;
  5819. }
  5820. $this->DrawText($font_id, $angle, $this->xtr($x_world) + $x_offset, $this->ytr($y_world) + $y_offset,
  5821. $this->ndx_dvlabel_color, $formatted_text, $h_align, $v_align);
  5822. return TRUE;
  5823. }
  5824. /**
  5825. * Draws an X axis data label, and optional data label line (used in vertical plots)
  5826. *
  5827. * @param string $xlab Text of the label to draw
  5828. * @param int $xpos X position for the label, in device coordinates
  5829. * @param int $row Row index, 0 for the first X, 1 for the second, etc.
  5830. * @param bool $do_lines True for plot types that support data label lines, False or omit if not
  5831. * @return bool True always
  5832. */
  5833. protected function DrawXDataLabel($xlab, $xpos, $row, $do_lines=FALSE)
  5834. {
  5835. $xlab = $this->FormatLabel('xd', $xlab, $row);
  5836. // Labels below the plot area
  5837. if ($this->x_data_label_pos == 'plotdown' || $this->x_data_label_pos == 'both')
  5838. $this->DrawText('x_label', $this->x_data_label_angle,
  5839. $xpos, $this->plot_area[3] + $this->x_label_bot_offset,
  5840. $this->ndx_datalabel_color, $xlab, 'center', 'top');
  5841. // Labels above the plot area
  5842. if ($this->x_data_label_pos == 'plotup' || $this->x_data_label_pos == 'both')
  5843. $this->DrawText('x_label', $this->x_data_label_angle,
  5844. $xpos, $this->plot_area[1] - $this->x_label_top_offset,
  5845. $this->ndx_datalabel_color, $xlab, 'center', 'bottom');
  5846. if ($do_lines && $this->draw_x_data_label_lines)
  5847. $this->DrawXDataLine($xpos, $row);
  5848. return TRUE;
  5849. }
  5850. /**
  5851. * Draws a Y axis data label, and optional data label line (used in horizontal plots)
  5852. *
  5853. * @param string $ylab Text of the label to draw
  5854. * @param int $ypos Y position for the label, in device coordinates
  5855. * @param int $row Row index, 0 for the first Y, 1 for the second, etc.
  5856. * @param bool $do_lines True for plot types that support data label lines, False or omit if not
  5857. * @return bool True always
  5858. * @since 5.1.2
  5859. */
  5860. protected function DrawYDataLabel($ylab, $ypos, $row, $do_lines=FALSE)
  5861. {
  5862. $ylab = $this->FormatLabel('yd', $ylab, $row);
  5863. // Labels left of the plot area
  5864. if ($this->y_data_label_pos == 'plotleft' || $this->y_data_label_pos == 'both')
  5865. $this->DrawText('y_label', $this->y_data_label_angle,
  5866. $this->plot_area[0] - $this->y_label_left_offset, $ypos,
  5867. $this->ndx_datalabel_color, $ylab, 'right', 'center');
  5868. // Labels right of the plot area
  5869. if ($this->y_data_label_pos == 'plotright' || $this->y_data_label_pos == 'both')
  5870. $this->DrawText('y_label', $this->y_data_label_angle,
  5871. $this->plot_area[2] + $this->y_label_right_offset, $ypos,
  5872. $this->ndx_datalabel_color, $ylab, 'left', 'center');
  5873. if ($do_lines && $this->draw_y_data_label_lines)
  5874. $this->DrawYDataLine($ypos, $row);
  5875. return TRUE;
  5876. }
  5877. /**
  5878. * Draws vertical data label lines (used in vertical plots)
  5879. *
  5880. * This draws vertical lines from a data point up and/or down.
  5881. * Which lines are drawn depends on the value of x_data_label_pos.
  5882. * Whether this is done not depends on draw_x_data_label_lines.
  5883. *
  5884. * @param int $xpos X position in pixels of the line
  5885. * @param int $row Index of the data row being drawn
  5886. * @return bool True always
  5887. */
  5888. protected function DrawXDataLine($xpos, $row)
  5889. {
  5890. // Set color for solid, or flag for dashed line:
  5891. $style = $this->SetDashedStyle($this->ndx_light_grid_color, $this->dashed_grid);
  5892. if ($this->x_data_label_pos == 'both') {
  5893. // Lines from the bottom up
  5894. ImageLine($this->img, $xpos, $this->plot_area[3], $xpos, $this->plot_area[1], $style);
  5895. } elseif ($this->x_data_label_pos == 'plotdown' && isset($this->data_max[$row])) {
  5896. // Lines from the bottom of the plot up to the max Y value at this X:
  5897. $ypos = $this->ytr($this->data_max[$row]);
  5898. ImageLine($this->img, $xpos, $ypos, $xpos, $this->plot_area[3], $style);
  5899. } elseif ($this->x_data_label_pos == 'plotup' && isset($this->data_min[$row])) {
  5900. // Lines from the top of the plot down to the min Y value at this X:
  5901. $ypos = $this->ytr($this->data_min[$row]);
  5902. ImageLine($this->img, $xpos, $this->plot_area[1], $xpos, $ypos, $style);
  5903. }
  5904. return TRUE;
  5905. }
  5906. /**
  5907. * Draws horizontal data label lines (used in horizontal plots)
  5908. *
  5909. * This draws horizontal lines from a data points left and/or right.
  5910. * Which lines are drawn depends on the value of y_data_label_pos.
  5911. * Whether this is done not depends on draw_y_data_label_lines.
  5912. *
  5913. * @param int $ypos Y position in pixels of the line
  5914. * @param int $row Index of the data row being drawn
  5915. * @return bool True always
  5916. * @since 6.0.0
  5917. */
  5918. protected function DrawYDataLine($ypos, $row)
  5919. {
  5920. // Set color for solid, or flag for dashed line:
  5921. $style = $this->SetDashedStyle($this->ndx_light_grid_color, $this->dashed_grid);
  5922. if ($this->y_data_label_pos == 'both') {
  5923. // Lines from the left side to the right side
  5924. ImageLine($this->img, $this->plot_area[0], $ypos, $this->plot_area[2], $ypos, $style);
  5925. } elseif ($this->y_data_label_pos == 'plotleft' && isset($this->data_max[$row])) {
  5926. // Lines from the left of the plot rightwards the max X value at this Y:
  5927. $xpos = $this->xtr($this->data_max[$row]);
  5928. ImageLine($this->img, $xpos, $ypos, $this->plot_area[0], $ypos, $style);
  5929. } elseif ($this->y_data_label_pos == 'plotright' && isset($this->data_min[$row])) {
  5930. // Lines from the right of the plot leftwards to the min X value at this Y:
  5931. $xpos = $this->xtr($this->data_min[$row]);
  5932. ImageLine($this->img, $this->plot_area[2], $ypos, $xpos, $ypos, $style);
  5933. }
  5934. return TRUE;
  5935. }
  5936. /**
  5937. * Formats a pie chart label
  5938. *
  5939. * @param int $index Pie slice number, starting with 0
  5940. * @param string[] $pie_label_source Label formatting mode(s). See CheckPieLabels() and SetPieLabelType()
  5941. * @param float $arc_angle Delta angle for this slice, in degrees
  5942. * @param float $slice_weight Numeric value, or relative weight, of this slice
  5943. * @return string The formatted label value
  5944. * @since 5.6.0
  5945. */
  5946. protected function FormatPieLabel($index, $pie_label_source, $arc_angle, $slice_weight)
  5947. {
  5948. $values = array(); // Builds up label value, one field at a time.
  5949. foreach ($pie_label_source as $word) {
  5950. switch ($word) {
  5951. case 'label': // Use label from data array, but only if data type is compatible
  5952. $values[] = $this->datatype_pie_single ? $this->data[$index][0] : '';
  5953. break;
  5954. case 'value': // Use actual numeric value of the slice
  5955. $values[] = $slice_weight;
  5956. break;
  5957. case 'index': // Use slice index: 0, 1, 2...
  5958. $values[] = $index;
  5959. break;
  5960. default: // Use percentage: 100% x arc_angle / (360 degrees) = arc_angle / 3.6
  5961. $values[] = $arc_angle / 3.6;
  5962. }
  5963. }
  5964. // Format the label and return the result. Note: The conditional avoids a number-to-string
  5965. // conversion for the single-source case. This avoids a PHP issue with locale-based conversion.
  5966. return $this->FormatLabel('p', count($values) == 1 ? $values[0] : implode(' ', $values));
  5967. }
  5968. /**
  5969. * Draws a pie chart label
  5970. *
  5971. * This draws a single label for a pie chart.
  5972. *
  5973. * The $r parameter array is calculated by DrawPieChart() and contains
  5974. * values that are constant for the chart, so do not need to be
  5975. * recalculated for each slice. Array keys are 'x' 'y' and 'reverse'.
  5976. * r[x], r[y] are the parameters of the ellipse: ` x**2 / r[x]**2 + y**2 / r[y]**2 = 1 `
  5977. * Also: ` x = r[x] * cos(angle) ` and ` y = r[y] * sin(angle) ` (relative to pie center).
  5978. * 'reverse' is a flag for text alignment (see GetTextAlignment()).
  5979. *
  5980. * @param string $label_txt Pre-formatted label, from FormatPieLabel()
  5981. * @param int $xc X device coordinate of the pie center
  5982. * @param int $yc Y device coordinate of the pie center
  5983. * @param float $start_angle Slice starting angle in degrees
  5984. * @param float $arc_angle Slice angular width in degrees
  5985. * @param mixed[] $r Additional paramter array (from DrawPieChart, see comment above)
  5986. * @return bool True always
  5987. * @since 5.6.0
  5988. */
  5989. protected function DrawPieLabel($label_txt, $xc, $yc, $start_angle, $arc_angle, $r)
  5990. {
  5991. $mid_angle = deg2rad($start_angle + $arc_angle / 2);
  5992. $sin_mid = sin($mid_angle);
  5993. $cos_mid = cos($mid_angle);
  5994. // Calculate label reference point.
  5995. $label_x = $xc + $cos_mid * $r['x'];
  5996. $label_y = $yc - $sin_mid * $r['y'];
  5997. // For labels in the lower half, outside the pie, offset it to account for shading.
  5998. // But don't shift labels just below the horizontal, because the shading is too thin there,
  5999. // and the label ends up too far from the slice. Make a smooth transition between label offsets on
  6000. // shaded area and above. (This isn't perfect at all, but works for reasonably low shading.)
  6001. if ($this->label_scale_position >= 0.5 && $this->shading > 0 && $sin_mid < 0) {
  6002. $yoff = min($this->shading, -$sin_mid * $r['y']);
  6003. } else $yoff = 0;
  6004. // Calculate text alignment (h_align, v_align) based on angle:
  6005. $this->GetTextAlignment($sin_mid, $cos_mid, $h_align, $v_align, $r['reverse']);
  6006. // Draw the label:
  6007. $this->DrawText('generic', 0, $label_x, $label_y + $yoff, $this->ndx_pielabel_color,
  6008. $label_txt, $h_align, $v_align);
  6009. return TRUE;
  6010. }
  6011. /////////////////////////////////////////////
  6012. /////////////// LEGEND
  6013. /////////////////////////////////////////////
  6014. /**
  6015. * Adds text to a legend box
  6016. *
  6017. * The legend can be set up with a single call by passing an array of
  6018. * strings (1 string per legend line/data set), or it can be built up
  6019. * one line at a time with repeated calls passing a single string.
  6020. * NULL (or an empty array) can be passed to cancel the legend.
  6021. *
  6022. * @param string|string[] $which_leg Array of strings for the legend, or a single string to append
  6023. * @return bool True always
  6024. */
  6025. function SetLegend($which_leg)
  6026. {
  6027. if (is_array($which_leg)) { // use array (or cancel, if empty array)
  6028. $this->legend = $which_leg;
  6029. } elseif (!is_null($which_leg)) { // append string
  6030. if (!isset($this->legend)) $this->legend = array(); // Seems unnecessary, but be safe.
  6031. $this->legend[] = $which_leg;
  6032. } else {
  6033. $this->legend = NULL; // Reset to no legend.
  6034. }
  6035. return TRUE;
  6036. }
  6037. /**
  6038. * Positions the legend on the image, using device coordinates
  6039. *
  6040. * @param int $which_x X coordinate in pixels of the upper left corner of the legend box
  6041. * @param int $which_y Y coordinate in pixels of the upper left corner of the legend box
  6042. * @return bool True (False on error if an error handler returns True)
  6043. */
  6044. function SetLegendPixels($which_x=NULL, $which_y=NULL)
  6045. {
  6046. return $this->SetLegendPosition(0, 0, 'image', 0, 0, $which_x, $which_y);
  6047. }
  6048. /**
  6049. * Positions the legend on the image, using world coordinates
  6050. *
  6051. * @param int $which_x World coordinate X of the upper left corner of the legend box
  6052. * @param int $which_y World coordinate Y of the upper left corner of the legend box
  6053. * @return bool True (False on error if an error handler returns True)
  6054. */
  6055. function SetLegendWorld($which_x, $which_y)
  6056. {
  6057. return $this->SetLegendPosition(0, 0, 'world', $which_x, $which_y);
  6058. }
  6059. /**
  6060. * Positions the legend
  6061. *
  6062. * This implements SetLegendWorld(), SetLegendPixels(), and also allows use
  6063. * of relative coordinates, with optional pixel offset.
  6064. *
  6065. * 'Relative coordinates' means: (0,0) is the upper left corner, and (1,1)
  6066. * is the lower right corner of the element (legend, image, plot, or title
  6067. * area), regardless of its size. These are floating point values, each
  6068. * usually in the range [0,1], but they can be negative or greater than 1.
  6069. *
  6070. * If any of x, y, x_offset, or y_offset are NULL, the default legend
  6071. * positioning is restored.
  6072. *
  6073. * Note: This only stores the parameters. The real work is in GetLegendPosition().
  6074. *
  6075. * @param float $x Relative coordinate X indicating an anchor point on the legend box
  6076. * @param float $y Relative coordinate X indicating an anchor point on the legend box
  6077. * @param string $relative_to Position is relative to: image | plot | world | title
  6078. * @param float $x_base Base point X for positioning to the anchor point
  6079. * @param float $y_base Base point Y for positioning to the anchor point
  6080. * @param int $x_offset Additional legend box offset X value in pixels
  6081. * @param int $y_offset Additional legend box offset Y value in pixels
  6082. * @return bool True (False on error if an error handler returns True)
  6083. * @since 5.4.0
  6084. */
  6085. function SetLegendPosition($x, $y, $relative_to, $x_base, $y_base, $x_offset = 0, $y_offset = 0)
  6086. {
  6087. // Special case: NULL means restore the default positioning.
  6088. if (!isset($x, $y, $x_offset, $y_offset)) {
  6089. $this->legend_pos = NULL;
  6090. } else {
  6091. $mode = $this->CheckOption($relative_to, 'image, plot, title, world', __FUNCTION__);
  6092. if (empty($mode))
  6093. return FALSE;
  6094. // Save all values for use by GetLegendPosition()
  6095. $this->legend_pos = compact('x', 'y', 'mode', 'x_base', 'y_base', 'x_offset', 'y_offset');
  6096. }
  6097. return TRUE;
  6098. }
  6099. /**
  6100. * Controls the appearance of the legend
  6101. *
  6102. * @param string $text_align How to align the text in the legend: left | right
  6103. * @param string $colorbox_align How to align the color boxes or shape markers: left | right | none | ''
  6104. * @return bool True (False on error if an error handler returns True)
  6105. * @since 5.0.4
  6106. */
  6107. function SetLegendStyle($text_align, $colorbox_align = '')
  6108. {
  6109. $this->legend_text_align = $this->CheckOption($text_align, 'left, right', __FUNCTION__);
  6110. if (empty($colorbox_align))
  6111. $this->legend_colorbox_align = $this->legend_text_align;
  6112. else
  6113. $this->legend_colorbox_align = $this->CheckOption($colorbox_align, 'left, right, none',
  6114. __FUNCTION__);
  6115. return ($this->legend_text_align && $this->legend_colorbox_align);
  6116. }
  6117. /**
  6118. * Selects use of color boxes or alternative shapes (point shapes or line segments) in the legend
  6119. *
  6120. * @param bool $use_shapes True to use shapes or lines, false to use color boxes
  6121. * @return bool True always
  6122. * @since 5.4.0
  6123. */
  6124. function SetLegendUseShapes($use_shapes)
  6125. {
  6126. $this->legend_use_shapes = (bool)$use_shapes;
  6127. return TRUE;
  6128. }
  6129. /**
  6130. * Controls the order of text lines in the legend (e.g. for Stackedbar plots)
  6131. *
  6132. * @param bool $reversal True to reverse the order - bottom up; False for default top down
  6133. * @return bool True always
  6134. * @since 5.5.0
  6135. */
  6136. function SetLegendReverse($reversal = False)
  6137. {
  6138. $this->legend_reverse_order = (bool)$reversal;
  6139. return TRUE;
  6140. }
  6141. /**
  6142. * Controls the borders around the color boxes in the legend
  6143. *
  6144. * @param string $cbbmode Color box mode: none | textcolor | databordercolor
  6145. * @return bool True (False on error if an error handler returns True)
  6146. * @since 6.0.0
  6147. */
  6148. function SetLegendColorboxBorders($cbbmode = 'textcolor')
  6149. {
  6150. $this->legend_colorbox_borders = $this->CheckOption($cbbmode, 'none, textcolor, databordercolor',
  6151. __FUNCTION__);
  6152. return (boolean)$this->legend_colorbox_borders;
  6153. }
  6154. /**
  6155. * Calculates legend sizing parameters
  6156. *
  6157. * Used by DrawLegend() and the public GetLegendSize().
  6158. * It returns information based on any SetLegend*() calls already made. It does not use
  6159. * legend position or data scaling, so it can be called before data scaling is set up.
  6160. * It must not be called if $this->legend is empty.
  6161. *
  6162. * Returns an associative array with these entries describing legend sizing:
  6163. * 'width', 'height' : Overall legend box size in pixels.
  6164. * 'char_w', 'char_h' : Width and height of 'E' in legend text font. (Used to size color boxes)
  6165. * 'v_margin' : Inside margin for legend
  6166. * 'dot_height' : Height of color boxes (even if not drawn), for line spacing.
  6167. * 'colorbox_mode', 'colorbox_width' : Colorbox/shape mode and width factor.
  6168. *
  6169. * @return array Legend sizing parameter associative array
  6170. * @since 5.4.0
  6171. */
  6172. protected function GetLegendSizeParams()
  6173. {
  6174. $font = &$this->fonts['legend']; // Shortcut to font info array
  6175. // Find maximum legend label line width.
  6176. $max_width = 0;
  6177. foreach ($this->legend as $line) {
  6178. list($width, $unused) = $this->SizeText('legend', 0, $line);
  6179. if ($width > $max_width) $max_width = $width;
  6180. }
  6181. // Font parameters are used to size the color boxes:
  6182. $char_w = $font['width'];
  6183. $char_h = $font['height'];
  6184. $line_spacing = $this->GetLineSpacing($font);
  6185. // Get color-box mode. Note GetLegendSizeParams can be called from GetLegendSize, and not all
  6186. // settings are defined then, but the colorbox_mode won't be used then so it need not be valid.
  6187. if ($this->legend_colorbox_align == 'none') {
  6188. $colorbox_mode = False; // Color boxes are off
  6189. } elseif (!$this->legend_use_shapes || empty(self::$plots[$this->plot_type]['legend_alt_marker'])) {
  6190. $colorbox_mode = 'box'; // Not using shapes, or plot type defines no shape, so use boxes.
  6191. } else {
  6192. $colorbox_mode = self::$plots[$this->plot_type]['legend_alt_marker']; // Shape from plot type
  6193. }
  6194. // Sizing parameters:
  6195. $v_margin = $char_h / 2; // Between vertical borders and labels
  6196. $dot_height = $char_h + $line_spacing; // Height of the color boxes (even if not drawn)
  6197. $colorbox_width = $char_w * $this->legend_colorbox_width; // Color box width, with adjustment
  6198. // The 'line' style marker needs a wider colorbox than shape or box.
  6199. if ($colorbox_mode == 'line')
  6200. $colorbox_width *= 4;
  6201. // Calculate overall legend box width and height.
  6202. // Width is e.g.: "| space colorbox space text space |" where each space adds $char_w,
  6203. // and colorbox (if drawn) adds $char_w * its width adjustment.
  6204. if ($colorbox_mode) {
  6205. $width = $max_width + 3 * $char_w + $colorbox_width;
  6206. } else {
  6207. $width = $max_width + 2 * $char_w;
  6208. }
  6209. $height = $dot_height * count($this->legend) + 2 * $v_margin;
  6210. return compact('width', 'height', 'char_w', 'char_h', 'v_margin',
  6211. 'colorbox_mode', 'dot_height', 'colorbox_width');
  6212. }
  6213. /**
  6214. * Gets the legend box size (can be used to adjust the plot margins, for example)
  6215. *
  6216. * @return int[] Legend box size as array of (width, height) in pixels, False if no legend defined.
  6217. * @since 5.4.0
  6218. */
  6219. function GetLegendSize()
  6220. {
  6221. if (empty($this->legend))
  6222. return FALSE;
  6223. $params = $this->GetLegendSizeParams();
  6224. return array($params['width'], $params['height']);
  6225. }
  6226. /**
  6227. * Calculates the legend location in device coordinates
  6228. *
  6229. * This is a helper for DrawLegend, and is only called if there is a legend.
  6230. * See SetLegendWorld(), SetLegendPixels(), SetLegendPosition().
  6231. *
  6232. * @param int $width Width of the legend box
  6233. * @param int $height Height of the legend box
  6234. * @return int[] Coordinates of the upper left corner of the legend box as an array ($x, $y)
  6235. * @since 5.4.0
  6236. */
  6237. protected function GetLegendPosition($width, $height)
  6238. {
  6239. // Extract variables set by SetLegend*(): $mode, $x, $y, $x_base, $y_base, $x_offset, $y_offset
  6240. if (isset($this->legend_pos['mode']))
  6241. extract($this->legend_pos);
  6242. else
  6243. $mode = ''; // Default legend position mode.
  6244. switch ($mode) {
  6245. case 'plot': // SetLegendPosition with mode='plot', relative coordinates over plot area.
  6246. return array((int)($x_base * $this->plot_area_width - $x * $width)
  6247. + $this->plot_area[0] + $x_offset,
  6248. (int)($y_base * $this->plot_area_height - $y * $height)
  6249. + $this->plot_area[1] + $y_offset);
  6250. case 'world': // User-defined position in world-coordinates (SetLegendWorld), using x_base, y_base
  6251. return array($this->xtr($x_base) + $x_offset - (int)($x * $width),
  6252. $this->ytr($y_base) + $y_offset - (int)($y * $height));
  6253. case 'image': // SetLegendPosition with mode='image', relative coordinates over image area.
  6254. // SetLegendPixels() uses this too, with x=y=0.
  6255. return array((int)($x_base * $this->image_width - $x * $width) + $x_offset,
  6256. (int)($y_base * $this->image_height - $y * $height) + $y_offset);
  6257. case 'title': // SetLegendPosition with mode='title', relative to main title.
  6258. // Recalculate main title position/size, since CalcMargins does not save it. See DrawTitle()
  6259. list($title_width, $title_height) = $this->SizeText('title', 0, $this->title_txt);
  6260. $title_x = (int)(($this->image_width - $title_width) / 2);
  6261. return array((int)($x_base * $title_width - $x * $width) + $title_x + $x_offset,
  6262. (int)($y_base * $title_height - $y * $height) + $this->title_offset + $y_offset);
  6263. default: // If mode is unset (or invalid), use default position.
  6264. return array ($this->plot_area[2] - $width - $this->safe_margin,
  6265. $this->plot_area[1] + $this->safe_margin);
  6266. }
  6267. }
  6268. /**
  6269. * Draws the plot legend - the outline box, text labels, and color boxes or shapes
  6270. *
  6271. * @return bool True always
  6272. */
  6273. protected function DrawLegend()
  6274. {
  6275. // Calculate legend box sizing parameters:
  6276. // See GetLegendSizeParams() to see what variables are set by this.
  6277. extract($this->GetLegendSizeParams());
  6278. // Get legend box position:
  6279. list($box_start_x, $box_start_y) = $this->GetLegendPosition($width, $height);
  6280. $box_end_y = $box_start_y + $height;
  6281. $box_end_x = $box_start_x + $width;
  6282. // Draw outer box
  6283. ImageFilledRectangle($this->img, $box_start_x, $box_start_y, $box_end_x, $box_end_y,
  6284. $this->ndx_legend_bg_color);
  6285. ImageRectangle($this->img, $box_start_x, $box_start_y, $box_end_x, $box_end_y,
  6286. $this->ndx_grid_color);
  6287. // Calculate color box and text horizontal positions.
  6288. if (!$colorbox_mode) {
  6289. if ($this->legend_text_align == 'left')
  6290. $x_pos = $box_start_x + $char_w;
  6291. else
  6292. $x_pos = $box_end_x - $char_w;
  6293. $dot_left_x = 0; // Not used directly if color boxes/shapes are off, but referenced below.
  6294. } elseif ($this->legend_colorbox_align == 'left') {
  6295. $dot_left_x = $box_start_x + $char_w;
  6296. $dot_right_x = $dot_left_x + $colorbox_width;
  6297. if ($this->legend_text_align == 'left')
  6298. $x_pos = $dot_right_x + $char_w;
  6299. else
  6300. $x_pos = $box_end_x - $char_w;
  6301. } else { // colorbox_align == 'right'
  6302. $dot_right_x = $box_end_x - $char_w;
  6303. $dot_left_x = $dot_right_x - $colorbox_width;
  6304. if ($this->legend_text_align == 'left')
  6305. $x_pos = $box_start_x + $char_w;
  6306. else
  6307. $x_pos = $dot_left_x - $char_w;
  6308. }
  6309. // $y_pos is the bottom of each color box. $yc is the vertical center of the color box or
  6310. // the point shape (if drawn). The text is centered vertically on $yc.
  6311. // For normal order (top-down), $y_pos starts at the top. For reversed order, at the bottom.
  6312. if ($this->legend_reverse_order) {
  6313. $y_pos = $box_end_y - $v_margin;
  6314. $delta_y = -$dot_height;
  6315. } else {
  6316. $y_pos = $box_start_y + $v_margin + $dot_height;
  6317. $delta_y = $dot_height;
  6318. }
  6319. $yc = (int)($y_pos - $dot_height / 2);
  6320. $xc = (int)($dot_left_x + $colorbox_width / 2); // Horizontal center for point shape if drawn
  6321. // Colorbox color index, shape index, and line width/style index variables.
  6322. // Note the arrays these are used to index have been padded to data_columns entries. The legend
  6323. // can contain more than data_columns entries, though, but it only makes sense to be able
  6324. // to index additional entries for the data color, due to the data_color callback.
  6325. if ($colorbox_mode) {
  6326. $color_index = 0;
  6327. $max_color_index = count($this->ndx_data_colors) - 1;
  6328. $lws_index = 0; // Line Width and Style index
  6329. $shape_index = 0;
  6330. }
  6331. foreach ($this->legend as $leg) {
  6332. // Draw text with requested alignment:
  6333. $this->DrawText('legend', 0, $x_pos, $yc, $this->ndx_legend_text_color, $leg,
  6334. $this->legend_text_align, 'center');
  6335. if ($colorbox_mode) {
  6336. $y1 = $y_pos - $dot_height + 1;
  6337. $y2 = $y_pos - 1;
  6338. // If plot area background is on, draw a background for any non-box shapes:
  6339. if ($this->draw_plot_area_background && $colorbox_mode != 'box') {
  6340. ImageFilledRectangle($this->img, $dot_left_x, $y1, $dot_right_x, $y2,
  6341. $this->ndx_plot_bg_color);
  6342. }
  6343. switch ($colorbox_mode) {
  6344. case 'shape':
  6345. // Draw the shape. DrawShape() takes shape_index modulo number of defined shapes.
  6346. $this->DrawShape($xc, $yc, $shape_index++, $this->ndx_data_colors[$color_index], FALSE);
  6347. break;
  6348. case 'line':
  6349. // Draw a short line segment with proper color, width, and style
  6350. imagesetthickness($this->img, $this->line_widths[$lws_index]);
  6351. $style = $this->SetDashedStyle($this->ndx_data_colors[$color_index],
  6352. $this->line_styles[$lws_index] == 'dashed');
  6353. imageline($this->img, $dot_left_x, $yc, $dot_right_x, $yc, $style);
  6354. imagesetthickness($this->img, 1);
  6355. if (++$lws_index >= $this->data_columns) $lws_index = 0; // Wrap around
  6356. break;
  6357. default:
  6358. // Draw color boxes:
  6359. ImageFilledRectangle($this->img, $dot_left_x, $y1, $dot_right_x, $y2,
  6360. $this->ndx_data_colors[$color_index]);
  6361. // Draw a rectangle around the box, if enabled.
  6362. if ($this->legend_colorbox_borders != 'none') {
  6363. if ($this->legend_colorbox_borders == 'databordercolor')
  6364. $color = $this->ndx_data_border_colors[$color_index];
  6365. else
  6366. $color = $this->ndx_text_color;
  6367. ImageRectangle($this->img, $dot_left_x, $y1, $dot_right_x, $y2, $color);
  6368. }
  6369. }
  6370. if (++$color_index > $max_color_index) $color_index = 0;
  6371. }
  6372. $y_pos += $delta_y;
  6373. $yc += $delta_y;
  6374. }
  6375. return TRUE;
  6376. }
  6377. /////////////////////////////////////////////
  6378. //////////////////// PLOT DRAWING HELPERS
  6379. /////////////////////////////////////////////
  6380. /**
  6381. * Gets the color index to use for plotting a data element (point or line segment, for example)
  6382. *
  6383. * This is used to select data colors for plotting. Without a custom data
  6384. * color callback, color selection is based on $idx, the column index in
  6385. * the data array. So the first data set (Y) uses the first color, etc.
  6386. * With a custom data color callback, both row and column index values
  6387. * are passed to the callback so it can use them to select a color.
  6388. *
  6389. * @param int $row Row index for the current data point (used only for a custom data color callback)
  6390. * @param int $idx Column index for the current data point (e.g. 0 for the first Y value for each X)
  6391. * @param mixed[] $vars Reference variable, array for local storage (caller makes an empty array)
  6392. * @param int $data_color Reference variable: returned color index to use for drawing
  6393. * @param mixed $extra Extra variable passed through to a data color callback
  6394. * @since 5.2.0
  6395. */
  6396. protected function GetDataColor($row, $idx, &$vars, &$data_color, $extra = 0)
  6397. {
  6398. // Initialize or extract variables:
  6399. if (empty($vars)) {
  6400. $custom_color = (bool)$this->GetCallback('data_color');
  6401. $num_data_colors = count($this->ndx_data_colors);
  6402. $vars = compact('custom_color', 'num_data_colors');
  6403. } else {
  6404. extract($vars);
  6405. }
  6406. // Select the data color:
  6407. if ($custom_color) {
  6408. $idx = $this->DoCallback('data_color', $row, $idx, $extra) % $num_data_colors;
  6409. }
  6410. $data_color = $this->ndx_data_colors[$idx];
  6411. }
  6412. /**
  6413. * Gets the color indexes to use for data element and error bar plotting
  6414. *
  6415. * @param int $row Row index for the current data point (used only for a custom data color callback)
  6416. * @param int $idx Column index for the current data point (e.g. 0 for the first Y value for each X)
  6417. * @param mixed[] $vars Reference variable, array for local storage (caller makes an empty array)
  6418. * @param int $data_color Reference variable: returned color index to use for drawing
  6419. * @param int error_color Reference variable: returned color index to use for the error bars
  6420. * @param mixed $extra Extra variable passed through to a data color callback
  6421. * @since 5.2.0
  6422. */
  6423. protected function GetDataErrorColors($row, $idx, &$vars, &$data_color, &$error_color, $extra = 0)
  6424. {
  6425. // Initialize or extract variables:
  6426. if (empty($vars)) {
  6427. $this->NeedErrorBarColors(); // This plot needs error bar colors.
  6428. $custom_color = (bool)$this->GetCallback('data_color');
  6429. $num_data_colors = count($this->ndx_data_colors);
  6430. $num_error_colors = count($this->ndx_error_bar_colors);
  6431. $vars = compact('custom_color', 'num_data_colors', 'num_error_colors');
  6432. } else {
  6433. extract($vars);
  6434. }
  6435. // Select the colors.
  6436. if ($custom_color) {
  6437. $col_i = $this->DoCallback('data_color', $row, $idx, $extra); // Custom color index
  6438. $data_color = $this->ndx_data_colors[$col_i % $num_data_colors];
  6439. $error_color = $this->ndx_error_bar_colors[$col_i % $num_error_colors];
  6440. } else {
  6441. $data_color = $this->ndx_data_colors[$idx];
  6442. $error_color = $this->ndx_error_bar_colors[$idx];
  6443. }
  6444. }
  6445. /**
  6446. * Gets the color indexes to use for a bar chart (data color, border color, shading color)
  6447. *
  6448. * @param int $row Row index for the current data point (used only for a custom data color callback)
  6449. * @param int $idx Column index for the current data point (e.g. 0 for the first Y value for each X)
  6450. * @param mixed[] $vars Reference variable, array for local storage (caller makes an empty array)
  6451. * @param int $data_color Returned color index to use for the bar fill
  6452. * @param int $shade_color Returned color index for the shading, NULL if shading is off
  6453. * @param int $border_color Returned color index for the bar borders, NULL if borders are off
  6454. * @since 5.2.0
  6455. */
  6456. protected function GetBarColors($row, $idx, &$vars, &$data_color, &$shade_color, &$border_color)
  6457. {
  6458. // Initialize or extract this functions persistant state variables:
  6459. if (empty($vars)) {
  6460. if (($shaded = ($this->shading > 0)))
  6461. $this->NeedDataDarkColors(); // Plot needs dark colors for shading
  6462. $custom_color = (bool)$this->GetCallback('data_color');
  6463. $num_data_colors = count($this->ndx_data_colors);
  6464. $num_border_colors = count($this->ndx_data_border_colors);
  6465. // Are borders enabled? Default is true for unshaded plots, false for shaded.
  6466. $borders = isset($this->draw_data_borders) ? $this->draw_data_borders : !$shaded;
  6467. $vars = compact('borders', 'custom_color', 'num_data_colors', 'num_border_colors', 'shaded');
  6468. } else {
  6469. extract($vars);
  6470. }
  6471. // Select the colors.
  6472. if ($custom_color) {
  6473. $col_i = $this->DoCallback('data_color', $row, $idx); // Custom color index
  6474. $i_data = $col_i % $num_data_colors; // Index for data colors and dark colors
  6475. $i_border = $col_i % $num_border_colors; // Index for data borders (if used)
  6476. } else {
  6477. $i_data = $i_border = $idx;
  6478. }
  6479. $data_color = $this->ndx_data_colors[$i_data];
  6480. $shade_color = $shaded ? $this->ndx_data_dark_colors[$i_data] : NULL;
  6481. $border_color = $borders ? $this->ndx_data_border_colors[$i_border] : NULL;
  6482. }
  6483. /**
  6484. * Gets the grid setting, on or off
  6485. *
  6486. * This function determines the dynamic defaults. The grid defaults on for
  6487. * the dependent variable, off for the independent variable.
  6488. *
  6489. * @param string $xy Which grid to check for: x | y
  6490. * @return bool True if the grid should be drawn, False if it should not be drawn
  6491. * @since 6.0.0
  6492. */
  6493. protected function GetGridSetting($xy)
  6494. {
  6495. if ($xy == 'x')
  6496. return isset($this->draw_x_grid) ? $this->draw_x_grid : $this->datatype_swapped_xy;
  6497. // Assumed 'y'
  6498. return isset($this->draw_y_grid) ? $this->draw_y_grid : !$this->datatype_swapped_xy;
  6499. }
  6500. /**
  6501. * Draws a single marker shape (a dot or shape)
  6502. *
  6503. * This is used by points and linepoints plots to draw a point, and by the
  6504. * legend. Also see SetPointShapes() for the list of supported shapes.
  6505. *
  6506. * @param int $x X device coordinate of the center of the shape
  6507. * @param int $y Y device coordinate of the center of the shape
  6508. * @param int $record Index into point_shapes[] and point_sizes[] arrays (taken modulo their sizes)
  6509. * @param int $color Color index to use for the point shape
  6510. * @param bool $allow_none True or omit allow 'none' as shape, False to substitute (for legend)
  6511. * @return bool True always
  6512. * @since 5.4.0
  6513. */
  6514. protected function DrawShape($x, $y, $record, $color, $allow_none = TRUE)
  6515. {
  6516. $index = $record % $this->point_counts;
  6517. $point_size = $this->point_sizes[$index];
  6518. $half_point = (int)($point_size / 2);
  6519. $x1 = $x - $half_point;
  6520. $x2 = $x + $half_point;
  6521. $y1 = $y - $half_point;
  6522. $y2 = $y + $half_point;
  6523. switch ($this->point_shapes[$index]) {
  6524. case 'halfline':
  6525. ImageLine($this->img, $x1, $y, $x, $y, $color);
  6526. break;
  6527. case 'none': /* Special case, no point shape here */
  6528. if ($allow_none) break; // But fall throught to line if a shape is required
  6529. case 'line':
  6530. ImageLine($this->img, $x1, $y, $x2, $y, $color);
  6531. break;
  6532. case 'plus':
  6533. ImageLine($this->img, $x1, $y, $x2, $y, $color);
  6534. ImageLine($this->img, $x, $y1, $x, $y2, $color);
  6535. break;
  6536. case 'cross':
  6537. ImageLine($this->img, $x1, $y1, $x2, $y2, $color);
  6538. ImageLine($this->img, $x1, $y2, $x2, $y1, $color);
  6539. break;
  6540. case 'circle':
  6541. ImageArc($this->img, $x, $y, $point_size, $point_size, 0, 360, $color);
  6542. break;
  6543. case 'dot':
  6544. ImageFilledEllipse($this->img, $x, $y, $point_size, $point_size, $color);
  6545. break;
  6546. case 'diamond':
  6547. $arrpoints = array($x1, $y, $x, $y1, $x2, $y, $x, $y2);
  6548. ImageFilledPolygon($this->img, $arrpoints, 4, $color);
  6549. break;
  6550. case 'triangle':
  6551. $arrpoints = array($x1, $y, $x2, $y, $x, $y2);
  6552. ImageFilledPolygon($this->img, $arrpoints, 3, $color);
  6553. break;
  6554. case 'trianglemid':
  6555. $arrpoints = array($x1, $y1, $x2, $y1, $x, $y);
  6556. ImageFilledPolygon($this->img, $arrpoints, 3, $color);
  6557. break;
  6558. case 'yield':
  6559. $arrpoints = array($x1, $y1, $x2, $y1, $x, $y2);
  6560. ImageFilledPolygon($this->img, $arrpoints, 3, $color);
  6561. break;
  6562. case 'delta':
  6563. $arrpoints = array($x1, $y2, $x2, $y2, $x, $y1);
  6564. ImageFilledPolygon($this->img, $arrpoints, 3, $color);
  6565. break;
  6566. case 'star':
  6567. ImageLine($this->img, $x1, $y, $x2, $y, $color);
  6568. ImageLine($this->img, $x, $y1, $x, $y2, $color);
  6569. ImageLine($this->img, $x1, $y1, $x2, $y2, $color);
  6570. ImageLine($this->img, $x1, $y2, $x2, $y1, $color);
  6571. break;
  6572. case 'hourglass':
  6573. $arrpoints = array($x1, $y1, $x2, $y1, $x1, $y2, $x2, $y2);
  6574. ImageFilledPolygon($this->img, $arrpoints, 4, $color);
  6575. break;
  6576. case 'bowtie':
  6577. $arrpoints = array($x1, $y1, $x1, $y2, $x2, $y1, $x2, $y2);
  6578. ImageFilledPolygon($this->img, $arrpoints, 4, $color);
  6579. break;
  6580. case 'target':
  6581. ImageFilledRectangle($this->img, $x1, $y1, $x, $y, $color);
  6582. ImageFilledRectangle($this->img, $x, $y, $x2, $y2, $color);
  6583. ImageRectangle($this->img, $x1, $y1, $x2, $y2, $color);
  6584. break;
  6585. case 'box':
  6586. ImageRectangle($this->img, $x1, $y1, $x2, $y2, $color);
  6587. break;
  6588. case 'home': /* As in: "home plate" (baseball), also looks sort of like a house. */
  6589. $arrpoints = array($x1, $y2, $x2, $y2, $x2, $y, $x, $y1, $x1, $y);
  6590. ImageFilledPolygon($this->img, $arrpoints, 5, $color);
  6591. break;
  6592. case 'up':
  6593. ImagePolygon($this->img, array($x, $y1, $x2, $y2, $x1, $y2), 3, $color);
  6594. break;
  6595. case 'down':
  6596. ImagePolygon($this->img, array($x, $y2, $x1, $y1, $x2, $y1), 3, $color);
  6597. break;
  6598. default: /* Also 'rect' */
  6599. ImageFilledRectangle($this->img, $x1, $y1, $x2, $y2, $color);
  6600. break;
  6601. }
  6602. return TRUE;
  6603. }
  6604. /**
  6605. * Draws a single marker point, using World Coordinates
  6606. *
  6607. * @param int $row Row index of data point (only used for a data_points callback)
  6608. * @param int $column Column index of data point, used to select the marker shape and size
  6609. * @param int $x_world X world coordinate of the data point
  6610. * @param int $y_world Y world coordinate of the data point
  6611. * @param int $color Color to use for the data point
  6612. * @return bool True always (from DrawShape)
  6613. */
  6614. protected function DrawDot($row, $column, $x_world, $y_world, $color)
  6615. {
  6616. $x = $this->xtr($x_world);
  6617. $y = $this->ytr($y_world);
  6618. $result = $this->DrawShape($x, $y, $column, $color);
  6619. $this->DoCallback('data_points', 'dot', $row, $column, $x, $y);
  6620. return $result;
  6621. }
  6622. /**
  6623. * Draws a single bar (or bar segment), with optional shading or border
  6624. *
  6625. * This draws a single bar (or bar segment), for bar and stackedbar plots,
  6626. * both vertical and horizontal. The 3 color values come from GetBarColors.
  6627. * Two flags (at most 1 of which can be false) are used to suppress shading
  6628. * for some cases of stackedbar plots.
  6629. *
  6630. * @param int $row Row index of data point (only used for a data_points callback)
  6631. * @param int $column Column index of data point (only used for a data_points callback)
  6632. * @param int $x1 One corner of the bar X (device coordinates)
  6633. * @param int $y1 One corner of the bar Y (device coordinates)
  6634. * @param int $x2 Other corner of the bar X (device coordinates)
  6635. * @param int $y2 Other corner of the bar Y (device coordinates)
  6636. * @param int $data_color Color index to use for the bar fill
  6637. * @param int $shade_color Color index to use for the shading (if shading is on, else NULL)
  6638. * @param int $border_color Color index to use for the bar outlines (borders), if enabled, else NULL
  6639. * @param bool $shade_top Shade the top? (Suppressed for downward stack segments except first)
  6640. * @param bool $shade_side Shade the right side? (Suppressed for leftward stack segments except first)
  6641. * @return bool True always
  6642. * @since 5.2.0
  6643. */
  6644. protected function DrawBar($row, $column, $x1, $y1, $x2, $y2, $data_color, $shade_color, $border_color,
  6645. $shade_top = TRUE, $shade_side = TRUE)
  6646. {
  6647. // Sort the points so x1,y1 is upper left and x2,y2 is lower right. This
  6648. // is needed in order to get the shading right, and imagerectangle may require it.
  6649. if ($x1 > $x2) {
  6650. $t = $x1; $x1 = $x2; $x2 = $t;
  6651. }
  6652. if ($y1 > $y2) {
  6653. $t = $y1; $y1 = $y2; $y2 = $t;
  6654. }
  6655. // Draw the bar
  6656. ImageFilledRectangle($this->img, $x1, $y1, $x2, $y2, $data_color);
  6657. // Draw a shade, if shading is on.
  6658. if (isset($shade_color)) {
  6659. $shade = $this->shading;
  6660. if ($shade_top && $shade_side) {
  6661. $pts = array($x1, $y1, $x1 + $shade, $y1 - $shade, $x2 + $shade, $y1 - $shade,
  6662. $x2 + $shade, $y2 - $shade, $x2, $y2, $x2, $y1);
  6663. } elseif ($shade_top) { // Suppress side shading
  6664. $pts = array($x1, $y1, $x1 + $shade, $y1 - $shade, $x2 + $shade, $y1 - $shade, $x2, $y1);
  6665. } else { // Suppress top shading (Note shade_top==FALSE && shade_side==FALSE is not allowed)
  6666. $pts = array($x2, $y2, $x2, $y1, $x2 + $shade, $y1 - $shade, $x2 + $shade, $y2 - $shade);
  6667. }
  6668. ImageFilledPolygon($this->img, $pts, count($pts) / 2, $shade_color);
  6669. }
  6670. // Draw a border around the bar, if enabled.
  6671. if (isset($border_color)) {
  6672. // Avoid a PHP/GD bug with zero-height ImageRectangle resulting in "T"-shaped ends.
  6673. if ($y1 == $y2)
  6674. imageline($this->img, $x1, $y1, $x2, $y2, $border_color);
  6675. else
  6676. imagerectangle($this->img, $x1, $y1, $x2, $y2, $border_color);
  6677. }
  6678. $this->DoCallback('data_points', 'rect', $row, $column, $x1, $y1, $x2, $y2);
  6679. return TRUE;
  6680. }
  6681. /**
  6682. * Draws an error bar set for horizontal plots, showing +/- error in X
  6683. *
  6684. * @param float $x X world coordinate of the data point (dependent variable)
  6685. * @param float $y Y world coordinate of the data point (independent variable)
  6686. * @param float $error_plus X error offset above $x (world coordinates >= 0)
  6687. * @param float $error_minus X error offset below $x (world coordinates >= 0)
  6688. * @param int $color Color to use for the error bars
  6689. * @return bool True always
  6690. * @since 6.1.0
  6691. */
  6692. protected function DrawXErrorBars($x, $y, $error_plus, $error_minus, $color)
  6693. {
  6694. $x1 = $this->xtr($x);
  6695. $y1 = $this->ytr($y);
  6696. $x2p = $this->xtr($x + $error_plus);
  6697. $x2m = $this->xtr($x - $error_minus);
  6698. imagesetthickness($this->img, $this->error_bar_line_width);
  6699. imageline($this->img, $x2p, $y1 , $x2m, $y1, $color);
  6700. if ($this->error_bar_shape == 'tee') {
  6701. $e = $this->error_bar_size;
  6702. imageline($this->img, $x2p, $y1 - $e, $x2p, $y1 + $e, $color);
  6703. imageline($this->img, $x2m, $y1 - $e, $x2m, $y1 + $e, $color);
  6704. }
  6705. imagesetthickness($this->img, 1);
  6706. return TRUE;
  6707. }
  6708. /**
  6709. * Draws an error bar set for vertical plots, showing +/- error in Y
  6710. *
  6711. * @param float $x X world coordinate of the data point (independent variable)
  6712. * @param float $y Y world coordinate of the data point (dependent variable)
  6713. * @param float $error_plus Y error offset above $y (world coordinates >= 0)
  6714. * @param float $error_minus Y error offset below $y (world coordinates >= 0)
  6715. * @param int $color Color to use for the error bars
  6716. * @return bool True always
  6717. * @since 6.1.0
  6718. */
  6719. protected function DrawYErrorBars($x, $y, $error_plus, $error_minus, $color)
  6720. {
  6721. $x1 = $this->xtr($x);
  6722. $y1 = $this->ytr($y);
  6723. $y2p = $this->ytr($y + $error_plus);
  6724. $y2m = $this->ytr($y - $error_minus);
  6725. imagesetthickness($this->img, $this->error_bar_line_width);
  6726. imageline($this->img, $x1, $y2p , $x1, $y2m, $color);
  6727. if ($this->error_bar_shape == 'tee') {
  6728. $e = $this->error_bar_size;
  6729. imageline($this->img, $x1 - $e, $y2p, $x1 + $e, $y2p, $color);
  6730. imageline($this->img, $x1 - $e, $y2m, $x1 + $e, $y2m, $color);
  6731. }
  6732. imagesetthickness($this->img, 1);
  6733. return TRUE;
  6734. }
  6735. /**
  6736. * Sets up the default pie chart label type and format
  6737. *
  6738. * If SetPieLabelType() was not called, this function set the default.
  6739. * The default for pie chart labels is to show the slice percentage,
  6740. * with fixed point precision. For backward compatibility with
  6741. * PHPlot <= 5.5.0, the Y label data precision (if set) is the default
  6742. * precision used.
  6743. *
  6744. * @return string[] A value to use as pie_label_source in FormatPieLabel()
  6745. * @since 5.6.0
  6746. */
  6747. protected function CheckPieLabels()
  6748. {
  6749. if (empty($this->pie_label_source)) { // SetPieLabelType() was not called, or was reset to default
  6750. $prec = isset($this->label_format['y']['precision']) ? $this->label_format['y']['precision'] : 1;
  6751. $this->SetLabelType('p', array('data', $prec, '', '%'));
  6752. return array('percent'); // Default to 'percent' labels (leaving this->pie_label_source empty)
  6753. }
  6754. return $this->pie_label_source; // Use label type set set with SetPieLabelType()
  6755. }
  6756. /**
  6757. * Sets up for an area plot, calculating a points list and drawing data labels
  6758. *
  6759. * This is used for area fill plots: [stacked]area and [stacked]squaredarea.
  6760. * It converts the data array to device coordinate arrays. This also
  6761. * draws the axis data labels (if enabled). Caller ensures there are at
  6762. * least 2 rows (X), and all rows have same number of columns (Y).
  6763. * Note that the returned $yd array has an extra column for points along
  6764. * the X axis. See comment below on 'artifical Y value'.
  6765. * This does not support missing points or data value labels.
  6766. *
  6767. * @param bool $stacked True for a stacked plot (cumulative Y), false if not
  6768. * @param int[] $xd Reference variable - returned array with X device coordinates
  6769. * @param int[] $yd Reference variable - returned 2D array with Y device coordinates
  6770. * @return int Number of columns in yd[][], which is $this->data_columns + 1
  6771. * @since 6.2.0
  6772. */
  6773. protected function SetupAreaPlot($stacked, &$xd, &$yd)
  6774. {
  6775. $xd = array();
  6776. $yd = array();
  6777. // Outer loop over rows (X); inner over columns (Y):
  6778. for ($row = 0; $row < $this->num_data_rows; $row++) {
  6779. $rec = 1; // Skip record #0 (data label)
  6780. if ($this->datatype_implied) // Implied X values?
  6781. $x_now = 0.5 + $row; // Place text-data at X = 0.5, 1.5, 2.5, etc...
  6782. else
  6783. $x_now = $this->data[$row][$rec++]; // Read it, advance record index
  6784. $xd[$row] = $x_now_pixels = $this->xtr($x_now); // Save in device coordinates
  6785. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  6786. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
  6787. // There is an artificial Y value at the X axis. For stacked plots, it goes before the
  6788. // first real Y, so the first area fill is from the axis to the first Y data set.
  6789. // For non-stacked plots, it goes after the last Y, so the last area fill is from axis
  6790. // to the last Y data set.
  6791. if ($stacked)
  6792. $yd[$row] = array($this->x_axis_y_pixels);
  6793. else
  6794. $yd[$row] = array();
  6795. // Store the Y values for this X. Missing Y values are not supported, and are replaced with 0.
  6796. // Negative numbers are not supported, and are replaced with absolute values.
  6797. // The resulting numbers are also clipped to the X axis' Y value (which can be > 0).
  6798. $y = 0; // Accumulate (if not reset below) the Y values
  6799. for ($idx = 0; $rec < $this->records_per_group; $rec++, $idx++) {
  6800. if (is_numeric($y_now = $this->data[$row][$rec]))
  6801. $y += abs($y_now);
  6802. $yd[$row][] = $this->ytr(max($this->x_axis_position, $y));
  6803. if (!$stacked) $y = 0; // For non-stacked plots, reset Y in each loop.
  6804. }
  6805. // See above: For non-stacked plots, the Y value for X axis goes at the end.
  6806. if (!$stacked)
  6807. $yd[$row][] = $this->x_axis_y_pixels;
  6808. }
  6809. return ($this->data_columns + 1); // This is the size of each yd[][]
  6810. }
  6811. /**
  6812. * Draws the data borders for an area fill plot
  6813. *
  6814. * This is used by area fill plots (area, squaredarea, and their stacked
  6815. * variants) to draw the data borders, if enabled.
  6816. *
  6817. * @param int $n_columns Number of columns in $yd, returned by SetupAreaPlot()
  6818. * @param int[] $xd X device coordinate array from SetupAreaPlot()
  6819. * @param int[] $yd Y device coordinate array from SetupAreaPlot()
  6820. * @param bool $stacked True for a stacked plot (cumulative Y), false if not
  6821. * @param bool $stepped True for a stepped (squared) plot, false for a regular area plot
  6822. * @return bool True always
  6823. * @since 6.2.0
  6824. */
  6825. function DrawAreaFillBorders($n_columns, $xd, $yd, $stacked, $stepped)
  6826. {
  6827. for ($col = 1; $col < $n_columns; $col++) {
  6828. $color = $this->ndx_data_border_colors[$col-1];
  6829. // This is due to the difference in the $yd array for stacked and unstacked.
  6830. if ($stacked) {
  6831. $this_col = $col; // Border follows column = 1 to N-1
  6832. $other_col = $col - 1; // Left and right edges use the previous column
  6833. } else {
  6834. $this_col = $col - 1; // Border follows column = 0 to N-2
  6835. $other_col = $col; // Left and right edges use the next column
  6836. }
  6837. // Left edge:
  6838. $x = $xd[0];
  6839. $y = $yd[0][$this_col];
  6840. ImageLine($this->img, $x, $yd[0][$other_col], $x, $y, $color);
  6841. // Across the top, with an 'X then Y' step at each point:
  6842. for ($row = 1; $row < $this->num_data_rows; $row++) {
  6843. $prev_x = $x;
  6844. $prev_y = $y;
  6845. $x = $xd[$row];
  6846. $y = $yd[$row][$this_col];
  6847. if ($stepped) {
  6848. ImageLine($this->img, $prev_x, $prev_y, $x, $prev_y, $color);
  6849. ImageLine($this->img, $x, $prev_y, $x, $y, $color);
  6850. } else {
  6851. ImageLine($this->img, $prev_x, $prev_y, $x, $y, $color);
  6852. }
  6853. }
  6854. // Right edge:
  6855. ImageLine($this->img, $x, $y, $x, $yd[$this->num_data_rows - 1][$other_col], $color);
  6856. }
  6857. return TRUE;
  6858. }
  6859. /////////////////////////////////////////////
  6860. //////////////////// PLOT DRAWING
  6861. /////////////////////////////////////////////
  6862. /**
  6863. * Draws a pie plot (Pie chart)
  6864. *
  6865. * This is the main function for drawing a pie chart. Supported data
  6866. * types are 'text-data', 'data-data', and 'text-data-single'.
  6867. *
  6868. * For text-data-single, the data array contains records with a label and
  6869. * one Y value. Each record defines a sector of the pie, as a portion of
  6870. * the sum of all Y values. Data labels are ignored by default, but can
  6871. * be selected for display with SetPieLabelType().
  6872. *
  6873. * For text-data and data-data, the data array contains records with an
  6874. * ignored label, an ignored X value for data-data only, and N (N>=1) Y
  6875. * values per record. The pie chart will be produced with N segments. The
  6876. * relative size of the first sector of the pie is the sum of the first Y
  6877. * data value in each record, etc. The data labels cannot be used, since
  6878. * they don't map to specific pie sectors.
  6879. *
  6880. * If there are no valid positive data points at all, just draw nothing.
  6881. * It may seem more correct to raise an error, but all of the other plot
  6882. * types handle it this way implicitly. DrawGraph() checks for an empty
  6883. * data array, but this handles a non-empty data array with no Y values,
  6884. * or all Y=0.
  6885. *
  6886. * @return bool True (False on error if an error handler returns True)
  6887. *
  6888. */
  6889. protected function DrawPieChart()
  6890. {
  6891. // Early checks and initialization:
  6892. if (!$this->CheckDataType('text-data, text-data-single, data-data'))
  6893. return FALSE;
  6894. // SetLabelScalePosition(0 or FALSE) means no labels.
  6895. $do_labels = !empty($this->label_scale_position);
  6896. if ($do_labels) {
  6897. // Validate and get default for pie chart label source and format:
  6898. $pie_label_source = $this->CheckPieLabels();
  6899. // Labels outside (vs inside) the pie? If so, pie size will need adjusting.
  6900. $labels_outside = $this->label_scale_position >= 0.5; // Only defined if ($do_labels)
  6901. }
  6902. // Draw segment borders? Default is True for unshaded, False for shaded
  6903. $do_borders = isset($this->draw_pie_borders) ? $this->draw_pie_borders : ($this->shading == 0);
  6904. $max_data_colors = count($this->ndx_data_colors); // Number of colors available
  6905. // Check shading. Diameter factor $diam_factor is (height / width)
  6906. if ($this->shading > 0) {
  6907. $diam_factor = $this->pie_diam_factor;
  6908. $this->NeedDataDarkColors(); // Dark colors are needed for shading
  6909. } else {
  6910. $diam_factor = 1.0; // Unshaded pies are always round, width == height
  6911. }
  6912. // Pie center point is always the center of the plot area, regardless of label sizes.
  6913. $xpos = $this->plot_area[0] + $this->plot_area_width/2;
  6914. $ypos = $this->plot_area[1] + $this->plot_area_height/2;
  6915. // Reduce the data array into sumarr[], accounting for the data type:
  6916. $num_slices = $this->data_columns; // See CheckDataArray which calculates this for us.
  6917. if ($num_slices < 1) return TRUE; // Give up early if there is no data at all.
  6918. $sumarr = array_fill(0, $num_slices, 0); // Initialize array of per-sector sums.
  6919. if ($this->datatype_pie_single) {
  6920. // text-data-single: One data column per row, one pie slice per row.
  6921. for ($i = 0; $i < $num_slices; $i++) {
  6922. if (is_numeric($val = $this->data[$i][1]))
  6923. $sumarr[$i] = abs($val);
  6924. }
  6925. } else {
  6926. // text-data: Sum each column (skipping label), one pie slice per column.
  6927. // data-data: Sum each column (skipping X value and label), one pie slice per column.
  6928. $skip = ($this->datatype_implied) ? 1 : 2; // Leading values to skip in each row.
  6929. for ($i = 0; $i < $this->num_data_rows; $i++) {
  6930. for ($j = $skip; $j < $this->num_recs[$i]; $j++) {
  6931. if (is_numeric($val = $this->data[$i][$j]))
  6932. $sumarr[$j-$skip] += abs($val);
  6933. }
  6934. }
  6935. }
  6936. $total = array_sum($sumarr);
  6937. if ($total == 0) {
  6938. // There are either no valid data points, or all are 0.
  6939. // See top comment about why not to make this an error.
  6940. return TRUE;
  6941. }
  6942. // Pre-calculate the label strings, if labels are on. Also get the maximum height and width
  6943. // of the labels, to use in sizing the pie chart (if the labels are outside the pie).
  6944. // This is an overly pessimistic approach - assumes the widest label is at 0 or 180 degrees - but
  6945. // is much easier than calculating the exact space needed for all labels around the pie.
  6946. // For more detailed comments on the in-loop calculations, see the second loop below where
  6947. // the features are actually drawn.
  6948. // Note this is going around the pie, with angles specified, but we do not yet know the pie size.
  6949. $label_max_width = 0; // Widest label width, in pixels
  6950. $label_max_height = 0; // Tallest label height, in pixels
  6951. if ($do_labels) {
  6952. $labels = array(); // Array to store the formatted label strings
  6953. $end_angle = $start_angle = $this->pie_start_angle;
  6954. for ($j = 0; $j < $num_slices; $j++) {
  6955. $slice_weight = $sumarr[$j];
  6956. $arc_angle = 360 * $slice_weight / $total;
  6957. if ($this->pie_direction_cw) {
  6958. $end_angle = $start_angle;
  6959. $start_angle -= $arc_angle;
  6960. } else {
  6961. $start_angle = $end_angle;
  6962. $end_angle += $arc_angle;
  6963. }
  6964. $arc_start_angle = (int)(360 - $start_angle);
  6965. $arc_end_angle = (int)(360 - $end_angle);
  6966. if ($arc_start_angle > $arc_end_angle) { // Skip segments with angle < 1 degree
  6967. $labels[$j] = $this->FormatPieLabel($j, $pie_label_source, $arc_angle, $slice_weight);
  6968. if ($labels_outside) { // Labels are outside the pie chart
  6969. list($width, $height) = $this->SizeText('generic', 0, $labels[$j]);
  6970. if ($width > $label_max_width) $label_max_width = $width;
  6971. if ($height > $label_max_height) $label_max_height = $height;
  6972. }
  6973. }
  6974. }
  6975. }
  6976. // Calculate the maximum available area for the pie, leaving room for labels (if outside the pie):
  6977. // This can be overridden by using SetPieAutoSize(FALSE), which sets the flag: pie_full_size=TRUE.
  6978. if ($do_labels && $labels_outside && !$this->pie_full_size) {
  6979. // There needs to be safe_margin between the labels and the plot area margins, and at least
  6980. // safe_margin between the labels and the pie edge (this is LR_marg and TB_marg below).
  6981. // plot_area_width = avail_width + 2 * (LR_marg + label_width + safe_margin)
  6982. // Where LR_marg = max(safe_margin, avail_width * label_scale_position - avail_width/2)
  6983. // plot_area_height = avail_height + 2 * (TB_marg + label_height + safe_margin + shading)
  6984. // Where TB_marg = max(safe_margin, avail_height * label_scale_position - avail_height/2)
  6985. // Note shading is on bottom only, but since center is fixed, it is counted on top too.
  6986. // Note (avail_width * label_scale_position) is the distance from the pie center to the label
  6987. // text base point. Subtract avail_width/2 to get the inner margin (unless it is too small).
  6988. // Similar for Y: avail_height * label_scale_position - avail_height/2 is the distance from
  6989. // the pie center up to the label text base point.
  6990. // Calculate available space for both values of LR_marg, TB_marg and take the smaller ones.
  6991. $avail_width = min(
  6992. ($this->plot_area_width / 2 - $label_max_width - $this->safe_margin) /
  6993. $this->label_scale_position,
  6994. $this->plot_area_width - 4 * $this->safe_margin - 2 * $label_max_width);
  6995. $avail_height = min(
  6996. ($this->plot_area_height / 2 - $label_max_height - $this->safe_margin - $this->shading) /
  6997. $this->label_scale_position,
  6998. $this->plot_area_height - 4*$this->safe_margin - 2*($label_max_height + $this->shading));
  6999. // Sanity check - don't let large labels shrink the pie too much.
  7000. $avail_width = max($avail_width, $this->pie_min_size_factor * $this->plot_area_width);
  7001. $avail_height = max($avail_height, $this->pie_min_size_factor * $this->plot_area_height);
  7002. } else { // No adjustment needed for labels
  7003. $avail_width = $this->plot_area_width - 2 * $this->safe_margin;
  7004. // Note shading is only on bottom, but need to subtract 2x because center does not move.
  7005. $avail_height = $this->plot_area_height - 2 * ($this->safe_margin + $this->shading);
  7006. }
  7007. // Calculate the pie width and height for the best fit, given diam_factor and available space:
  7008. if ($avail_height / $avail_width > $diam_factor) {
  7009. $pie_width = $avail_width;
  7010. $pie_height = $pie_width * $diam_factor;
  7011. } else {
  7012. $pie_height = $avail_height;
  7013. $pie_width = $pie_height / $diam_factor;
  7014. }
  7015. // Factors used to calculate label positions by DrawPieLabel(). See there for explanation.
  7016. if ($do_labels) {
  7017. $r['reverse'] = 0.25 < $this->label_scale_position && $this->label_scale_position < 0.5;
  7018. $r['x'] = $pie_width * $this->label_scale_position;
  7019. $r['y'] = $pie_height * $this->label_scale_position;
  7020. if ($labels_outside) {
  7021. // Don't let outside labels touch the pie edge - move them out a bit:
  7022. $r['x'] = max($r['x'], $pie_width / 2 + $this->safe_margin);
  7023. $r['y'] = max($r['y'], $pie_height / 2 + $this->safe_margin);
  7024. } else {
  7025. // Don't let inside labels touch the pie edge - move them in a bit:
  7026. $r['x'] = min($r['x'], $pie_width / 2 - $this->safe_margin);
  7027. $r['y'] = min($r['y'], $pie_height / 2 - $this->safe_margin);
  7028. }
  7029. }
  7030. // Draw the pie. For shaded pies, draw one set for each shading level ($h).
  7031. for ($h = $this->shading; $h >= 0; $h--) {
  7032. $color_index = 0;
  7033. // Initialize the start angle (for clockwise) or end angle (for counter-clockwise).
  7034. // See "Calculate the two angles" below to make sense of this.
  7035. $end_angle = $start_angle = $this->pie_start_angle;
  7036. // Loop over all pie segments:
  7037. for ($j = 0; $j < $num_slices; $j++) {
  7038. $slice_weight = $sumarr[$j];
  7039. $arc_angle = 360 * $slice_weight / $total;
  7040. // For shaded pies: the last one (at the top of the "stack") has a brighter color:
  7041. if ($h == 0)
  7042. $slicecol = $this->ndx_data_colors[$color_index];
  7043. else
  7044. $slicecol = $this->ndx_data_dark_colors[$color_index];
  7045. // Calculate the two angles that define this pie segment.
  7046. // Note that regardless of the direction (CW or CCW), start_angle < end_angle.
  7047. if ($this->pie_direction_cw) {
  7048. $end_angle = $start_angle;
  7049. $start_angle -= $arc_angle;
  7050. } else {
  7051. $start_angle = $end_angle;
  7052. $end_angle += $arc_angle;
  7053. }
  7054. // Calculate the arc angles for ImageFilledArc(), which measures angles in the opposite
  7055. // direction (counter-clockwise), and only takes integer values.
  7056. $arc_start_angle = (int)(360 - $start_angle);
  7057. $arc_end_angle = (int)(360 - $end_angle);
  7058. // Don't try to draw a 0 degree slice - it would make a full circle.
  7059. if ($arc_start_angle > $arc_end_angle) {
  7060. // Draw the slice
  7061. ImageFilledArc($this->img, $xpos, $ypos+$h, $pie_width, $pie_height,
  7062. $arc_end_angle, $arc_start_angle, $slicecol, IMG_ARC_PIE);
  7063. // Processing to do only for the last (if shaded) or only (if unshaded) loop:
  7064. if ($h == 0) {
  7065. // Draw the pie segment outline (if enabled):
  7066. if ($do_borders) {
  7067. ImageFilledArc($this->img, $xpos, $ypos, $pie_width, $pie_height,
  7068. $arc_end_angle, $arc_start_angle, $this->ndx_pieborder_color,
  7069. IMG_ARC_PIE | IMG_ARC_EDGED |IMG_ARC_NOFILL);
  7070. }
  7071. // Draw the label:
  7072. if ($do_labels)
  7073. $this->DrawPieLabel($labels[$j], $xpos, $ypos, $start_angle, $arc_angle, $r);
  7074. // Trigger a data points callback; note it gets the calculated (reversed) angles:
  7075. $this->DoCallback('data_points', 'pie', $j, 0, $xpos, $ypos, $pie_width,
  7076. $pie_height, $arc_start_angle, $arc_end_angle);
  7077. }
  7078. }
  7079. if (++$color_index >= $max_data_colors)
  7080. $color_index = 0;
  7081. } // end loop for each slice
  7082. } // end loop for each level of shading
  7083. return TRUE;
  7084. }
  7085. /**
  7086. * Draws a points plot, or the points for a linepoints plot
  7087. *
  7088. * This is the main function for drawing a points plot, and is also used
  7089. * for a linepoints plot. Vertical and Horizontal plots, and error plots,
  7090. * are all supported. "iv" is used for the independent variable (X for
  7091. * vertical plots, Y for horizontal) and "dv" is used for the dependent
  7092. * variable (Y or X respectively).
  7093. *
  7094. * When $paired is true, a linepoints plot is being drawn, and some
  7095. * elements are suppressed here because they are done elsewhere. See
  7096. * DrawLinePoints() for details.
  7097. *
  7098. * @param bool $paired True if doing a linepoints plot, False or omit for points plot
  7099. * @return bool True (False on error if an error handler returns True)
  7100. */
  7101. protected function DrawDots($paired = FALSE)
  7102. {
  7103. if (!$this->CheckDataType('text-data, data-data, text-data-yx, data-data-yx, '
  7104. . 'data-data-error, data-data-yx-error'))
  7105. return FALSE;
  7106. // Adjust the point shapes and point sizes arrays:
  7107. $this->CheckPointParams();
  7108. $gcvars = array(); // For GetDataColor, which initializes and uses this.
  7109. // Special flag for data color callback to indicate the 'points' part of 'linepoints':
  7110. $alt_flag = $paired ? 1 : 0;
  7111. // Data labels, Data Value Labels? (Skip if doing the points from a linepoints plot)
  7112. if ($this->datatype_swapped_xy) {
  7113. // Horizontal plots can have X Data Value Labels, Y Axis Data Labels
  7114. $do_x_axis_labels = FALSE;
  7115. $do_x_valu_labels = !$paired && $this->CheckDataValueLabels($this->x_data_label_pos, $dvl);
  7116. $do_y_axis_labels = !$paired && $this->y_data_label_pos != 'none';
  7117. $do_y_valu_labels = FALSE;
  7118. } else {
  7119. // Vertical plots can have X Axis Data Labels, Y Data Value Labels
  7120. $do_x_axis_labels = !$paired && $this->x_data_label_pos != 'none';
  7121. $do_x_valu_labels = FALSE;
  7122. $do_y_axis_labels = FALSE;
  7123. $do_y_valu_labels = !$paired && $this->CheckDataValueLabels($this->y_data_label_pos, $dvl);
  7124. }
  7125. for ($row = 0; $row < $this->num_data_rows; $row++) {
  7126. $rec = 1; // Skip record #0 (data label)
  7127. if ($this->datatype_implied) // Implied independent variable values?
  7128. $iv = 0.5 + $row; // Place text-data at 0.5, 1.5, 2.5, etc...
  7129. else
  7130. $iv = $this->data[$row][$rec++]; // Read it, advance record index
  7131. // Axis data label?
  7132. if ($do_x_axis_labels)
  7133. $this->DrawXDataLabel($this->data[$row][0], $this->xtr($iv), $row, TRUE);
  7134. elseif ($do_y_axis_labels)
  7135. $this->DrawYDataLabel($this->data[$row][0], $this->ytr($iv), $row, TRUE);
  7136. // Proceed with dependent values
  7137. for ($idx = 0; $rec < $this->num_recs[$row]; $idx++) {
  7138. if (is_numeric($dv = $this->data[$row][$rec++])) { // Allow for missing data
  7139. // Select the color(s):
  7140. if ($this->datatype_error_bars) {
  7141. $this->GetDataErrorColors($row, $idx, $gcvars, $data_color, $error_color, $alt_flag);
  7142. } else {
  7143. $this->GetDataColor($row, $idx, $gcvars, $data_color, $alt_flag);
  7144. }
  7145. // Draw the marker, and error bar (if enabled):
  7146. if ($this->datatype_swapped_xy) {
  7147. $this->DrawDot($row, $idx, $dv, $iv, $data_color);
  7148. if ($this->datatype_error_bars) {
  7149. $this->DrawXErrorBars($dv, $iv, $this->data[$row][$rec],
  7150. $this->data[$row][$rec+1], $error_color);
  7151. }
  7152. } else {
  7153. $this->DrawDot($row, $idx, $iv, $dv, $data_color);
  7154. if ($this->datatype_error_bars) {
  7155. $this->DrawYErrorBars($iv, $dv, $this->data[$row][$rec],
  7156. $this->data[$row][$rec+1], $error_color);
  7157. }
  7158. }
  7159. // Draw data value labels?
  7160. if ($do_y_valu_labels) { // Vertical plot
  7161. $this->DrawDataValueLabel('y', $row, $idx, $iv, $dv, $dv, $dvl);
  7162. } elseif ($do_x_valu_labels) { // Horizontal plot
  7163. $this->DrawDataValueLabel('x', $row, $idx, $dv, $iv, $dv, $dvl);
  7164. }
  7165. }
  7166. if ($this->datatype_error_bars) {
  7167. $rec += 2; // Skip over error bar values, even in missing data case.
  7168. }
  7169. }
  7170. }
  7171. return TRUE;
  7172. }
  7173. /**
  7174. * Draws a thinbarline plot (Thin Bar Line)
  7175. *
  7176. * This is the main function for drawing a thinbarline plot, which
  7177. * is also known as an Impulse plot. Supported data types are
  7178. * data-data and text-data for vertical plots, and data-data-yx and
  7179. * text-data-yx for horizontal plots. "iv" is used for the independent
  7180. * variable (X for vertical plots, Y for horizontal) and "dv" is used
  7181. * for the dependent variable (Y or X respectively).
  7182. *
  7183. * Although this plot type supports multiple data sets, it rarely makes
  7184. * sense to have more than one, because the lines will overlay.
  7185. *
  7186. * @return bool True (False on error if an error handler returns True)
  7187. */
  7188. protected function DrawThinBarLines()
  7189. {
  7190. if (!$this->CheckDataType('text-data, data-data, text-data-yx, data-data-yx'))
  7191. return FALSE;
  7192. $gcvars = array(); // For GetDataColor, which initializes and uses this.
  7193. for ($row = 0; $row < $this->num_data_rows; $row++) {
  7194. $rec = 1; // Skip record #0 (data label)
  7195. if ($this->datatype_implied) // Implied independent variable values?
  7196. $iv_now = 0.5 + $row; // Place text-data at 0.5, 1.5, 2.5, etc...
  7197. else
  7198. $iv_now = $this->data[$row][$rec++]; // Read it, advance record index
  7199. if ($this->datatype_swapped_xy) {
  7200. $y_now_pixels = $this->ytr($iv_now);
  7201. // Draw Y Data labels?
  7202. if ($this->y_data_label_pos != 'none')
  7203. $this->DrawYDataLabel($this->data[$row][0], $y_now_pixels, $row);
  7204. } else {
  7205. $x_now_pixels = $this->xtr($iv_now);
  7206. // Draw X Data labels?
  7207. if ($this->x_data_label_pos != 'none')
  7208. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
  7209. }
  7210. // Proceed with dependent values
  7211. for ($idx = 0; $rec < $this->num_recs[$row]; $rec++, $idx++) {
  7212. if (is_numeric($dv = $this->data[$row][$rec])) { // Allow for missing data
  7213. ImageSetThickness($this->img, $this->line_widths[$idx]);
  7214. // Select the color:
  7215. $this->GetDataColor($row, $idx, $gcvars, $data_color);
  7216. if ($this->datatype_swapped_xy) {
  7217. // Draw a line from user defined y axis position right (or left) to xtr($dv)
  7218. ImageLine($this->img, $this->y_axis_x_pixels, $y_now_pixels,
  7219. $this->xtr($dv), $y_now_pixels, $data_color);
  7220. } else {
  7221. // Draw a line from user defined x axis position up (or down) to ytr($dv)
  7222. ImageLine($this->img, $x_now_pixels, $this->x_axis_y_pixels,
  7223. $x_now_pixels, $this->ytr($dv), $data_color);
  7224. }
  7225. }
  7226. }
  7227. }
  7228. ImageSetThickness($this->img, 1);
  7229. return TRUE;
  7230. }
  7231. /**
  7232. * Draws an area or stackedarea plot
  7233. *
  7234. * This is the main function for drawing area and stackedarea plots. Both
  7235. * of these fill the area between lines, but 'stackedarea' is cumulative (like
  7236. * stackedbars), and 'area' is not. Also 'area' fills from the last data set to
  7237. * the X axis, and 'stackedarea' fills from the X axis to the first data set.
  7238. * 'area' and 'stackedarea' plots are identical when there is only one data set.
  7239. *
  7240. * Supported data types are data-data and text-data. All Y values must be
  7241. * >= 0 (with absolute value used if any negative values are found).
  7242. * Missing data points are not supported (any missing points are set to
  7243. * 0). All rows must have the same number of Y points, or an error will
  7244. * be produced.
  7245. *
  7246. * @param bool $do_stacked True for stackedarea plot, false or omit for area plot
  7247. * @return bool True (False on error if an error handler returns True)
  7248. */
  7249. protected function DrawArea($do_stacked = FALSE)
  7250. {
  7251. if (!$this->CheckDataType('text-data, data-data'))
  7252. return FALSE;
  7253. // Validation: Need at least 2 rows; all rows must have same number of columns.
  7254. if (($n_rows = $this->num_data_rows) < 2) return TRUE;
  7255. if ($this->records_per_group != min($this->num_recs)) {
  7256. return $this->PrintError("DrawArea(): Data array must contain the same number"
  7257. . " of Y values for each X");
  7258. }
  7259. // Calculate and store device coordinates xd[] and yd[][], and draw the data labels.
  7260. $n_columns = $this->SetupAreaPlot($do_stacked, $xd, $yd);
  7261. // Draw the filled polygons.
  7262. // Note data_columns is the number of Y points (columns excluding label and X), and the
  7263. // number of entries in the yd[] arrays is data_columns+1.
  7264. $prev_col = 0;
  7265. for ($col = 1; $col < $n_columns; $col++) { // 1 extra for X axis artificial column
  7266. $pts = array();
  7267. // Previous data set forms top (for area) or bottom (for stackedarea):
  7268. for ($row = 0; $row < $n_rows; $row++) {
  7269. array_push($pts, $xd[$row], $yd[$row][$prev_col]);
  7270. }
  7271. // Current data set forms bottom (for area) or top (for stackedarea):
  7272. for ($row = $n_rows - 1; $row >= 0; $row--) {
  7273. array_push($pts, $xd[$row], $yd[$row][$col]);
  7274. }
  7275. // Draw it:
  7276. ImageFilledPolygon($this->img, $pts, $n_rows * 2, $this->ndx_data_colors[$prev_col]);
  7277. $prev_col = $col;
  7278. }
  7279. // Draw the data borders, if enabled. (After, else the area fills cover parts of it.)
  7280. if (!empty($this->draw_data_borders))
  7281. $this->DrawAreaFillBorders($n_columns, $xd, $yd, $do_stacked, FALSE);
  7282. return TRUE;
  7283. }
  7284. /**
  7285. * Draws a lines plot, or the lines for a linepoints plot
  7286. *
  7287. * This is the main function for drawing a lines plot, and is also used
  7288. * for a linepoints plot. Vertical and Horizontal plots, and error plots,
  7289. * are all supported. "iv" is used for the independent variable (X for
  7290. * vertical plots, Y for horizontal) and "dv" is used for the dependent
  7291. * variable (Y or X respectively).
  7292. *
  7293. * When $paired is true, a linepoints plot is being drawn, and some
  7294. * elements are suppressed here because they are done elsewhere. See
  7295. * DrawLinePoints() for details.
  7296. *
  7297. * @param bool $paired True if doing a linepoints plots, False or omit for lines plot
  7298. * @return bool True (False on error if an error handler returns True)
  7299. */
  7300. protected function DrawLines($paired = FALSE)
  7301. {
  7302. if (!$this->CheckDataType('text-data, data-data, text-data-yx, data-data-yx, '
  7303. . 'data-data-error, data-data-yx-error'))
  7304. return FALSE;
  7305. // Flag array telling if the current point is valid, one element per plot line.
  7306. // If start_lines[i] is true, then (lastx[i], lasty[i]) is the previous point.
  7307. if ($this->data_columns > 0)
  7308. $start_lines = array_fill(0, $this->data_columns, FALSE);
  7309. $gcvars = array(); // For GetDataColor, which initializes and uses this.
  7310. // Data labels, Data Value Labels?
  7311. if ($this->datatype_swapped_xy) {
  7312. // Horizontal plots can have X Data Value Labels, Y Axis Data Labels
  7313. $do_x_axis_labels = FALSE;
  7314. $do_x_valu_labels = $this->CheckDataValueLabels($this->x_data_label_pos, $dvl);
  7315. $do_y_axis_labels = $this->y_data_label_pos != 'none';
  7316. $do_y_valu_labels = FALSE;
  7317. } else {
  7318. // Vertical plots can have X Axis Data Labels, Y Data Value Labels
  7319. $do_x_axis_labels = $this->x_data_label_pos != 'none';
  7320. $do_x_valu_labels = FALSE;
  7321. $do_y_axis_labels = FALSE;
  7322. $do_y_valu_labels = $this->CheckDataValueLabels($this->y_data_label_pos, $dvl);
  7323. }
  7324. for ($row = 0; $row < $this->num_data_rows; $row++) {
  7325. $rec = 1; // Skip record #0 (data label)
  7326. if ($this->datatype_implied) // Implied X values?
  7327. $iv = 0.5 + $row; // Place text-data at X = 0.5, 1.5, 2.5, etc...
  7328. else
  7329. $iv = $this->data[$row][$rec++]; // Get actual X value from array
  7330. // Convert independent variable to device coordinates
  7331. if ($this->datatype_swapped_xy) {
  7332. $y_now_pixels = $this->ytr($iv);
  7333. } else {
  7334. $x_now_pixels = $this->xtr($iv);
  7335. }
  7336. // Axis data label?
  7337. if ($do_x_axis_labels)
  7338. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row, TRUE);
  7339. elseif ($do_y_axis_labels)
  7340. $this->DrawYDataLabel($this->data[$row][0], $y_now_pixels, $row, TRUE);
  7341. // Proceed with dependent values
  7342. for ($idx = 0; $rec < $this->num_recs[$row]; $idx++) {
  7343. $line_style = $this->line_styles[$idx];
  7344. // Skip point if data value is missing. Also skip if the whole line is suppressed
  7345. // with style='none' (useful with linepoints plots)
  7346. if (is_numeric($dv = $this->data[$row][$rec++]) && $line_style != 'none') {
  7347. // Convert dependent variable to device coordinates
  7348. if ($this->datatype_swapped_xy) {
  7349. $x_now_pixels = $this->xtr($dv);
  7350. } else {
  7351. $y_now_pixels = $this->ytr($dv);
  7352. }
  7353. // Select the color(s):
  7354. if ($this->datatype_error_bars) {
  7355. $this->GetDataErrorColors($row, $idx, $gcvars, $data_color, $error_color);
  7356. } else {
  7357. $this->GetDataColor($row, $idx, $gcvars, $data_color);
  7358. }
  7359. if ($start_lines[$idx]) {
  7360. // Set line width, revert it to normal at the end
  7361. ImageSetThickness($this->img, $this->line_widths[$idx]);
  7362. // Select solid color or dashed line
  7363. $style = $this->SetDashedStyle($data_color, $line_style == 'dashed');
  7364. // Draw the line segment:
  7365. ImageLine($this->img, $x_now_pixels, $y_now_pixels,
  7366. $lastx[$idx], $lasty[$idx], $style);
  7367. }
  7368. // Draw error bars, but not for linepoints plots, because DrawPoints() does it.
  7369. if ($this->datatype_error_bars && !$paired) {
  7370. if ($this->datatype_swapped_xy) {
  7371. $this->DrawXErrorBars($dv, $iv, $this->data[$row][$rec],
  7372. $this->data[$row][$rec+1], $error_color);
  7373. } else {
  7374. $this->DrawYErrorBars($iv, $dv, $this->data[$row][$rec],
  7375. $this->data[$row][$rec+1], $error_color);
  7376. }
  7377. }
  7378. // Draw data value labels?
  7379. if ($do_y_valu_labels) // Vertical plot
  7380. $this->DrawDataValueLabel('y', $row, $idx, $iv, $dv, $dv, $dvl);
  7381. elseif ($do_x_valu_labels) // Horizontal plot
  7382. $this->DrawDataValueLabel('x', $row, $idx, $dv, $iv, $dv, $dvl);
  7383. $lastx[$idx] = $x_now_pixels;
  7384. $lasty[$idx] = $y_now_pixels;
  7385. $start_lines[$idx] = TRUE;
  7386. } elseif ($this->draw_broken_lines) {
  7387. $start_lines[$idx] = FALSE; // Missing point value or line style suppression
  7388. }
  7389. if ($this->datatype_error_bars)
  7390. $rec += 2; // Skip over error bar values, even in missing data case.
  7391. }
  7392. }
  7393. ImageSetThickness($this->img, 1); // Revert to original state for lines to be drawn later.
  7394. return TRUE;
  7395. }
  7396. /**
  7397. * Draws a linepoints plot (Lines and Points)
  7398. *
  7399. * This is the main function for drawing a linepoints plot. This just uses
  7400. * DrawLines() to draw the lines, and DrawDots() to draw the points, so it
  7401. * supports the same data types and variations as they do.
  7402. *
  7403. * The argument passed to the two drawing functions tells them not to
  7404. * duplicate elements, as follows: DrawLines() draws the lines, not the
  7405. * error bars (even if applicable), and the data labels. DrawDots() draws
  7406. * the points, the error bars (if applicable), and not the data labels.
  7407. *
  7408. * @return bool True (False on error if an error handler returns True)
  7409. * @since 5.1.3
  7410. */
  7411. protected function DrawLinePoints()
  7412. {
  7413. return $this->DrawLines(TRUE) && $this->DrawDots(TRUE);
  7414. }
  7415. /**
  7416. * Draws a squared plot (Squared Line, Stepped Line)
  7417. *
  7418. * This is the main function for drawing a squared plot. Supported data
  7419. * types are data-data and text-data. This is based on DrawLines(), with
  7420. * two line segments drawn for each point.
  7421. *
  7422. * @return bool True (False on error if an error handler returns True)
  7423. */
  7424. protected function DrawSquared()
  7425. {
  7426. if (!$this->CheckDataType('text-data, data-data'))
  7427. return FALSE;
  7428. // Flag array telling if the current point is valid, one element per plot line.
  7429. // If start_lines[i] is true, then (lastx[i], lasty[i]) is the previous point.
  7430. if ($this->data_columns > 0)
  7431. $start_lines = array_fill(0, $this->data_columns, FALSE);
  7432. $gcvars = array(); // For GetDataColor, which initializes and uses this.
  7433. // Data Value Labels?
  7434. $do_dvls = $this->CheckDataValueLabels($this->y_data_label_pos, $dvl);
  7435. for ($row = 0; $row < $this->num_data_rows; $row++) {
  7436. $record = 1; // Skip record #0 (data label)
  7437. if ($this->datatype_implied) // Implied X values?
  7438. $x_now = 0.5 + $row; // Place text-data at X = 0.5, 1.5, 2.5, etc...
  7439. else
  7440. $x_now = $this->data[$row][$record++]; // Read it, advance record index
  7441. $x_now_pixels = $this->xtr($x_now); // Absolute coordinates
  7442. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  7443. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
  7444. // Draw Lines
  7445. for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
  7446. if (is_numeric($y_now = $this->data[$row][$record])) { // Allow for missing Y data
  7447. $y_now_pixels = $this->ytr($y_now);
  7448. if ($start_lines[$idx]) {
  7449. // Set line width, revert it to normal at the end
  7450. ImageSetThickness($this->img, $this->line_widths[$idx]);
  7451. // Select the color:
  7452. $this->GetDataColor($row, $idx, $gcvars, $data_color);
  7453. // Select solid color or dashed line
  7454. $style = $this->SetDashedStyle($data_color, $this->line_styles[$idx] == 'dashed');
  7455. // Draw the step:
  7456. $y_mid = $lasty[$idx];
  7457. ImageLine($this->img, $lastx[$idx], $y_mid, $x_now_pixels, $y_mid, $style);
  7458. ImageLine($this->img, $x_now_pixels, $y_mid, $x_now_pixels, $y_now_pixels, $style);
  7459. }
  7460. // Draw data value labels?
  7461. if ($do_dvls)
  7462. $this->DrawDataValueLabel('y', $row, $idx, $x_now, $y_now, $y_now, $dvl);
  7463. $lastx[$idx] = $x_now_pixels;
  7464. $lasty[$idx] = $y_now_pixels;
  7465. $start_lines[$idx] = TRUE;
  7466. } elseif ($this->draw_broken_lines) { // Y data missing, leave a gap.
  7467. $start_lines[$idx] = FALSE;
  7468. }
  7469. }
  7470. }
  7471. ImageSetThickness($this->img, 1);
  7472. return TRUE;
  7473. }
  7474. /**
  7475. * Draws a squaredarea or stackedsquaredarea plot (Squared Area)
  7476. *
  7477. * This is the main function for drawing squaredarea and stackedsquaredarea plots,
  7478. * which area a blend of 'squared' plus either 'area' or 'stackedarea'. Supported
  7479. * data types are data-data and text-data. Missing points are not allowed,
  7480. * and all data sets must have the same number of points.
  7481. *
  7482. * @param bool $do_stacked True for cumulative (stacked), false or omit for unstacked.
  7483. * @return bool True (False on error if an error handler returns True)
  7484. */
  7485. protected function DrawSquaredArea($do_stacked = FALSE)
  7486. {
  7487. if (!$this->CheckDataType('text-data, data-data'))
  7488. return FALSE;
  7489. // Validation: Need at least 2 rows; all rows must have same number of columns.
  7490. if (($n_rows = $this->num_data_rows) < 2) return TRUE;
  7491. if ($this->records_per_group != min($this->num_recs)) {
  7492. return $this->PrintError("DrawSquaredArea(): Data array must contain the same number"
  7493. . " of Y values for each X");
  7494. }
  7495. // Calculate and store device coordinates xd[] and yd[][], and draw the data labels.
  7496. $n_columns = $this->SetupAreaPlot($do_stacked, $xd, $yd);
  7497. // Draw a filled polygon for each Y column
  7498. $prev_col = 0;
  7499. for ($col = 1; $col < $n_columns; $col++) { // 1 extra for X axis artificial column
  7500. // Current data set forms the top. For each point after the first, add 2 points.
  7501. $x_prev = $xd[0];
  7502. $y_prev = $yd[0][$col];
  7503. $pts = array($x_prev, $y_prev); // Bottom left point
  7504. for ($row = 1; $row < $n_rows; $row++) {
  7505. $x = $xd[$row];
  7506. $y = $yd[$row][$col];
  7507. array_push($pts, $x, $y_prev, $x, $y);
  7508. $x_prev = $x;
  7509. $y_prev = $y;
  7510. }
  7511. // Previous data set forms the bottom. Process right to left.
  7512. // Note $row is now $n_rows, and it will be stepped back to 0.
  7513. $row--;
  7514. $x_prev = $xd[$row];
  7515. $y_prev = $yd[$row][$prev_col];
  7516. array_push($pts, $x_prev, $y_prev); // Bottom right point
  7517. while (--$row >= 0) {
  7518. $x = $xd[$row];
  7519. $y = $yd[$row][$prev_col];
  7520. array_push($pts, $x_prev, $y, $x, $y);
  7521. $x_prev = $x;
  7522. $y_prev = $y;
  7523. }
  7524. // Draw the resulting polygon, which has (2 * (1 + 2*(n_rows-1))) points:
  7525. ImageFilledPolygon($this->img, $pts, 4 * $n_rows - 2, $this->ndx_data_colors[$prev_col]);
  7526. $prev_col = $col;
  7527. }
  7528. // Draw the data borders, if enabled. (After, else the area fills cover parts of it.)
  7529. if (!empty($this->draw_data_borders))
  7530. $this->DrawAreaFillBorders($n_columns, $xd, $yd, $do_stacked, TRUE);
  7531. return TRUE;
  7532. }
  7533. /**
  7534. * Draws a bars plot (Bar chart)
  7535. *
  7536. * This is the main function for drawing a bars plot. Supported data
  7537. * types are text-data, for vertical plots, and text-data-yx, for
  7538. * horizontal plots (for which it calls DrawHorizBars()).
  7539. *
  7540. * @return bool True (False on error if an error handler returns True)
  7541. */
  7542. protected function DrawBars()
  7543. {
  7544. if (!$this->CheckDataType('text-data, text-data-yx'))
  7545. return FALSE;
  7546. if ($this->datatype_swapped_xy)
  7547. return $this->DrawHorizBars();
  7548. $this->CalcBarWidths(FALSE, TRUE); // Calculate bar widths for unstacked, vertical
  7549. // This is the X offset from the bar group's label center point to the left side of the first bar
  7550. // in the group. See also CalcBarWidths above.
  7551. $x_first_bar = ($this->data_columns * $this->record_bar_width) / 2 - $this->bar_adjust_gap;
  7552. $gcvars = array(); // For GetBarColors, which initializes and uses this.
  7553. for ($row = 0; $row < $this->num_data_rows; $row++) {
  7554. $record = 1; // Skip record #0 (data label)
  7555. $x_now_pixels = $this->xtr(0.5 + $row); // Place text-data at X = 0.5, 1.5, 2.5, etc...
  7556. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  7557. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
  7558. // Lower left X of first bar in the group:
  7559. $x1 = $x_now_pixels - $x_first_bar;
  7560. // Draw the bars in the group:
  7561. for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
  7562. if (is_numeric($y = $this->data[$row][$record])) { // Allow for missing Y data
  7563. $x2 = $x1 + $this->actual_bar_width;
  7564. if (($upgoing_bar = $y >= $this->x_axis_position)) {
  7565. $y1 = $this->ytr($y);
  7566. $y2 = $this->x_axis_y_pixels;
  7567. } else {
  7568. $y1 = $this->x_axis_y_pixels;
  7569. $y2 = $this->ytr($y);
  7570. }
  7571. // Select the colors:
  7572. $this->GetBarColors($row, $idx, $gcvars, $data_color, $shade_color, $border_color);
  7573. // Draw the bar, and the shade or border:
  7574. $this->DrawBar($row, $idx, $x1, $y1, $x2, $y2, $data_color, $shade_color, $border_color);
  7575. // Draw optional data value label above or below the bar:
  7576. if ($this->y_data_label_pos == 'plotin') {
  7577. $dvl['x_offset'] = ($idx + 0.5) * $this->record_bar_width - $x_first_bar;
  7578. if ($upgoing_bar) {
  7579. $dvl['v_align'] = 'bottom';
  7580. $dvl['y_offset'] = -5 - $this->shading;
  7581. } else {
  7582. $dvl['v_align'] = 'top';
  7583. $dvl['y_offset'] = 2;
  7584. }
  7585. $this->DrawDataValueLabel('y', $row, $idx, $row+0.5, $y, $y, $dvl);
  7586. }
  7587. }
  7588. // Step to next bar in group:
  7589. $x1 += $this->record_bar_width;
  7590. }
  7591. }
  7592. return TRUE;
  7593. }
  7594. /**
  7595. * Draws a Horizontal Bar chart
  7596. *
  7597. * This is called from DrawBars() when the data type indicates a
  7598. * horizontal plot.
  7599. *
  7600. * @return bool True (False on error if an error handler returns True)
  7601. * @since 5.1.2
  7602. */
  7603. protected function DrawHorizBars()
  7604. {
  7605. $this->CalcBarWidths(FALSE, FALSE); // Calculate bar widths for unstacked, vertical
  7606. // This is the Y offset from the bar group's label center point to the bottom of the first bar
  7607. // in the group. See also CalcBarWidths above.
  7608. $y_first_bar = ($this->data_columns * $this->record_bar_width) / 2 - $this->bar_adjust_gap;
  7609. $gcvars = array(); // For GetBarColors, which initializes and uses this.
  7610. for ($row = 0; $row < $this->num_data_rows; $row++) {
  7611. $record = 1; // Skip record #0 (data label)
  7612. $y_now_pixels = $this->ytr(0.5 + $row); // Place bars at Y=0.5, 1.5, 2.5, etc...
  7613. if ($this->y_data_label_pos != 'none') // Draw Y Data Labels?
  7614. $this->DrawYDataLabel($this->data[$row][0], $y_now_pixels, $row);
  7615. // Lower left Y of first bar in the group:
  7616. $y1 = $y_now_pixels + $y_first_bar;
  7617. // Draw the bars in the group:
  7618. for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
  7619. if (is_numeric($x = $this->data[$row][$record])) { // Allow for missing X data
  7620. $y2 = $y1 - $this->actual_bar_width;
  7621. if (($rightwards_bar = $x >= $this->y_axis_position)) {
  7622. $x1 = $this->xtr($x);
  7623. $x2 = $this->y_axis_x_pixels;
  7624. } else {
  7625. $x1 = $this->y_axis_x_pixels;
  7626. $x2 = $this->xtr($x);
  7627. }
  7628. // Select the colors:
  7629. $this->GetBarColors($row, $idx, $gcvars, $data_color, $shade_color, $border_color);
  7630. // Draw the bar, and the shade or border:
  7631. $this->DrawBar($row, $idx, $x1, $y1, $x2, $y2, $data_color, $shade_color, $border_color);
  7632. // Draw optional data value label to the right or left of the bar:
  7633. if ($this->x_data_label_pos == 'plotin') {
  7634. $dvl['y_offset'] = $y_first_bar - ($idx + 0.5) * $this->record_bar_width;
  7635. if ($rightwards_bar) {
  7636. $dvl['h_align'] = 'left';
  7637. $dvl['x_offset'] = 5 + $this->shading;
  7638. } else {
  7639. $dvl['h_align'] = 'right';
  7640. $dvl['x_offset'] = -2;
  7641. }
  7642. $this->DrawDataValueLabel('x', $row, $idx, $x, $row+0.5, $x, $dvl);
  7643. }
  7644. }
  7645. // Step to next bar in group:
  7646. $y1 -= $this->record_bar_width;
  7647. }
  7648. }
  7649. return TRUE;
  7650. }
  7651. /**
  7652. * Draws a stackedbars plot (Stacked Bar chart)
  7653. *
  7654. * This is the main function for drawing a stackedbars plot. Supported
  7655. * data types are text-data, for vertical plots, and text-data-yx, for
  7656. * horizontal plots (for which it calls DrawHorizStackedBars()).
  7657. * Original stacked bars idea by Laurent Kruk < lolok at users.sourceforge.net >
  7658. *
  7659. * @return bool True (False on error if an error handler returns True)
  7660. */
  7661. protected function DrawStackedBars()
  7662. {
  7663. if (!$this->CheckDataType('text-data, text-data-yx'))
  7664. return FALSE;
  7665. if ($this->datatype_swapped_xy)
  7666. return $this->DrawHorizStackedBars();
  7667. $this->CalcBarWidths(TRUE, TRUE); // Calculate bar widths for stacked, vertical
  7668. // This is the X offset from the bar's label center point to the left side of the bar.
  7669. $x_first_bar = $this->record_bar_width / 2 - $this->bar_adjust_gap;
  7670. $gcvars = array(); // For GetBarColors, which initializes and uses this.
  7671. // Determine if any data labels are on:
  7672. $data_labels_within = ($this->y_data_label_pos == 'plotstack');
  7673. $data_labels_end = $data_labels_within || ($this->y_data_label_pos == 'plotin');
  7674. $data_label_y_offset = -5 - $this->shading; // For upward labels only.
  7675. for ($row = 0; $row < $this->num_data_rows; $row++) {
  7676. $record = 1; // Skip record #0 (data label)
  7677. $x_now_pixels = $this->xtr(0.5 + $row); // Place text-data at X = 0.5, 1.5, 2.5, etc...
  7678. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  7679. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
  7680. // Determine bar direction based on 1st non-zero value. Note the bar direction is
  7681. // based on zero, not the axis value.
  7682. $n_recs = $this->num_recs[$row];
  7683. $upward = TRUE; // Initialize this for the case of all segments = 0
  7684. for ($i = $record; $i < $n_recs; $i++) {
  7685. if (is_numeric($this_y = $this->data[$row][$i]) && $this_y != 0) {
  7686. $upward = ($this_y > 0);
  7687. break;
  7688. }
  7689. }
  7690. $x1 = $x_now_pixels - $x_first_bar; // Left X of bars in this stack
  7691. $x2 = $x1 + $this->actual_bar_width; // Right X of bars in this stack
  7692. $wy1 = 0; // World coordinates Y1, current sum of values
  7693. $wy2 = $this->x_axis_position; // World coordinates Y2, last drawn value
  7694. // Draw bar segments and labels in this stack.
  7695. $first = TRUE;
  7696. for ($idx = 0; $record < $n_recs; $record++, $idx++) {
  7697. // Skip missing Y values. Process Y=0 values due to special case of moved axis.
  7698. if (is_numeric($this_y = $this->data[$row][$record])) {
  7699. $wy1 += $this_y; // Keep the running total for this bar stack
  7700. // Draw the segment only if it will increase the stack height (ignore if wrong direction):
  7701. if (($upward && $wy1 > $wy2) || (!$upward && $wy2 > $wy1)) {
  7702. $y1 = $this->ytr($wy1); // Convert to device coordinates. $y1 is outermost value.
  7703. $y2 = $this->ytr($wy2); // $y2 is innermost (closest to axis).
  7704. // Select the colors:
  7705. $this->GetBarColors($row, $idx, $gcvars, $data_color, $shade_color, $border_color);
  7706. // Draw the bar, and the shade or border:
  7707. $this->DrawBar($row, $idx, $x1, $y1, $x2, $y2,
  7708. $data_color, $shade_color, $border_color,
  7709. // Only shade the top for upward bars, or the first segment of downward bars:
  7710. $upward || $first, TRUE);
  7711. // Draw optional data label for this bar segment just inside the end.
  7712. // Text value is the current Y, but position is the cumulative Y.
  7713. // The label is only drawn if it fits in the segment height |y2-y1|.
  7714. if ($data_labels_within) {
  7715. $dvl['min_height'] = abs($y1 - $y2);
  7716. if ($upward) {
  7717. $dvl['v_align'] = 'top';
  7718. $dvl['y_offset'] = 3;
  7719. } else {
  7720. $dvl['v_align'] = 'bottom';
  7721. $dvl['y_offset'] = -3;
  7722. }
  7723. $this->DrawDataValueLabel('y', $row, $idx, $row+0.5, $wy1, $this_y, $dvl);
  7724. }
  7725. // Mark the new end of the bar, conditional on segment height > 0.
  7726. $wy2 = $wy1;
  7727. $first = FALSE;
  7728. }
  7729. }
  7730. } // end for
  7731. // Draw optional data label above the bar with the total value.
  7732. // Value is wy1 (total value), but position is wy2 (end of the bar stack).
  7733. // These differ only with wrong-direction segments, or a stack completely clipped by the axis.
  7734. if ($data_labels_end) {
  7735. $dvl['min_height'] = NULL; // Might be set above, but the whole array might not exist.
  7736. if ($upward) {
  7737. $dvl['v_align'] = 'bottom';
  7738. $dvl['y_offset'] = $data_label_y_offset;
  7739. } else {
  7740. $dvl['v_align'] = 'top';
  7741. $dvl['y_offset'] = 5;
  7742. }
  7743. $this->DrawDataValueLabel('y', $row, NULL, $row+0.5, $wy2, $wy1, $dvl);
  7744. }
  7745. } // end for
  7746. return TRUE;
  7747. }
  7748. /**
  7749. * Draws a Horizontal Stacked Bar chart
  7750. *
  7751. * This is called from DrawStackedBars() when the data type indicates a
  7752. * horizontal plot.
  7753. *
  7754. * @return bool True (False on error if an error handler returns True)
  7755. * @since 5.1.3
  7756. */
  7757. protected function DrawHorizStackedBars()
  7758. {
  7759. $this->CalcBarWidths(TRUE, FALSE); // Calculate bar widths for stacked, horizontal
  7760. // This is the Y offset from the bar's label center point to the bottom of the bar
  7761. $y_first_bar = $this->record_bar_width / 2 - $this->bar_adjust_gap;
  7762. $gcvars = array(); // For GetBarColors, which initializes and uses this.
  7763. // Determine if any data labels are on:
  7764. $data_labels_within = ($this->x_data_label_pos == 'plotstack');
  7765. $data_labels_end = $data_labels_within || ($this->x_data_label_pos == 'plotin');
  7766. $data_label_x_offset = 5 + $this->shading; // For rightward labels only
  7767. for ($row = 0; $row < $this->num_data_rows; $row++) {
  7768. $record = 1; // Skip record #0 (data label)
  7769. $y_now_pixels = $this->ytr(0.5 + $row); // Place bars at Y=0.5, 1.5, 2.5, etc...
  7770. if ($this->y_data_label_pos != 'none') // Draw Y Data labels?
  7771. $this->DrawYDataLabel($this->data[$row][0], $y_now_pixels, $row);
  7772. // Determine bar direction based on 1st non-zero value. Note the bar direction is
  7773. // based on zero, not the axis value.
  7774. $n_recs = $this->num_recs[$row];
  7775. $rightward = TRUE; // Initialize this for the case of all segments = 0
  7776. for ($i = $record; $i < $n_recs; $i++) {
  7777. if (is_numeric($this_x = $this->data[$row][$i]) && $this_x != 0) {
  7778. $rightward = ($this_x > 0);
  7779. break;
  7780. }
  7781. }
  7782. // Lower left and upper left Y of the bars in this stack:
  7783. $y1 = $y_now_pixels + $y_first_bar; // Lower Y of bars in this stack
  7784. $y2 = $y1 - $this->actual_bar_width; // Upper Y of bars in this stack
  7785. $wx1 = 0; // World coordinates X1, current sum of values
  7786. $wx2 = $this->y_axis_position; // World coordinates X2, last drawn value
  7787. // Draw bar segments and labels in this stack.
  7788. $first = TRUE;
  7789. for ($idx = 0; $record < $this->num_recs[$row]; $record++, $idx++) {
  7790. // Skip missing X values. Process X=0 values due to special case of moved axis.
  7791. if (is_numeric($this_x = $this->data[$row][$record])) {
  7792. $wx1 += $this_x; // Keep the running total for this bar stack
  7793. // Draw the segment only if it will increase the stack length (ignore if wrong direction):
  7794. if (($rightward && $wx1 > $wx2) || (!$rightward && $wx2 > $wx1)) {
  7795. $x1 = $this->xtr($wx1); // Convert to device coordinates. $x1 is outermost value.
  7796. $x2 = $this->xtr($wx2); // $x2 is innermost (closest to axis).
  7797. // Select the colors:
  7798. $this->GetBarColors($row, $idx, $gcvars, $data_color, $shade_color, $border_color);
  7799. // Draw the bar, and the shade or border:
  7800. $this->DrawBar($row, $idx, $x1, $y1, $x2, $y2,
  7801. $data_color, $shade_color, $border_color,
  7802. // Only shade the side for rightward bars, or the first segment of leftward bars:
  7803. TRUE, $rightward || $first);
  7804. // Draw optional data label for this bar segment just inside the end.
  7805. // Text value is the current X, but position is the cumulative X.
  7806. // The label is only drawn if it fits in the segment width |x2-x1|.
  7807. if ($data_labels_within) {
  7808. $dvl['min_width'] = abs($x1 - $x2);
  7809. if ($rightward) {
  7810. $dvl['h_align'] = 'right';
  7811. $dvl['x_offset'] = -3;
  7812. } else {
  7813. $dvl['h_align'] = 'left';
  7814. $dvl['x_offset'] = 3;
  7815. }
  7816. $this->DrawDataValueLabel('x', $row, $idx, $wx1, $row+0.5, $this_x, $dvl);
  7817. }
  7818. // Mark the new end of the bar, conditional on segment width > 0.
  7819. $wx2 = $wx1;
  7820. $first = FALSE;
  7821. }
  7822. }
  7823. } // end for
  7824. // Draw optional data label right of the bar with the total value.
  7825. // Value is wx1 (total value), but position is wx2 (end of the bar stack).
  7826. // These differ only with wrong-direction segments, or a stack completely clipped by the axis.
  7827. if ($data_labels_end) {
  7828. $dvl['min_width'] = NULL; // Might be set above, but the whole array might not exist.
  7829. if ($rightward) {
  7830. $dvl['h_align'] = 'left';
  7831. $dvl['x_offset'] = $data_label_x_offset;
  7832. } else {
  7833. $dvl['h_align'] = 'right';
  7834. $dvl['x_offset'] = -5;
  7835. }
  7836. $this->DrawDataValueLabel('x', $row, NULL, $wx2, $row+0.5, $wx1, $dvl);
  7837. }
  7838. } // end for
  7839. return TRUE;
  7840. }
  7841. /**
  7842. * Draws an ohlc, candlesticks, or candlesticks2 plot ("Open/High/Low/Close" OHLC plot)
  7843. *
  7844. * This is the main function for drawing an ohlc, candlesticks, or
  7845. * candlesticks2 plot, which are typically used to show price changes in
  7846. * financial instruments. Supported data types are text-data and
  7847. * data-data, each with exactly 4 Y values per row: Open, High, Low, and
  7848. * Close. The 2 parameters select one of the 3 plot subtypes.
  7849. *
  7850. * @param bool $draw_candles True to draw a candlestick plot, False to draw an ohlc plot
  7851. * @param bool $always_fill True to always fill, False or omit to fill only when closing down
  7852. * @return bool True (False on error if an error handler returns True)
  7853. * @since 5.3.0
  7854. */
  7855. protected function DrawOHLC($draw_candles, $always_fill = FALSE)
  7856. {
  7857. if (!$this->CheckDataType('text-data, data-data'))
  7858. return FALSE;
  7859. if ($this->data_columns != 4) // early error check (more inside the loop)
  7860. return $this->PrintError("DrawOHLC(): rows must have 4 values.");
  7861. // Assign name of GD function to draw candlestick bodies for stocks that close up.
  7862. $draw_body_close_up = $always_fill ? 'imagefilledrectangle' : 'imagerectangle';
  7863. // Calculate the half-width of the candle body, or length of the tick marks.
  7864. // This is scaled based on the plot density, but within tight limits.
  7865. $dw = max($this->ohlc_min_width, min($this->ohlc_max_width,
  7866. (int)($this->ohlc_frac_width * $this->plot_area_width / $this->num_data_rows)));
  7867. // Get line widths to use: index 0 for body/stroke, 1 for wick/tick.
  7868. list($body_thickness, $wick_thickness) = $this->line_widths;
  7869. $gcvars = array(); // For GetDataColor, which initializes and uses this.
  7870. for ($row = 0; $row < $this->num_data_rows; $row++) {
  7871. $record = 1; // Skip record #0 (data label)
  7872. if ($this->datatype_implied) // Implied X values?
  7873. $x_now = 0.5 + $row; // Place text-data at X = 0.5, 1.5, 2.5, etc...
  7874. else
  7875. $x_now = $this->data[$row][$record++]; // Read it, advance record index
  7876. $x_now_pixels = $this->xtr($x_now); // Convert X to device coordinates
  7877. $x_left = $x_now_pixels - $dw;
  7878. $x_right = $x_now_pixels + $dw;
  7879. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  7880. $this->DrawXDataLabel($this->data[$row][0], $x_now_pixels, $row);
  7881. // Each row must have 4 values, but skip rows with non-numeric entries.
  7882. if ($this->num_recs[$row] - $record != 4) {
  7883. return $this->PrintError("DrawOHLC(): row $row must have 4 values.");
  7884. }
  7885. if (!is_numeric($yo = $this->data[$row][$record++])
  7886. || !is_numeric($yh = $this->data[$row][$record++])
  7887. || !is_numeric($yl = $this->data[$row][$record++])
  7888. || !is_numeric($yc = $this->data[$row][$record++])) {
  7889. continue;
  7890. }
  7891. // Set device coordinates for each value and direction flag:
  7892. $yh_pixels = $this->ytr($yh);
  7893. $yl_pixels = $this->ytr($yl);
  7894. $yc_pixels = $this->ytr($yc);
  7895. $yo_pixels = $this->ytr($yo);
  7896. $closed_up = $yc >= $yo;
  7897. // Get data colors and line thicknesses:
  7898. if ($closed_up) {
  7899. $this->GetDataColor($row, 1, $gcvars, $body_color); // Color 1 for body, closing up
  7900. $this->GetDataColor($row, 3, $gcvars, $ext_color); // Color 3 for wicks/ticks
  7901. } else {
  7902. $this->GetDataColor($row, 0, $gcvars, $body_color); // Color 0 for body, closing down
  7903. $this->GetDataColor($row, 2, $gcvars, $ext_color); // Color 2 for wicks/ticks
  7904. }
  7905. imagesetthickness($this->img, $body_thickness);
  7906. if ($draw_candles) {
  7907. // Note: Unlike ImageFilledRectangle, ImageRectangle 'requires' its arguments in
  7908. // order with upper left corner first.
  7909. if ($closed_up) {
  7910. $yb1_pixels = $yc_pixels; // Upper body Y
  7911. $yb2_pixels = $yo_pixels; // Lower body Y
  7912. $draw_body = $draw_body_close_up;
  7913. // Avoid a PHP/GD bug resulting in "T"-shaped ends to zero height unfilled rectangle:
  7914. if ($yb1_pixels == $yb2_pixels)
  7915. $draw_body = 'imagefilledrectangle';
  7916. } else {
  7917. $yb1_pixels = $yo_pixels;
  7918. $yb2_pixels = $yc_pixels;
  7919. $draw_body = 'imagefilledrectangle';
  7920. }
  7921. // Draw candle body
  7922. $draw_body($this->img, $x_left, $yb1_pixels, $x_right, $yb2_pixels, $body_color);
  7923. // Draw upper and lower wicks, if they have height. (In device coords, that's dY<0)
  7924. imagesetthickness($this->img, $wick_thickness);
  7925. if ($yh_pixels < $yb1_pixels) {
  7926. imageline($this->img, $x_now_pixels, $yb1_pixels, $x_now_pixels, $yh_pixels, $ext_color);
  7927. }
  7928. if ($yl_pixels > $yb2_pixels) {
  7929. imageline($this->img, $x_now_pixels, $yb2_pixels, $x_now_pixels, $yl_pixels, $ext_color);
  7930. }
  7931. } else {
  7932. // Basic OHLC
  7933. imageline($this->img, $x_now_pixels, $yl_pixels, $x_now_pixels, $yh_pixels, $body_color);
  7934. imagesetthickness($this->img, $wick_thickness);
  7935. imageline($this->img, $x_left, $yo_pixels, $x_now_pixels, $yo_pixels, $ext_color);
  7936. imageline($this->img, $x_right, $yc_pixels, $x_now_pixels, $yc_pixels, $ext_color);
  7937. }
  7938. imagesetthickness($this->img, 1);
  7939. $this->DoCallback('data_points', 'rect', $row, 0, $x_left, $yh_pixels, $x_right, $yl_pixels);
  7940. }
  7941. return TRUE;
  7942. }
  7943. /**
  7944. * Draws a bubbles plot (Bubble chart)
  7945. *
  7946. * This is the main function for drawing a bubbles plot, which is a
  7947. * scatter plot with bubble size showing the Z value.
  7948. * Supported data type is data-data-xyz with rows of (label, X, Y1, Z1, ...)
  7949. * with multiple data sets (Y, Z pairs) supported.
  7950. *
  7951. * @return bool True (False on error if an error handler returns True)
  7952. * @since 5.5.0
  7953. */
  7954. protected function DrawBubbles()
  7955. {
  7956. if (!$this->CheckDataType('data-data-xyz'))
  7957. return FALSE;
  7958. $gcvars = array(); // For GetDataColor, which initializes and uses this.
  7959. // Calculate or use supplied maximum bubble size:
  7960. if (isset($this->bubbles_max_size)) {
  7961. $bubbles_max_size = $this->bubbles_max_size;
  7962. } else {
  7963. $bubbles_max_size = min($this->plot_area_width, $this->plot_area_height) / 12;
  7964. }
  7965. // Calculate bubble scale parameters. Bubble_size(z) = $f_size * $z + $b_size
  7966. if ($this->max_z <= $this->min_z) { // Regressive case, no Z range.
  7967. $f_size = 0;
  7968. $b_size = ($bubbles_max_size + $this->bubbles_min_size) / 2; // Use average size of all bubbles
  7969. } else {
  7970. $f_size = ($bubbles_max_size - $this->bubbles_min_size) / ($this->max_z - $this->min_z);
  7971. $b_size = $bubbles_max_size - $f_size * $this->max_z;
  7972. }
  7973. for ($row = 0; $row < $this->num_data_rows; $row++) {
  7974. $rec = 1; // Skip record #0 (data label)
  7975. $x = $this->xtr($this->data[$row][$rec++]); // Get X value from data array.
  7976. // Draw X Data labels?
  7977. if ($this->x_data_label_pos != 'none')
  7978. $this->DrawXDataLabel($this->data[$row][0], $x, $row, TRUE);
  7979. // Proceed with Y,Z values
  7980. for ($idx = 0; $rec < $this->num_recs[$row]; $rec += 2, $idx++) {
  7981. if (is_numeric($y_now = $this->data[$row][$rec])) { //Allow for missing Y data
  7982. $y = $this->ytr($y_now);
  7983. $z = (double)$this->data[$row][$rec+1]; // Z is required if Y is present.
  7984. $size = (int)($f_size * $z + $b_size); // Calculate bubble size
  7985. // Select the color:
  7986. $this->GetDataColor($row, $idx, $gcvars, $data_color);
  7987. // Draw the bubble:
  7988. ImageFilledEllipse($this->img, $x, $y, $size, $size, $data_color);
  7989. $this->DoCallback('data_points', 'circle', $row, $idx, $x, $y, $size);
  7990. }
  7991. }
  7992. }
  7993. return TRUE;
  7994. }
  7995. /**
  7996. * Draws a boxes plot (Box Plot or Box and Whisker plot)
  7997. *
  7998. * This is the main function for drawing a boxes plot. Supported data
  7999. * types are text-data and data-data, each with 5 or more Y values per
  8000. * row. The first 5 values are Ymin, YQ1, Ymid, YQ3, Ymax. Any additional
  8001. * values are outliers. PHPlot requires Ymin <= YQ1 <= Ymin <= YQ3 <= Ymax
  8002. * but does not assume anything about specific values (quartile, median).
  8003. *
  8004. * @return bool True (False on error if an error handler returns True)
  8005. * @since 6.1.0
  8006. */
  8007. protected function DrawBoxes()
  8008. {
  8009. if (!$this->CheckDataType('text-data, data-data'))
  8010. return FALSE;
  8011. if ($this->data_columns < 5) // early error check (more inside the loop)
  8012. return $this->PrintError("DrawBoxes(): rows must have 5 or more values.");
  8013. // Set up the point shapes/sizes arrays - needed for outliers:
  8014. $this->CheckPointParams();
  8015. // Calculate the half-width of the boxes.
  8016. // This is scaled based on the plot density, but within tight limits.
  8017. $width1 = max($this->boxes_min_width, min($this->boxes_max_width,
  8018. (int)($this->boxes_frac_width * $this->plot_area_width / $this->num_data_rows)));
  8019. // This is the half-width of the upper and lower T's and the ends of the whiskers:
  8020. $width2 = $this->boxes_t_width * $width1;
  8021. // A box plot can use up to 3 different line widths:
  8022. list($box_thickness, $belt_thickness, $whisker_thickness) = $this->line_widths;
  8023. $gcvars = array(); // For GetDataColor, which initializes and uses this.
  8024. for ($row = 0; $row < $this->num_data_rows; $row++) {
  8025. $record = 1; // Skip record #0 (data label)
  8026. if ($this->datatype_implied) // Implied X values?
  8027. $xw = 0.5 + $row; // Place text-data at X = 0.5, 1.5, 2.5, etc...
  8028. else
  8029. $xw = $this->data[$row][$record++]; // Read it, advance record index
  8030. $xd = $this->xtr($xw); // Convert X to device coordinates
  8031. $x_left = $xd - $width1;
  8032. $x_right = $xd + $width1;
  8033. if ($this->x_data_label_pos != 'none') // Draw X Data labels?
  8034. $this->DrawXDataLabel($this->data[$row][0], $xd, $row);
  8035. // Each row must have at least 5 values:
  8036. $num_y = $this->num_recs[$row] - $record;
  8037. if ($num_y < 5) {
  8038. return $this->PrintError("DrawBoxes(): row $row must have at least 5 values.");
  8039. }
  8040. // Collect the 5 primary Y values, plus any outliers:
  8041. $yd = array(); // Device coords
  8042. for ($i = 0; $i < $num_y; $i++) {
  8043. $yd[$i] = is_numeric($y = $this->data[$row][$record++]) ? $this->ytr($y) : NULL;
  8044. }
  8045. // Skip the row if either YQ1 or YQ3 is missing:
  8046. if (!isset($yd[1], $yd[3])) continue;
  8047. // Box plot uses 4 colors, and 1 dashed line style for the whiskers:
  8048. $this->GetDataColor($row, 0, $gcvars, $box_color);
  8049. $this->GetDataColor($row, 1, $gcvars, $belt_color);
  8050. $this->GetDataColor($row, 2, $gcvars, $outlier_color);
  8051. $this->GetDataColor($row, 3, $gcvars, $whisker_color);
  8052. $whisker_style = $this->SetDashedStyle($whisker_color, $this->line_styles[0] == 'dashed');
  8053. // Draw the lower whisker and T
  8054. if (isset($yd[0]) && $yd[0] > $yd[1]) { // Note device Y coordinates are inverted (*-1)
  8055. imagesetthickness($this->img, $whisker_thickness);
  8056. imageline($this->img, $xd, $yd[0], $xd, $yd[1], $whisker_style);
  8057. imageline($this->img, $xd - $width2, $yd[0], $xd + $width2, $yd[0], $whisker_color);
  8058. }
  8059. // Draw the upper whisker and T
  8060. if (isset($yd[4]) && $yd[3] > $yd[4]) { // Meaning: Yworld[3] < Yworld[4]
  8061. imagesetthickness($this->img, $whisker_thickness);
  8062. imageline($this->img, $xd, $yd[3], $xd, $yd[4], $whisker_style);
  8063. imageline($this->img, $xd - $width2, $yd[4], $xd + $width2, $yd[4], $whisker_color);
  8064. }
  8065. // Draw the median belt (before the box, so the ends of the belt don't break up the box.)
  8066. if (isset($yd[2])) {
  8067. imagesetthickness($this->img, $belt_thickness);
  8068. imageline($this->img, $x_left, $yd[2], $x_right, $yd[2], $belt_color);
  8069. }
  8070. // Draw the box
  8071. imagesetthickness($this->img, $box_thickness);
  8072. imagerectangle($this->img, $x_left, $yd[3], $x_right, $yd[1], $box_color);
  8073. imagesetthickness($this->img, 1);
  8074. // Draw any outliers, all using the same shape marker (index 0) and color:
  8075. for ($i = 5; $i < $num_y; $i++) {
  8076. if (isset($yd[$i]))
  8077. $this->DrawShape($xd, $yd[$i], 0, $outlier_color);
  8078. }
  8079. $this->DoCallback('data_points', 'rect', $row, 0, $x_left, $yd[4], $x_right, $yd[0]);
  8080. }
  8081. return TRUE;
  8082. }
  8083. /**
  8084. * Draws the current graph onto the image
  8085. *
  8086. * This is the function that performs the actual drawing, after all the
  8087. * parameters and data are set up. It also outputs the finished image,
  8088. * unless told not to with SetPrintImage(False).
  8089. * Note: It is possible for this to be called multiple times (multi-plot).
  8090. *
  8091. * @return bool True (False on error if an error handler returns True)
  8092. */
  8093. function DrawGraph()
  8094. {
  8095. // Test for missing image, missing data, empty data:
  8096. if (!$this->CheckDataArray())
  8097. return FALSE; // Error message already reported.
  8098. // Load some configuration values from the array of plot types:
  8099. $pt = &self::$plots[$this->plot_type]; // Use reference for shortcut
  8100. $draw_method = $pt['draw_method'];
  8101. $draw_arg = isset($pt['draw_arg']) ? $pt['draw_arg'] : array();
  8102. $draw_axes = empty($pt['suppress_axes']);
  8103. // Allocate colors for the plot:
  8104. $this->SetColorIndexes();
  8105. // Calculate scaling, but only for plots with axes (excludes pie charts).
  8106. if ($draw_axes) {
  8107. // Get maxima and minima for scaling:
  8108. if (!$this->FindDataLimits())
  8109. return FALSE;
  8110. // Set plot area world values (plot_max_x, etc.):
  8111. if (!$this->CalcPlotAreaWorld())
  8112. return FALSE;
  8113. // Calculate X and Y axis positions in World Coordinates:
  8114. $this->CalcAxisPositions();
  8115. // Process label-related parameters:
  8116. $this->CheckLabels();
  8117. }
  8118. // Calculate the plot margins, if needed.
  8119. // For pie charts, set the $maximize argument to maximize space usage.
  8120. $this->CalcMargins(!$draw_axes);
  8121. // Calculate the actual plot area in device coordinates:
  8122. $this->CalcPlotAreaPixels();
  8123. // Calculate the mapping between world and device coordinates:
  8124. if ($draw_axes) $this->CalcTranslation();
  8125. // Pad color and style arrays to fit records per group:
  8126. $this->PadArrays();
  8127. $this->DoCallback('draw_setup');
  8128. $this->DrawBackground();
  8129. $this->DrawImageBorder();
  8130. $this->DoCallback('draw_image_background');
  8131. $this->DrawPlotAreaBackground();
  8132. $this->DoCallback('draw_plotarea_background', $this->plot_area);
  8133. $this->DrawTitle();
  8134. if ($draw_axes) { // If no axes (pie chart), no axis titles either
  8135. $this->DrawXTitle();
  8136. $this->DrawYTitle();
  8137. }
  8138. $this->DoCallback('draw_titles');
  8139. // grid_at_foreground flag allows grid behind or in front of the plot
  8140. if ($draw_axes && !$this->grid_at_foreground) {
  8141. $this->DrawYAxis(); // Y axis must be drawn before X axis (see DrawYAxis())
  8142. $this->DrawXAxis();
  8143. $this->DoCallback('draw_axes');
  8144. }
  8145. // Call the plot-type drawing method:
  8146. call_user_func_array(array($this, $draw_method), $draw_arg);
  8147. $this->DoCallback('draw_graph', $this->plot_area);
  8148. if ($draw_axes && $this->grid_at_foreground) {
  8149. $this->DrawYAxis(); // Y axis must be drawn before X axis (see DrawYAxis())
  8150. $this->DrawXAxis();
  8151. $this->DoCallback('draw_axes');
  8152. }
  8153. $this->DrawPlotBorder($draw_axes); // Flag controls default for plot area borders
  8154. $this->DoCallback('draw_border');
  8155. if (!empty($this->legend)) {
  8156. $this->DrawLegend();
  8157. $this->DoCallback('draw_legend');
  8158. }
  8159. $this->DoCallback('draw_all', $this->plot_area);
  8160. if ($this->print_image && !$this->PrintImage())
  8161. return FALSE;
  8162. return TRUE;
  8163. }
  8164. /////////////////////////////////////////////
  8165. ////////////////// DEPRECATED METHODS
  8166. /////////////////////////////////////////////
  8167. /*
  8168. * Note on deprecated methods - as these pre-date the PHPlot Reference
  8169. * Manual, and there is minimal documentation about them, I have neither
  8170. * removed them nor changed them. They are not tested or documented, and
  8171. * should not be used.
  8172. */
  8173. /**
  8174. * @deprecated Use SetYTickPos() instead
  8175. */
  8176. function SetDrawVertTicks($which_dvt)
  8177. {
  8178. if ($which_dvt != 1)
  8179. $this->SetYTickPos('none');
  8180. return TRUE;
  8181. }
  8182. /**
  8183. * @deprecated Use SetXTickPos() instead
  8184. */
  8185. function SetDrawHorizTicks($which_dht)
  8186. {
  8187. if ($which_dht != 1)
  8188. $this->SetXTickPos('none');
  8189. return TRUE;
  8190. }
  8191. /**
  8192. * @deprecated Use SetNumXTicks() instead
  8193. */
  8194. function SetNumHorizTicks($n)
  8195. {
  8196. return $this->SetNumXTicks($n);
  8197. }
  8198. /**
  8199. * @deprecated Use SetNumYTicks() instead
  8200. */
  8201. function SetNumVertTicks($n)
  8202. {
  8203. return $this->SetNumYTicks($n);
  8204. }
  8205. /**
  8206. * @deprecated Use SetXTickIncrement() instead
  8207. */
  8208. function SetHorizTickIncrement($inc)
  8209. {
  8210. return $this->SetXTickIncrement($inc);
  8211. }
  8212. /**
  8213. * @deprecated Use SetYTickIncrement() instead
  8214. */
  8215. function SetVertTickIncrement($inc)
  8216. {
  8217. return $this->SetYTickIncrement($inc);
  8218. }
  8219. /**
  8220. * @deprecated Use SetYTickPos() instead
  8221. */
  8222. function SetVertTickPosition($which_tp)
  8223. {
  8224. return $this->SetYTickPos($which_tp);
  8225. }
  8226. /**
  8227. * @deprecated Use SetXTickPos() instead
  8228. */
  8229. function SetHorizTickPosition($which_tp)
  8230. {
  8231. return $this->SetXTickPos($which_tp);
  8232. }
  8233. /**
  8234. * @deprecated Use SetFont() instead
  8235. */
  8236. function SetTitleFontSize($which_size)
  8237. {
  8238. return $this->SetFont('title', $which_size);
  8239. }
  8240. /**
  8241. * @deprecated Use SetFont() instead
  8242. */
  8243. function SetAxisFontSize($which_size)
  8244. {
  8245. $this->SetFont('x_label', $which_size);
  8246. $this->SetFont('y_label', $which_size);
  8247. }
  8248. /**
  8249. * @deprecated Use SetFont() instead
  8250. */
  8251. function SetSmallFontSize($which_size)
  8252. {
  8253. return $this->SetFont('generic', $which_size);
  8254. }
  8255. /**
  8256. * @deprecated Use SetFont() instead
  8257. */
  8258. function SetXLabelFontSize($which_size)
  8259. {
  8260. return $this->SetFont('x_title', $which_size);
  8261. }
  8262. /**
  8263. * @deprecated Use SetFont() instead
  8264. */
  8265. function SetYLabelFontSize($which_size)
  8266. {
  8267. return $this->SetFont('y_title', $which_size);
  8268. }
  8269. /**
  8270. * @deprecated Use SetXTitle() instead
  8271. */
  8272. function SetXLabel($which_xlab)
  8273. {
  8274. return $this->SetXTitle($which_xlab);
  8275. }
  8276. /**
  8277. * @deprecated Use SetYTitle() instead
  8278. */
  8279. function SetYLabel($which_ylab)
  8280. {
  8281. return $this->SetYTitle($which_ylab);
  8282. }
  8283. /**
  8284. * @deprecated Use SetXTickLength() and SetYTickLength() instead
  8285. */
  8286. function SetTickLength($which_tl)
  8287. {
  8288. $this->SetXTickLength($which_tl);
  8289. $this->SetYTickLength($which_tl);
  8290. return TRUE;
  8291. }
  8292. /**
  8293. * @deprecated Use SetYLabelType() instead
  8294. */
  8295. function SetYGridLabelType($which_yglt)
  8296. {
  8297. return $this->SetYLabelType($which_yglt);
  8298. }
  8299. /**
  8300. * @deprecated Use SetXLabelType() instead
  8301. */
  8302. function SetXGridLabelType($which_xglt)
  8303. {
  8304. return $this->SetXLabelType($which_xglt);
  8305. }
  8306. /**
  8307. * @deprecated Use SetYTickLabelPos() instead
  8308. */
  8309. function SetYGridLabelPos($which_yglp)
  8310. {
  8311. return $this->SetYTickLabelPos($which_yglp);
  8312. }
  8313. /**
  8314. * @deprecated Use SetXTickLabelPos() instead
  8315. */
  8316. function SetXGridLabelPos($which_xglp)
  8317. {
  8318. return $this->SetXTickLabelPos($which_xglp);
  8319. }
  8320. /**
  8321. * @deprecated Use SetXtitle() instead
  8322. */
  8323. function SetXTitlePos($xpos)
  8324. {
  8325. $this->x_title_pos = $xpos;
  8326. return TRUE;
  8327. }
  8328. /**
  8329. * @deprecated Use SetYTitle() instead
  8330. */
  8331. function SetYTitlePos($xpos)
  8332. {
  8333. $this->y_title_pos = $xpos;
  8334. return TRUE;
  8335. }
  8336. /**
  8337. * @deprecated Use SetXDataLabelPos() instead
  8338. */
  8339. function SetDrawXDataLabels($which_dxdl)
  8340. {
  8341. if ($which_dxdl == '1' )
  8342. $this->SetXDataLabelPos('plotdown');
  8343. else
  8344. $this->SetXDataLabelPos('none');
  8345. }
  8346. /**
  8347. * @deprecated Use SetPlotAreaPixels() instead
  8348. */
  8349. function SetNewPlotAreaPixels($x1, $y1, $x2, $y2)
  8350. {
  8351. return $this->SetPlotAreaPixels($x1, $y1, $x2, $y2);
  8352. }
  8353. /**
  8354. * @deprecated Use SetLineWidths() instead
  8355. */
  8356. function SetLineWidth($which_lw)
  8357. {
  8358. $this->SetLineWidths($which_lw);
  8359. if (!$this->error_bar_line_width) {
  8360. $this->SetErrorBarLineWidth($which_lw);
  8361. }
  8362. return TRUE;
  8363. }
  8364. /**
  8365. * @deprecated Use SetPointShapes() instead
  8366. */
  8367. function SetPointShape($which_pt)
  8368. {
  8369. $this->SetPointShapes($which_pt);
  8370. return TRUE;
  8371. }
  8372. /**
  8373. * @deprecated Use SetPointSizes() instead
  8374. */
  8375. function SetPointSize($which_ps)
  8376. {
  8377. $this->SetPointSizes($which_ps);
  8378. return TRUE;
  8379. }
  8380. /**
  8381. * @deprecated Use PrintError() instead
  8382. */
  8383. protected function DrawError($error_message, $where_x = NULL, $where_y = NULL)
  8384. {
  8385. return $this->PrintError($error_message);
  8386. }
  8387. }
  8388. /**
  8389. * Class for creating a plot using a truecolor (24-bit R,G,B) image
  8390. *
  8391. * The PHPlot_truecolor class extends the PHPlot class to use GD truecolor
  8392. * images. Unlike PHPlot which usually creates indexed RGB files limited to
  8393. * 256 total colors, PHPlot_truecolor objects use images which do not have a
  8394. * limit on the number of colors.
  8395. *
  8396. * Note: Without a background image, the PHPlot class creates a palette
  8397. * (indexed) color image, and the PHPlot_truecolor class creates a truecolor
  8398. * image. If a background image is used with the constructor of either class,
  8399. * the type of image produced matches the type of the background image.
  8400. *
  8401. */
  8402. class PHPlot_truecolor extends PHPlot
  8403. {
  8404. /**
  8405. * Constructor: Sets up GD truecolor image resource, and initializes plot style controls
  8406. *
  8407. * @param int $width Image width in pixels
  8408. * @param int $height Image height in pixels
  8409. * @param string $output_file Path for output file. Omit, or NULL, or '' to mean no output file
  8410. * @param string $input_file Path to a file to be used as background. Omit, NULL, or '' for none
  8411. */
  8412. function __construct($width=600, $height=400, $output_file=NULL, $input_file=NULL)
  8413. {
  8414. $this->initialize('imagecreatetruecolor', $width, $height, $output_file, $input_file);
  8415. }
  8416. }