metamodel.class.php 200 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946
  1. <?php
  2. // Copyright (C) 2010-2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. require_once(APPROOT.'core/modulehandler.class.inc.php');
  19. require_once(APPROOT.'core/querybuildercontext.class.inc.php');
  20. require_once(APPROOT.'core/querymodifier.class.inc.php');
  21. require_once(APPROOT.'core/metamodelmodifier.inc.php');
  22. require_once(APPROOT.'core/computing.inc.php');
  23. require_once(APPROOT.'core/relationgraph.class.inc.php');
  24. /**
  25. * Metamodel
  26. *
  27. * @copyright Copyright (C) 2010-2012 Combodo SARL
  28. * @license http://opensource.org/licenses/AGPL-3.0
  29. */
  30. // #@# todo: change into class const (see Doctrine)
  31. // Doctrine example
  32. // class toto
  33. // {
  34. // /**
  35. // * VERSION
  36. // */
  37. // const VERSION = '1.0.0';
  38. // }
  39. /**
  40. * add some description here...
  41. *
  42. * @package iTopORM
  43. */
  44. define('ENUM_CHILD_CLASSES_EXCLUDETOP', 1);
  45. /**
  46. * add some description here...
  47. *
  48. * @package iTopORM
  49. */
  50. define('ENUM_CHILD_CLASSES_ALL', 2);
  51. /**
  52. * add some description here...
  53. *
  54. * @package iTopORM
  55. */
  56. define('ENUM_PARENT_CLASSES_EXCLUDELEAF', 1);
  57. /**
  58. * add some description here...
  59. *
  60. * @package iTopORM
  61. */
  62. define('ENUM_PARENT_CLASSES_ALL', 2);
  63. /**
  64. * Specifies that this attribute is visible/editable.... normal (default config)
  65. *
  66. * @package iTopORM
  67. */
  68. define('OPT_ATT_NORMAL', 0);
  69. /**
  70. * Specifies that this attribute is hidden in that state
  71. *
  72. * @package iTopORM
  73. */
  74. define('OPT_ATT_HIDDEN', 1);
  75. /**
  76. * Specifies that this attribute is not editable in that state
  77. *
  78. * @package iTopORM
  79. */
  80. define('OPT_ATT_READONLY', 2);
  81. /**
  82. * Specifieds that the attribute must be set (different than default value?) when arriving into that state
  83. *
  84. * @package iTopORM
  85. */
  86. define('OPT_ATT_MANDATORY', 4);
  87. /**
  88. * Specifies that the attribute must change when arriving into that state
  89. *
  90. * @package iTopORM
  91. */
  92. define('OPT_ATT_MUSTCHANGE', 8);
  93. /**
  94. * Specifies that the attribute must be proposed when arriving into that state
  95. *
  96. * @package iTopORM
  97. */
  98. define('OPT_ATT_MUSTPROMPT', 16);
  99. /**
  100. * Specifies that the attribute is in 'slave' mode compared to one data exchange task:
  101. * it should not be edited inside iTop anymore
  102. *
  103. * @package iTopORM
  104. */
  105. define('OPT_ATT_SLAVE', 32);
  106. /**
  107. * DB Engine -should be moved into CMDBSource
  108. *
  109. * @package iTopORM
  110. */
  111. define('MYSQL_ENGINE', 'innodb');
  112. //define('MYSQL_ENGINE', 'myisam');
  113. /**
  114. * (API) The objects definitions as well as their mapping to the database
  115. *
  116. * @package iTopORM
  117. */
  118. abstract class MetaModel
  119. {
  120. ///////////////////////////////////////////////////////////////////////////
  121. //
  122. // STATIC Members
  123. //
  124. ///////////////////////////////////////////////////////////////////////////
  125. private static $m_bTraceSourceFiles = false;
  126. private static $m_aClassToFile = array();
  127. public static function GetClassFiles()
  128. {
  129. return self::$m_aClassToFile;
  130. }
  131. // Purpose: workaround the following limitation = PHP5 does not allow to know the class (derived from the current one)
  132. // from which a static function is called (__CLASS__ and self are interpreted during parsing)
  133. private static function GetCallersPHPClass($sExpectedFunctionName = null, $bRecordSourceFile = false)
  134. {
  135. //var_dump(debug_backtrace());
  136. $aBacktrace = debug_backtrace();
  137. // $aBacktrace[0] is where we are
  138. // $aBacktrace[1] is the caller of GetCallersPHPClass
  139. // $aBacktrace[1] is the info we want
  140. if (!empty($sExpectedFunctionName))
  141. {
  142. assert('$aBacktrace[2]["function"] == $sExpectedFunctionName');
  143. }
  144. if ($bRecordSourceFile)
  145. {
  146. self::$m_aClassToFile[$aBacktrace[2]["class"]] = $aBacktrace[1]["file"];
  147. }
  148. return $aBacktrace[2]["class"];
  149. }
  150. // Static init -why and how it works
  151. //
  152. // We found the following limitations:
  153. //- it is not possible to define non scalar constants
  154. //- it is not possible to declare a static variable as '= new myclass()'
  155. // Then we had do propose this model, in which a derived (non abstract)
  156. // class should implement Init(), to call InheritAttributes or AddAttribute.
  157. private static function _check_subclass($sClass)
  158. {
  159. // See also IsValidClass()... ???? #@#
  160. // class is mandatory
  161. // (it is not possible to guess it when called as myderived::...)
  162. if (!array_key_exists($sClass, self::$m_aClassParams))
  163. {
  164. throw new CoreException("Unknown class '$sClass'");
  165. }
  166. }
  167. public static function static_var_dump()
  168. {
  169. var_dump(get_class_vars(__CLASS__));
  170. }
  171. private static $m_bDebugQuery = false;
  172. private static $m_iStackDepthRef = 0;
  173. public static function StartDebugQuery()
  174. {
  175. $aBacktrace = debug_backtrace();
  176. self::$m_iStackDepthRef = count($aBacktrace);
  177. self::$m_bDebugQuery = true;
  178. }
  179. public static function StopDebugQuery()
  180. {
  181. self::$m_bDebugQuery = false;
  182. }
  183. public static function DbgTrace($value)
  184. {
  185. if (!self::$m_bDebugQuery) return;
  186. $aBacktrace = debug_backtrace();
  187. $iCallStackPos = count($aBacktrace) - self::$m_bDebugQuery;
  188. $sIndent = "";
  189. for ($i = 0 ; $i < $iCallStackPos ; $i++)
  190. {
  191. $sIndent .= " .-=^=-. ";
  192. }
  193. $aCallers = array();
  194. foreach($aBacktrace as $aStackInfo)
  195. {
  196. $aCallers[] = $aStackInfo["function"];
  197. }
  198. $sCallers = "Callstack: ".implode(', ', $aCallers);
  199. $sFunction = "<b title=\"$sCallers\">".$aBacktrace[1]["function"]."</b>";
  200. if (is_string($value))
  201. {
  202. echo "$sIndent$sFunction: $value<br/>\n";
  203. }
  204. else if (is_object($value))
  205. {
  206. echo "$sIndent$sFunction:\n<pre>\n";
  207. print_r($value);
  208. echo "</pre>\n";
  209. }
  210. else
  211. {
  212. echo "$sIndent$sFunction: $value<br/>\n";
  213. }
  214. }
  215. private static $m_oConfig = null;
  216. protected static $m_aModulesParameters = array();
  217. private static $m_bSkipCheckToWrite = false;
  218. private static $m_bSkipCheckExtKeys = false;
  219. private static $m_bUseAPCCache = false;
  220. private static $m_iQueryCacheTTL = 3600;
  221. private static $m_bQueryCacheEnabled = false;
  222. private static $m_bTraceQueries = false;
  223. private static $m_bIndentQueries = false;
  224. private static $m_bOptimizeQueries = false;
  225. private static $m_aQueriesLog = array();
  226. private static $m_bLogIssue = false;
  227. private static $m_bLogNotification = false;
  228. private static $m_bLogWebService = false;
  229. public static function SkipCheckToWrite()
  230. {
  231. return self::$m_bSkipCheckToWrite;
  232. }
  233. public static function SkipCheckExtKeys()
  234. {
  235. return self::$m_bSkipCheckExtKeys;
  236. }
  237. public static function IsLogEnabledIssue()
  238. {
  239. return self::$m_bLogIssue;
  240. }
  241. public static function IsLogEnabledNotification()
  242. {
  243. return self::$m_bLogNotification;
  244. }
  245. public static function IsLogEnabledWebService()
  246. {
  247. return self::$m_bLogWebService;
  248. }
  249. private static $m_sDBName = "";
  250. private static $m_sTablePrefix = ""; // table prefix for the current application instance (allow several applications on the same DB)
  251. private static $m_Category2Class = array();
  252. private static $m_aRootClasses = array(); // array of "classname" => "rootclass"
  253. private static $m_aParentClasses = array(); // array of ("classname" => array of "parentclass")
  254. private static $m_aChildClasses = array(); // array of ("classname" => array of "childclass")
  255. private static $m_aClassParams = array(); // array of ("classname" => array of class information)
  256. private static $m_aHighlightScales = array(); // array of ("classname" => array of highlightscale information)
  257. static public function GetParentPersistentClass($sRefClass)
  258. {
  259. $sClass = get_parent_class($sRefClass);
  260. if (!$sClass) return '';
  261. if ($sClass == 'DBObject') return ''; // Warning: __CLASS__ is lower case in my version of PHP
  262. // Note: the UI/business model may implement pure PHP classes (intermediate layers)
  263. if (array_key_exists($sClass, self::$m_aClassParams))
  264. {
  265. return $sClass;
  266. }
  267. return self::GetParentPersistentClass($sClass);
  268. }
  269. final static public function GetName($sClass)
  270. {
  271. self::_check_subclass($sClass);
  272. $sStringCode = 'Class:'.$sClass;
  273. return Dict::S($sStringCode, str_replace('_', ' ', $sClass));
  274. }
  275. final static public function GetName_Obsolete($sClass)
  276. {
  277. // Written for compatibility with a data model written prior to version 0.9.1
  278. self::_check_subclass($sClass);
  279. if (array_key_exists('name', self::$m_aClassParams[$sClass]))
  280. {
  281. return self::$m_aClassParams[$sClass]['name'];
  282. }
  283. else
  284. {
  285. return self::GetName($sClass);
  286. }
  287. }
  288. final static public function GetClassFromLabel($sClassLabel, $bCaseSensitive = true)
  289. {
  290. foreach(self::GetClasses() as $sClass)
  291. {
  292. if ($bCaseSensitive)
  293. {
  294. if (self::GetName($sClass) == $sClassLabel)
  295. {
  296. return $sClass;
  297. }
  298. }
  299. else
  300. {
  301. if (strcasecmp(self::GetName($sClass), $sClassLabel) == 0)
  302. {
  303. return $sClass;
  304. }
  305. }
  306. }
  307. return null;
  308. }
  309. final static public function GetCategory($sClass)
  310. {
  311. self::_check_subclass($sClass);
  312. return self::$m_aClassParams[$sClass]["category"];
  313. }
  314. final static public function HasCategory($sClass, $sCategory)
  315. {
  316. self::_check_subclass($sClass);
  317. return (strpos(self::$m_aClassParams[$sClass]["category"], $sCategory) !== false);
  318. }
  319. final static public function GetClassDescription($sClass)
  320. {
  321. self::_check_subclass($sClass);
  322. $sStringCode = 'Class:'.$sClass.'+';
  323. return Dict::S($sStringCode, '');
  324. }
  325. final static public function GetClassDescription_Obsolete($sClass)
  326. {
  327. // Written for compatibility with a data model written prior to version 0.9.1
  328. self::_check_subclass($sClass);
  329. if (array_key_exists('description', self::$m_aClassParams[$sClass]))
  330. {
  331. return self::$m_aClassParams[$sClass]['description'];
  332. }
  333. else
  334. {
  335. return self::GetClassDescription($sClass);
  336. }
  337. }
  338. final static public function GetClassIcon($sClass, $bImgTag = true, $sMoreStyles = '')
  339. {
  340. self::_check_subclass($sClass);
  341. $sIcon = '';
  342. if (array_key_exists('icon', self::$m_aClassParams[$sClass]))
  343. {
  344. $sIcon = self::$m_aClassParams[$sClass]['icon'];
  345. }
  346. if (strlen($sIcon) == 0)
  347. {
  348. $sParentClass = self::GetParentPersistentClass($sClass);
  349. if (strlen($sParentClass) > 0)
  350. {
  351. return self::GetClassIcon($sParentClass, $bImgTag, $sMoreStyles);
  352. }
  353. }
  354. $sIcon = str_replace('/modules/', '/env-'.utils::GetCurrentEnvironment().'/', $sIcon); // Support of pre-2.0 modules
  355. if ($bImgTag && ($sIcon != ''))
  356. {
  357. $sIcon = "<img src=\"$sIcon\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  358. }
  359. return $sIcon;
  360. }
  361. final static public function IsAutoIncrementKey($sClass)
  362. {
  363. self::_check_subclass($sClass);
  364. return (self::$m_aClassParams[$sClass]["key_type"] == "autoincrement");
  365. }
  366. final static public function GetNameSpec($sClass)
  367. {
  368. self::_check_subclass($sClass);
  369. $nameRawSpec = self::$m_aClassParams[$sClass]["name_attcode"];
  370. if (is_array($nameRawSpec))
  371. {
  372. $sFormat = Dict::S("Class:$sClass/Name", '');
  373. if (strlen($sFormat) == 0)
  374. {
  375. // Default to "%1$s %2$s..."
  376. for($i = 1 ; $i <= count($nameRawSpec) ; $i++)
  377. {
  378. if (empty($sFormat))
  379. {
  380. $sFormat .= '%'.$i.'$s';
  381. }
  382. else
  383. {
  384. $sFormat .= ' %'.$i.'$s';
  385. }
  386. }
  387. }
  388. return array($sFormat, $nameRawSpec);
  389. }
  390. elseif (empty($nameRawSpec))
  391. {
  392. //return array($sClass.' %s', array('id'));
  393. return array($sClass, array());
  394. }
  395. else
  396. {
  397. // string -> attcode
  398. return array('%1$s', array($nameRawSpec));
  399. }
  400. }
  401. /**
  402. * Get the friendly name expression for a given class
  403. */
  404. final static public function GetNameExpression($sClass)
  405. {
  406. $aNameSpec = self::GetNameSpec($sClass);
  407. $sFormat = $aNameSpec[0];
  408. $aAttributes = $aNameSpec[1];
  409. $aPieces = preg_split('/%([0-9])\\$s/', $sFormat, -1, PREG_SPLIT_DELIM_CAPTURE);
  410. $aExpressions = array();
  411. foreach($aPieces as $i => $sPiece)
  412. {
  413. if ($i & 1)
  414. {
  415. // $i is ODD - sPiece is a delimiter
  416. //
  417. $iReplacement = (int)$sPiece - 1;
  418. if (isset($aAttributes[$iReplacement]))
  419. {
  420. $sAttCode = $aAttributes[$iReplacement];
  421. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  422. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  423. {
  424. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  425. $sClassOfAttribute = self::GetAttributeOrigin($sClass, $sKeyAttCode);
  426. }
  427. else
  428. {
  429. $sClassOfAttribute = self::GetAttributeOrigin($sClass, $sAttCode);
  430. }
  431. $aExpressions[] = new FieldExpression($sAttCode, $sClassOfAttribute);
  432. }
  433. }
  434. else
  435. {
  436. // $i is EVEN - sPiece is a literal
  437. //
  438. if (strlen($sPiece) > 0)
  439. {
  440. $aExpressions[] = new ScalarExpression($sPiece);
  441. }
  442. }
  443. }
  444. $oNameExpr = new CharConcatExpression($aExpressions);
  445. return $oNameExpr;
  446. }
  447. /**
  448. * Get the friendly name for the class and its subclasses (if finalclass = 'subclass' ...)
  449. * Simplifies the final expression by grouping classes having the same name expression
  450. * Used when querying a parent class
  451. */
  452. final static protected function GetExtendedNameExpression($sClass)
  453. {
  454. // 1st step - get all of the required expressions (instantiable classes)
  455. // and group them using their OQL representation
  456. //
  457. $aFNExpressions = array(); // signature => array('expression' => oExp, 'classes' => array of classes)
  458. foreach (self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
  459. {
  460. if (($sSubClass != $sClass) && self::IsAbstract($sSubClass)) continue;
  461. $oSubClassName = self::GetNameExpression($sSubClass);
  462. $sSignature = $oSubClassName->Render();
  463. if (!array_key_exists($sSignature, $aFNExpressions))
  464. {
  465. $aFNExpressions[$sSignature] = array(
  466. 'expression' => $oSubClassName,
  467. 'classes' => array(),
  468. );
  469. }
  470. $aFNExpressions[$sSignature]['classes'][] = $sSubClass;
  471. }
  472. // 2nd step - build the final name expression depending on the finalclass
  473. //
  474. if (count($aFNExpressions) == 1)
  475. {
  476. $aExpData = reset($aFNExpressions);
  477. $oNameExpression = $aExpData['expression'];
  478. }
  479. else
  480. {
  481. $oNameExpression = null;
  482. foreach ($aFNExpressions as $sSignature => $aExpData)
  483. {
  484. $oClassListExpr = ListExpression::FromScalars($aExpData['classes']);
  485. $oClassExpr = new FieldExpression('finalclass', $sClass);
  486. $oClassInList = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  487. if (is_null($oNameExpression))
  488. {
  489. $oNameExpression = $aExpData['expression'];
  490. }
  491. else
  492. {
  493. $oNameExpression = new FunctionExpression('IF', array($oClassInList, $aExpData['expression'], $oNameExpression));
  494. }
  495. }
  496. }
  497. return $oNameExpression;
  498. }
  499. final static public function GetStateAttributeCode($sClass)
  500. {
  501. self::_check_subclass($sClass);
  502. return self::$m_aClassParams[$sClass]["state_attcode"];
  503. }
  504. final static public function GetDefaultState($sClass)
  505. {
  506. $sDefaultState = '';
  507. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  508. if (!empty($sStateAttrCode))
  509. {
  510. $oStateAttrDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  511. $sDefaultState = $oStateAttrDef->GetDefaultValue();
  512. }
  513. return $sDefaultState;
  514. }
  515. final static public function GetReconcKeys($sClass)
  516. {
  517. self::_check_subclass($sClass);
  518. return self::$m_aClassParams[$sClass]["reconc_keys"];
  519. }
  520. final static public function GetDisplayTemplate($sClass)
  521. {
  522. self::_check_subclass($sClass);
  523. return array_key_exists("display_template", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["display_template"]: '';
  524. }
  525. final static public function GetOrderByDefault($sClass, $bOnlyDeclared = false)
  526. {
  527. self::_check_subclass($sClass);
  528. $aOrderBy = array_key_exists("order_by_default", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["order_by_default"]: array();
  529. if ($bOnlyDeclared)
  530. {
  531. // Used to reverse engineer the declaration of the data model
  532. return $aOrderBy;
  533. }
  534. else
  535. {
  536. if (count($aOrderBy) == 0)
  537. {
  538. $aOrderBy['friendlyname'] = true;
  539. }
  540. return $aOrderBy;
  541. }
  542. }
  543. final static public function GetAttributeOrigin($sClass, $sAttCode)
  544. {
  545. self::_check_subclass($sClass);
  546. return self::$m_aAttribOrigins[$sClass][$sAttCode];
  547. }
  548. final static public function GetPrequisiteAttributes($sClass, $sAttCode)
  549. {
  550. self::_check_subclass($sClass);
  551. $oAtt = self::GetAttributeDef($sClass, $sAttCode);
  552. // Temporary implementation: later, we might be able to compute
  553. // the dependencies, based on the attributes definition
  554. // (allowed values and default values)
  555. // Even non-writable attributes (like ExternalFields) can now have Prerequisites
  556. return $oAtt->GetPrerequisiteAttributes();
  557. }
  558. /**
  559. * Find all attributes that depend on the specified one (reverse of GetPrequisiteAttributes)
  560. * @param string $sClass Name of the class
  561. * @param string $sAttCode Code of the attributes
  562. * @return Array List of attribute codes that depend on the given attribute, empty array if none.
  563. */
  564. final static public function GetDependentAttributes($sClass, $sAttCode)
  565. {
  566. $aResults = array();
  567. self::_check_subclass($sClass);
  568. foreach (self::ListAttributeDefs($sClass) as $sDependentAttCode=>$void)
  569. {
  570. $aPrerequisites = self::GetPrequisiteAttributes($sClass, $sDependentAttCode);
  571. if (in_array($sAttCode, $aPrerequisites))
  572. {
  573. $aResults[] = $sDependentAttCode;
  574. }
  575. }
  576. return $aResults;
  577. }
  578. // #@# restore to private ?
  579. final static public function DBGetTable($sClass, $sAttCode = null)
  580. {
  581. self::_check_subclass($sClass);
  582. if (empty($sAttCode) || ($sAttCode == "id"))
  583. {
  584. $sTableRaw = self::$m_aClassParams[$sClass]["db_table"];
  585. if (empty($sTableRaw))
  586. {
  587. // return an empty string whenever the table is undefined, meaning that there is no table associated to this 'abstract' class
  588. return '';
  589. }
  590. else
  591. {
  592. // If the format changes here, do not forget to update the setup index page (detection of installed modules)
  593. return self::$m_sTablePrefix.$sTableRaw;
  594. }
  595. }
  596. // This attribute has been inherited (compound objects)
  597. return self::DBGetTable(self::$m_aAttribOrigins[$sClass][$sAttCode]);
  598. }
  599. final static public function DBGetView($sClass)
  600. {
  601. return self::$m_sTablePrefix."view_".$sClass;
  602. }
  603. final static public function DBEnumTables()
  604. {
  605. // This API does not rely on our capability to query the DB and retrieve
  606. // the list of existing tables
  607. // Rather, it uses the list of expected tables, corresponding to the data model
  608. $aTables = array();
  609. foreach (self::GetClasses() as $sClass)
  610. {
  611. if (!self::HasTable($sClass)) continue;
  612. $sTable = self::DBGetTable($sClass);
  613. // Could be completed later with all the classes that are using a given table
  614. if (!array_key_exists($sTable, $aTables))
  615. {
  616. $aTables[$sTable] = array();
  617. }
  618. $aTables[$sTable][] = $sClass;
  619. }
  620. return $aTables;
  621. }
  622. final static public function DBGetIndexes($sClass)
  623. {
  624. self::_check_subclass($sClass);
  625. if (isset(self::$m_aClassParams[$sClass]['indexes']))
  626. {
  627. return self::$m_aClassParams[$sClass]['indexes'];
  628. }
  629. else
  630. {
  631. return array();
  632. }
  633. }
  634. final static public function DBGetKey($sClass)
  635. {
  636. self::_check_subclass($sClass);
  637. return self::$m_aClassParams[$sClass]["db_key_field"];
  638. }
  639. final static public function DBGetClassField($sClass)
  640. {
  641. self::_check_subclass($sClass);
  642. return self::$m_aClassParams[$sClass]["db_finalclass_field"];
  643. }
  644. final static public function IsStandaloneClass($sClass)
  645. {
  646. self::_check_subclass($sClass);
  647. if (count(self::$m_aChildClasses[$sClass]) == 0)
  648. {
  649. if (count(self::$m_aParentClasses[$sClass]) == 0)
  650. {
  651. return true;
  652. }
  653. }
  654. return false;
  655. }
  656. final static public function IsParentClass($sParentClass, $sChildClass)
  657. {
  658. self::_check_subclass($sChildClass);
  659. self::_check_subclass($sParentClass);
  660. if (in_array($sParentClass, self::$m_aParentClasses[$sChildClass])) return true;
  661. if ($sChildClass == $sParentClass) return true;
  662. return false;
  663. }
  664. final static public function IsSameFamilyBranch($sClassA, $sClassB)
  665. {
  666. self::_check_subclass($sClassA);
  667. self::_check_subclass($sClassB);
  668. if (in_array($sClassA, self::$m_aParentClasses[$sClassB])) return true;
  669. if (in_array($sClassB, self::$m_aParentClasses[$sClassA])) return true;
  670. if ($sClassA == $sClassB) return true;
  671. return false;
  672. }
  673. final static public function IsSameFamily($sClassA, $sClassB)
  674. {
  675. self::_check_subclass($sClassA);
  676. self::_check_subclass($sClassB);
  677. return (self::GetRootClass($sClassA) == self::GetRootClass($sClassB));
  678. }
  679. // Attributes of a given class may contain attributes defined in a parent class
  680. // - Some attributes are a copy of the definition
  681. // - Some attributes correspond to the upper class table definition (compound objects)
  682. // (see also filters definition)
  683. private static $m_aAttribDefs = array(); // array of ("classname" => array of attributes)
  684. private static $m_aAttribOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  685. private static $m_aExtKeyFriends = array(); // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  686. private static $m_aIgnoredAttributes = array(); //array of ("classname" => array of ("attcode")
  687. final static public function ListAttributeDefs($sClass)
  688. {
  689. self::_check_subclass($sClass);
  690. return self::$m_aAttribDefs[$sClass];
  691. }
  692. final public static function GetAttributesList($sClass)
  693. {
  694. self::_check_subclass($sClass);
  695. return array_keys(self::$m_aAttribDefs[$sClass]);
  696. }
  697. final public static function GetFiltersList($sClass)
  698. {
  699. self::_check_subclass($sClass);
  700. return array_keys(self::$m_aFilterDefs[$sClass]);
  701. }
  702. final public static function GetKeysList($sClass)
  703. {
  704. self::_check_subclass($sClass);
  705. $aExtKeys = array();
  706. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  707. {
  708. if ($oAttDef->IsExternalKey())
  709. {
  710. $aExtKeys[] = $sAttCode;
  711. }
  712. }
  713. return $aExtKeys;
  714. }
  715. final static public function IsValidKeyAttCode($sClass, $sAttCode)
  716. {
  717. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  718. if (!array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass])) return false;
  719. return (self::$m_aAttribDefs[$sClass][$sAttCode]->IsExternalKey());
  720. }
  721. final static public function IsValidAttCode($sClass, $sAttCode, $bExtended = false)
  722. {
  723. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  724. if ($bExtended)
  725. {
  726. if (($iPos = strpos($sAttCode, '->')) === false)
  727. {
  728. $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
  729. }
  730. else
  731. {
  732. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  733. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  734. if (MetaModel::IsValidAttCode($sClass, $sExtKeyAttCode))
  735. {
  736. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  737. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  738. $bRes = MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode, true);
  739. }
  740. else
  741. {
  742. $bRes = false;
  743. }
  744. }
  745. }
  746. else
  747. {
  748. $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
  749. }
  750. return $bRes;
  751. }
  752. final static public function IsAttributeOrigin($sClass, $sAttCode)
  753. {
  754. return (self::$m_aAttribOrigins[$sClass][$sAttCode] == $sClass);
  755. }
  756. final static public function IsValidFilterCode($sClass, $sFilterCode)
  757. {
  758. if (!array_key_exists($sClass, self::$m_aFilterDefs)) return false;
  759. return (array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]));
  760. }
  761. public static function IsValidClass($sClass)
  762. {
  763. return (array_key_exists($sClass, self::$m_aAttribDefs));
  764. }
  765. public static function IsValidObject($oObject)
  766. {
  767. if (!is_object($oObject)) return false;
  768. return (self::IsValidClass(get_class($oObject)));
  769. }
  770. public static function IsReconcKey($sClass, $sAttCode)
  771. {
  772. return (in_array($sAttCode, self::GetReconcKeys($sClass)));
  773. }
  774. final static public function GetAttributeDef($sClass, $sAttCode)
  775. {
  776. self::_check_subclass($sClass);
  777. if (!isset(self::$m_aAttribDefs[$sClass][$sAttCode]))
  778. {
  779. throw new Exception("Unknown attribute $sAttCode from class $sClass");
  780. }
  781. return self::$m_aAttribDefs[$sClass][$sAttCode];
  782. }
  783. final static public function GetExternalKeys($sClass)
  784. {
  785. $aExtKeys = array();
  786. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  787. {
  788. if ($oAtt->IsExternalKey())
  789. {
  790. $aExtKeys[$sAttCode] = $oAtt;
  791. }
  792. }
  793. return $aExtKeys;
  794. }
  795. final static public function GetLinkedSets($sClass)
  796. {
  797. $aLinkedSets = array();
  798. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  799. {
  800. if (is_subclass_of($oAtt, 'AttributeLinkedSet'))
  801. {
  802. $aLinkedSets[$sAttCode] = $oAtt;
  803. }
  804. }
  805. return $aLinkedSets;
  806. }
  807. final static public function GetExternalFields($sClass, $sKeyAttCode)
  808. {
  809. static $aExtFields = array();
  810. if (!isset($aExtFields[$sClass][$sKeyAttCode]))
  811. {
  812. $aExtFields[$sClass][$sKeyAttCode] = array();
  813. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  814. {
  815. if ($oAtt->IsExternalField() && ($oAtt->GetKeyAttCode() == $sKeyAttCode))
  816. {
  817. $aExtFields[$sClass][$sKeyAttCode][$oAtt->GetExtAttCode()] = $oAtt;
  818. }
  819. }
  820. }
  821. return $aExtFields[$sClass][$sKeyAttCode];
  822. }
  823. final static public function FindExternalField($sClass, $sKeyAttCode, $sRemoteAttCode)
  824. {
  825. $aExtFields = self::GetExternalFields($sClass, $sKeyAttCode);
  826. if (isset($aExtFields[$sRemoteAttCode]))
  827. {
  828. return $aExtFields[$sRemoteAttCode];
  829. }
  830. else
  831. {
  832. return null;
  833. }
  834. }
  835. final static public function GetExtKeyFriends($sClass, $sExtKeyAttCode)
  836. {
  837. if (array_key_exists($sExtKeyAttCode, self::$m_aExtKeyFriends[$sClass]))
  838. {
  839. return self::$m_aExtKeyFriends[$sClass][$sExtKeyAttCode];
  840. }
  841. else
  842. {
  843. return array();
  844. }
  845. }
  846. protected static $m_aTrackForwardCache = array();
  847. /**
  848. * List external keys for which there is a LinkSet (direct or indirect) on the other end
  849. * For those external keys, a change will have a special meaning on the other end
  850. * in term of change tracking
  851. */
  852. final static public function GetTrackForwardExternalKeys($sClass)
  853. {
  854. if (!isset(self::$m_aTrackForwardCache[$sClass]))
  855. {
  856. $aRes = array();
  857. foreach (MetaModel::GetExternalKeys($sClass) as $sAttCode => $oAttDef)
  858. {
  859. $sRemoteClass = $oAttDef->GetTargetClass();
  860. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  861. {
  862. if (!$oRemoteAttDef->IsLinkSet()) continue;
  863. if (!is_subclass_of($sClass, $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $sClass) continue;
  864. if ($oRemoteAttDef->GetExtKeyToMe() != $sAttCode) continue;
  865. $aRes[$sAttCode] = $oRemoteAttDef;
  866. }
  867. }
  868. self::$m_aTrackForwardCache[$sClass] = $aRes;
  869. }
  870. return self::$m_aTrackForwardCache[$sClass];
  871. }
  872. /**
  873. * Get the attribute label
  874. * @param string sClass Persistent class
  875. * @param string sAttCodeEx Extended attribute code: attcode[->attcode]
  876. * @param bool $bShowMandatory If true, add a star character (at the end or before the ->) to show that the field is mandatory
  877. * @return string A user friendly format of the string: AttributeName or AttributeName->ExtAttributeName
  878. */
  879. public static function GetLabel($sClass, $sAttCodeEx, $bShowMandatory = false)
  880. {
  881. $sLabel = '';
  882. if (preg_match('/(.+)->(.+)/', $sAttCodeEx, $aMatches) > 0)
  883. {
  884. $sAttribute = $aMatches[1];
  885. $sField = $aMatches[2];
  886. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttribute);
  887. $sMandatory = ($bShowMandatory && !$oAttDef->IsNullAllowed()) ? '*' : '';
  888. if ($oAttDef->IsExternalKey())
  889. {
  890. $sTargetClass = $oAttDef->GetTargetClass();
  891. $oTargetAttDef = MetaModel::GetAttributeDef($sTargetClass, $sField);
  892. $sLabel = $oAttDef->GetLabel().$sMandatory.'->'.$oTargetAttDef->GetLabel();
  893. }
  894. else
  895. {
  896. // Let's return something displayable... but this should never happen!
  897. $sLabel = $oAttDef->GetLabel().$sMandatory.'->'.$aMatches[2];
  898. }
  899. }
  900. else
  901. {
  902. if ($sAttCodeEx == 'id')
  903. {
  904. $sLabel = Dict::S('UI:CSVImport:idField');
  905. }
  906. else
  907. {
  908. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCodeEx);
  909. $sMandatory = ($bShowMandatory && !$oAttDef->IsNullAllowed()) ? '*' : '';
  910. $sLabel = $oAttDef->GetLabel().$sMandatory;
  911. }
  912. }
  913. return $sLabel;
  914. }
  915. public static function GetDescription($sClass, $sAttCode)
  916. {
  917. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  918. if ($oAttDef) return $oAttDef->GetDescription();
  919. return "";
  920. }
  921. // Filters of a given class may contain filters defined in a parent class
  922. // - Some filters are a copy of the definition
  923. // - Some filters correspond to the upper class table definition (compound objects)
  924. // (see also attributes definition)
  925. private static $m_aFilterDefs = array(); // array of ("classname" => array filterdef)
  926. private static $m_aFilterOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  927. public static function GetClassFilterDefs($sClass)
  928. {
  929. self::_check_subclass($sClass);
  930. return self::$m_aFilterDefs[$sClass];
  931. }
  932. final static public function GetClassFilterDef($sClass, $sFilterCode)
  933. {
  934. self::_check_subclass($sClass);
  935. if (!array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]))
  936. {
  937. throw new CoreException("Unknown filter code '$sFilterCode' for class '$sClass'");
  938. }
  939. return self::$m_aFilterDefs[$sClass][$sFilterCode];
  940. }
  941. public static function GetFilterLabel($sClass, $sFilterCode)
  942. {
  943. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  944. if ($oFilter) return $oFilter->GetLabel();
  945. return "";
  946. }
  947. public static function GetFilterDescription($sClass, $sFilterCode)
  948. {
  949. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  950. if ($oFilter) return $oFilter->GetDescription();
  951. return "";
  952. }
  953. // returns an array of opcode=>oplabel (e.g. "differs from")
  954. public static function GetFilterOperators($sClass, $sFilterCode)
  955. {
  956. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  957. if ($oFilter) return $oFilter->GetOperators();
  958. return array();
  959. }
  960. // returns an opcode
  961. public static function GetFilterLooseOperator($sClass, $sFilterCode)
  962. {
  963. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  964. if ($oFilter) return $oFilter->GetLooseOperator();
  965. return array();
  966. }
  967. public static function GetFilterOpDescription($sClass, $sFilterCode, $sOpCode)
  968. {
  969. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  970. if ($oFilter) return $oFilter->GetOpDescription($sOpCode);
  971. return "";
  972. }
  973. public static function GetFilterHTMLInput($sFilterCode)
  974. {
  975. return "<INPUT name=\"$sFilterCode\">";
  976. }
  977. // Lists of attributes/search filters
  978. //
  979. private static $m_aListInfos = array(); // array of ("listcode" => various info on the list, common to every classes)
  980. private static $m_aListData = array(); // array of ("classname" => array of "listcode" => list)
  981. // list may be an array of attcode / fltcode
  982. // list may be an array of "groupname" => (array of attcode / fltcode)
  983. public static function EnumZLists()
  984. {
  985. return array_keys(self::$m_aListInfos);
  986. }
  987. final static public function GetZListInfo($sListCode)
  988. {
  989. return self::$m_aListInfos[$sListCode];
  990. }
  991. public static function GetZListItems($sClass, $sListCode)
  992. {
  993. if (array_key_exists($sClass, self::$m_aListData))
  994. {
  995. if (array_key_exists($sListCode, self::$m_aListData[$sClass]))
  996. {
  997. return self::$m_aListData[$sClass][$sListCode];
  998. }
  999. }
  1000. $sParentClass = self::GetParentPersistentClass($sClass);
  1001. if (empty($sParentClass)) return array(); // nothing for the mother of all classes
  1002. // Dig recursively
  1003. return self::GetZListItems($sParentClass, $sListCode);
  1004. }
  1005. public static function IsAttributeInZList($sClass, $sListCode, $sAttCodeOrFltCode, $sGroup = null)
  1006. {
  1007. $aZList = self::FlattenZlist(self::GetZListItems($sClass, $sListCode));
  1008. if (!$sGroup)
  1009. {
  1010. return (in_array($sAttCodeOrFltCode, $aZList));
  1011. }
  1012. return (in_array($sAttCodeOrFltCode, $aZList[$sGroup]));
  1013. }
  1014. //
  1015. // Relations
  1016. //
  1017. private static $m_aRelationInfos = array(); // array of ("relcode" => various info on the list, common to every classes)
  1018. /**
  1019. * TO BE DEPRECATED: use EnumRelationsEx instead
  1020. * @param string $sClass
  1021. * @return multitype:string unknown |Ambigous <string, multitype:>
  1022. */
  1023. public static function EnumRelations($sClass = '')
  1024. {
  1025. $aResult = array_keys(self::$m_aRelationInfos);
  1026. if (!empty($sClass))
  1027. {
  1028. // Return only the relations that have a meaning (i.e. for which at least one query is defined)
  1029. // for the specified class
  1030. $aClassRelations = array();
  1031. foreach($aResult as $sRelCode)
  1032. {
  1033. $aQueriesDown = self::EnumRelationQueries($sClass, $sRelCode);
  1034. if (count($aQueriesDown) > 0)
  1035. {
  1036. $aClassRelations[] = $sRelCode;
  1037. }
  1038. // Temporary patch: until the impact analysis GUI gets rewritten,
  1039. // let's consider that "depends on" is equivalent to "impacts/up"
  1040. // The current patch has been implemented in DBObject and MetaModel
  1041. if ($sRelCode == 'impacts')
  1042. {
  1043. $aQueriesUp = self::EnumRelationQueries($sClass, 'impacts', false);
  1044. if (count($aQueriesUp) > 0)
  1045. {
  1046. $aClassRelations[] = 'depends on';
  1047. }
  1048. }
  1049. }
  1050. return $aClassRelations;
  1051. }
  1052. // Temporary patch: until the impact analysis GUI gets rewritten,
  1053. // let's consider that "depends on" is equivalent to "impacts/up"
  1054. // The current patch has been implemented in DBObject and MetaModel
  1055. if (in_array('impacts', $aResult))
  1056. {
  1057. $aResult[] = 'depends on';
  1058. }
  1059. return $aResult;
  1060. }
  1061. public static function EnumRelationsEx($sClass)
  1062. {
  1063. $aRelationInfo = array_keys(self::$m_aRelationInfos);
  1064. // Return only the relations that have a meaning (i.e. for which at least one query is defined)
  1065. // for the specified class
  1066. $aClassRelations = array();
  1067. foreach($aRelationInfo as $sRelCode)
  1068. {
  1069. $aQueriesDown = self::EnumRelationQueries($sClass, $sRelCode, true /* Down */);
  1070. if (count($aQueriesDown) > 0)
  1071. {
  1072. $aClassRelations[$sRelCode]['down'] = self::GetRelationLabel($sRelCode, true);
  1073. }
  1074. $aQueriesUp = self::EnumRelationQueries($sClass, $sRelCode, false /* Up */);
  1075. if (count($aQueriesUp) > 0)
  1076. {
  1077. $aClassRelations[$sRelCode]['up'] = self::GetRelationLabel($sRelCode, false);
  1078. }
  1079. }
  1080. return $aClassRelations;
  1081. }
  1082. final static public function GetRelationDescription($sRelCode)
  1083. {
  1084. return Dict::S("Relation:$sRelCode/Description");
  1085. }
  1086. final static public function GetRelationLabel($sRelCode, $bDown = true)
  1087. {
  1088. if ($bDown)
  1089. {
  1090. // The legacy convention is confusing with regard to the way we have conceptualized the relations:
  1091. // In the former representation, the main stream was named after "up"
  1092. // Now, the relation from A to B says that something is transmitted from A to B, thus going DOWNstream as described in a petri net.
  1093. $sKey = "Relation:$sRelCode/DownStream";
  1094. $sLegacy = Dict::S("Relation:$sRelCode/VerbUp", $sKey);
  1095. }
  1096. else
  1097. {
  1098. $sKey = "Relation:$sRelCode/UpStream";
  1099. $sLegacy = Dict::S("Relation:$sRelCode/VerbDown", $sKey);
  1100. }
  1101. $sRet = Dict::S($sKey, $sLegacy);
  1102. return $sRet;
  1103. }
  1104. protected static function ComputeRelationQueries($sRelCode)
  1105. {
  1106. $bHasLegacy = false;
  1107. $aQueries = array();
  1108. foreach (self::GetClasses() as $sClass)
  1109. {
  1110. $aQueries[$sClass]['down'] = array();
  1111. if (!array_key_exists('up', $aQueries[$sClass]))
  1112. {
  1113. $aQueries[$sClass]['up'] = array();
  1114. }
  1115. $aNeighboursDown = call_user_func_array(array($sClass, 'GetRelationQueriesEx'), array($sRelCode));
  1116. // Translate attributes into queries (new style of spec only)
  1117. foreach($aNeighboursDown as $sNeighbourId => $aNeighbourData)
  1118. {
  1119. $aNeighbourData['sFromClass'] = $aNeighbourData['sDefinedInClass'];
  1120. try
  1121. {
  1122. if (strlen($aNeighbourData['sQueryDown']) == 0)
  1123. {
  1124. $oAttDef = self::GetAttributeDef($sClass, $aNeighbourData['sAttribute']);
  1125. if ($oAttDef instanceof AttributeExternalKey)
  1126. {
  1127. $sTargetClass = $oAttDef->GetTargetClass();
  1128. $aNeighbourData['sToClass'] = $sTargetClass;
  1129. $aNeighbourData['sQueryDown'] = 'SELECT '.$sTargetClass.' AS o WHERE o.id = :this->'.$aNeighbourData['sAttribute'];
  1130. $aNeighbourData['sQueryUp'] = 'SELECT '.$aNeighbourData['sFromClass'].' AS o WHERE o.'.$aNeighbourData['sAttribute'].' = :this->id';
  1131. }
  1132. elseif ($oAttDef instanceof AttributeLinkedSet)
  1133. {
  1134. $sLinkedClass = $oAttDef->GetLinkedClass();
  1135. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  1136. if ($oAttDef->IsIndirect())
  1137. {
  1138. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  1139. $oRemoteAttDef = self::GetAttributeDef($sLinkedClass, $sExtKeyToRemote);
  1140. $sRemoteClass = $oRemoteAttDef->GetTargetClass();
  1141. $aNeighbourData['sToClass'] = $sRemoteClass;
  1142. $aNeighbourData['sQueryDown'] = "SELECT $sRemoteClass AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToRemote = o.id WHERE lnk.$sExtKeyToMe = :this->id";
  1143. $aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToMe = o.id WHERE lnk.$sExtKeyToRemote = :this->id";
  1144. }
  1145. else
  1146. {
  1147. $aNeighbourData['sToClass'] = $sLinkedClass;
  1148. $aNeighbourData['sQueryDown'] = "SELECT $sLinkedClass AS o WHERE o.$sExtKeyToMe = :this->id";
  1149. $aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o WHERE o.id = :this->$sExtKeyToMe";
  1150. }
  1151. }
  1152. else
  1153. {
  1154. throw new Exception("Unexpected attribute type for '{$aNeighbourData['sAttribute']}'. Expecting a link set or external key.");
  1155. }
  1156. }
  1157. else
  1158. {
  1159. $oSearch = DBObjectSearch::FromOQL($aNeighbourData['sQueryDown']);
  1160. $aNeighbourData['sToClass'] = $oSearch->GetClass();
  1161. }
  1162. }
  1163. catch (Exception $e)
  1164. {
  1165. throw new Exception("Wrong definition for the relation $sRelCode/{$aNeighbourData['sDefinedInClass']}/{$aNeighbourData['sNeighbour']}: ".$e->getMessage());
  1166. }
  1167. if ($aNeighbourData['sDirection'] == 'down')
  1168. {
  1169. $aNeighbourData['sQueryUp'] = null;
  1170. }
  1171. $sArrowId = $aNeighbourData['sDefinedInClass'].'_'.$sNeighbourId;
  1172. $aQueries[$sClass]['down'][$sArrowId] = $aNeighbourData;
  1173. // Compute the reverse index
  1174. if ($aNeighbourData['sDefinedInClass'] == $sClass)
  1175. {
  1176. if ($aNeighbourData['sDirection'] == 'both')
  1177. {
  1178. $sFromClass = $aNeighbourData['sFromClass'];
  1179. $sToClass = $aNeighbourData['sToClass'];
  1180. foreach (self::EnumChildClasses($sToClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
  1181. {
  1182. $aQueries[$sSubClass]['up'][$sArrowId] = $aNeighbourData;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. // Read legacy definitions
  1188. // The up/down queries have to be reconcilied, which can only be done later when all the classes have been browsed
  1189. //
  1190. // The keys used to store a query (up or down) into the array are built differently between the modern and legacy made data:
  1191. // Modern way: aQueries[sClass]['up'|'down'][sArrowId], where sArrowId is made of the source class + neighbour id (XML def)
  1192. // Legacy way: aQueries[sClass]['up'|'down'][sRemoteClass]
  1193. // The modern way does allow for several arrows between two classes
  1194. // The legacy way aims at simplifying the transformation (reconciliation between up and down)
  1195. if ($sRelCode == 'impacts')
  1196. {
  1197. $sRevertCode = 'depends on';
  1198. $aLegacy = call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRelCode));
  1199. foreach($aLegacy as $sId => $aLegacyEntry)
  1200. {
  1201. $bHasLegacy = true;
  1202. $oFilter = DBObjectSearch::FromOQL($aLegacyEntry['sQuery']);
  1203. $sRemoteClass = $oFilter->GetClass();
  1204. // Determine wether the query is inherited from a parent or not
  1205. $bInherited = false;
  1206. foreach (self::EnumParentClasses($sClass) as $sParent)
  1207. {
  1208. if (!isset($aQueries[$sParent]['down'][$sRemoteClass])) continue;
  1209. if ($aLegacyEntry['sQuery'] == $aQueries[$sParent]['down'][$sRemoteClass]['sQueryDown'])
  1210. {
  1211. $bInherited = true;
  1212. $aQueries[$sClass]['down'][$sRemoteClass] = $aQueries[$sParent]['down'][$sRemoteClass];
  1213. break;
  1214. }
  1215. }
  1216. if (!$bInherited)
  1217. {
  1218. $aQueries[$sClass]['down'][$sRemoteClass] = array(
  1219. '_legacy_' => true,
  1220. 'sDefinedInClass' => $sClass,
  1221. 'sFromClass' => $sClass,
  1222. 'sToClass' => $sRemoteClass,
  1223. 'sDirection' => 'down',
  1224. 'sQueryDown' => $aLegacyEntry['sQuery'],
  1225. 'sQueryUp' => null,
  1226. 'sNeighbour' => $sRemoteClass // Normalize the neighbour id
  1227. );
  1228. }
  1229. }
  1230. $aLegacy = call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRevertCode));
  1231. foreach($aLegacy as $sId => $aLegacyEntry)
  1232. {
  1233. $bHasLegacy = true;
  1234. $oFilter = DBObjectSearch::FromOQL($aLegacyEntry['sQuery']);
  1235. $sRemoteClass = $oFilter->GetClass();
  1236. // Determine wether the query is inherited from a parent or not
  1237. $bInherited = false;
  1238. foreach (self::EnumParentClasses($sClass) as $sParent)
  1239. {
  1240. if (!isset($aQueries[$sParent]['up'][$sRemoteClass])) continue;
  1241. if ($aLegacyEntry['sQuery'] == $aQueries[$sParent]['up'][$sRemoteClass]['sQueryUp'])
  1242. {
  1243. $bInherited = true;
  1244. $aQueries[$sClass]['up'][$sRemoteClass] = $aQueries[$sParent]['up'][$sRemoteClass];
  1245. break;
  1246. }
  1247. }
  1248. if (!$bInherited)
  1249. {
  1250. $aQueries[$sClass]['up'][$sRemoteClass] = array(
  1251. '_legacy_' => true,
  1252. 'sDefinedInClass' => $sRemoteClass,
  1253. 'sFromClass' => $sRemoteClass,
  1254. 'sToClass' => $sClass,
  1255. 'sDirection' => 'both',
  1256. 'sQueryDown' => null,
  1257. 'sQueryUp' => $aLegacyEntry['sQuery'],
  1258. 'sNeighbour' => $sClass// Normalize the neighbour id
  1259. );
  1260. }
  1261. }
  1262. }
  1263. else
  1264. {
  1265. // Cannot take the legacy system into account... simply ignore it
  1266. }
  1267. } // foreach class
  1268. // Perform the up/down reconciliation for the legacy definitions
  1269. if ($bHasLegacy)
  1270. {
  1271. foreach (self::GetClasses() as $sClass)
  1272. {
  1273. // Foreach "up" legacy query, update its "down" counterpart
  1274. if (isset($aQueries[$sClass]['up']))
  1275. {
  1276. foreach ($aQueries[$sClass]['up'] as $sNeighbourId => $aNeighbourData)
  1277. {
  1278. if (!array_key_exists('_legacy_', $aNeighbourData))
  1279. {
  1280. continue;
  1281. }
  1282. if (!$aNeighbourData['_legacy_']) continue; // Skip modern definitions
  1283. $sLocalClass = $aNeighbourData['sToClass'];
  1284. foreach (self::EnumChildClasses($aNeighbourData['sFromClass'], ENUM_CHILD_CLASSES_ALL) as $sRemoteClass)
  1285. {
  1286. if (isset($aQueries[$sRemoteClass]['down'][$sLocalClass]))
  1287. {
  1288. $aQueries[$sRemoteClass]['down'][$sLocalClass]['sQueryUp'] = $aNeighbourData['sQueryUp'];
  1289. $aQueries[$sRemoteClass]['down'][$sLocalClass]['sDirection'] = 'both';
  1290. }
  1291. // Be silent in order to transparently support legacy data models where the counterpart query does not always exist
  1292. //else
  1293. //{
  1294. // throw new Exception("Legacy definition of the relation '$sRelCode/$sRevertCode', defined on $sLocalClass (relation: $sRevertCode, inherited to $sClass), missing the counterpart query on class $sRemoteClass ($sRelCode)");
  1295. //}
  1296. }
  1297. }
  1298. }
  1299. // Foreach "down" legacy query, update its "up" counterpart (if any)
  1300. foreach ($aQueries[$sClass]['down'] as $sNeighbourId => $aNeighbourData)
  1301. {
  1302. if (!$aNeighbourData['_legacy_']) continue; // Skip modern definitions
  1303. $sLocalClass = $aNeighbourData['sFromClass'];
  1304. foreach (self::EnumChildClasses($aNeighbourData['sToClass'], ENUM_CHILD_CLASSES_ALL) as $sRemoteClass)
  1305. {
  1306. if (isset($aQueries[$sRemoteClass]['up'][$sLocalClass]))
  1307. {
  1308. $aQueries[$sRemoteClass]['up'][$sLocalClass]['sQueryDown'] = $aNeighbourData['sQueryDown'];
  1309. }
  1310. }
  1311. }
  1312. }
  1313. }
  1314. return $aQueries;
  1315. }
  1316. public static function EnumRelationQueries($sClass, $sRelCode, $bDown = true)
  1317. {
  1318. static $aQueries = array();
  1319. if (!isset($aQueries[$sRelCode]))
  1320. {
  1321. $aQueries[$sRelCode] = self::ComputeRelationQueries($sRelCode);
  1322. }
  1323. $sDirection = $bDown ? 'down' : 'up';
  1324. if (isset($aQueries[$sRelCode][$sClass][$sDirection]))
  1325. {
  1326. return $aQueries[$sRelCode][$sClass][$sDirection];
  1327. }
  1328. else
  1329. {
  1330. return array();
  1331. }
  1332. }
  1333. /**
  1334. * Compute the "RelatedObjects" for a whole set of DBObjects
  1335. *
  1336. * @param string $sRelCode The code of the relation to use for the computation
  1337. * @param array $asourceObjects The objects to start with
  1338. * @param int $iMaxDepth
  1339. * @param boolean $bEnableReduncancy
  1340. * @param array $aUnreachable Array of objects to be considered as 'unreachable'
  1341. *
  1342. * @return RelationGraph The graph of all the related objects
  1343. */
  1344. static public function GetRelatedObjectsDown($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aUnreachable = array(), $aContexts = array())
  1345. {
  1346. $oGraph = new RelationGraph();
  1347. foreach ($aSourceObjects as $oObject)
  1348. {
  1349. $oGraph->AddSourceObject($oObject);
  1350. }
  1351. foreach($aContexts as $key => $sOQL)
  1352. {
  1353. $oGraph->AddContextQuery($key, $sOQL);
  1354. }
  1355. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy, $aUnreachable);
  1356. return $oGraph;
  1357. }
  1358. /**
  1359. * Compute the "RelatedObjects" in the reverse way
  1360. *
  1361. * @param string $sRelCode The code of the relation to use for the computation
  1362. * @param array $asourceObjects The objects to start with
  1363. * @param int $iMaxDepth
  1364. * @param boolean $bEnableReduncancy
  1365. *
  1366. * @return RelationGraph The graph of all the related objects
  1367. */
  1368. static public function GetRelatedObjectsUp($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aContexts = array())
  1369. {
  1370. $oGraph = new RelationGraph();
  1371. foreach ($aSourceObjects as $oObject)
  1372. {
  1373. $oGraph->AddSinkObject($oObject);
  1374. }
  1375. foreach($aContexts as $key => $sOQL)
  1376. {
  1377. $oGraph->AddContextQuery($key, $sOQL);
  1378. }
  1379. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  1380. return $oGraph;
  1381. }
  1382. //
  1383. // Object lifecycle model
  1384. //
  1385. private static $m_aStates = array(); // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  1386. private static $m_aStimuli = array(); // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  1387. private static $m_aTransitions = array(); // array of ("classname" => array of ("statcode_from"=>array of ("stimuluscode" => array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD)))
  1388. public static function EnumStates($sClass)
  1389. {
  1390. if (array_key_exists($sClass, self::$m_aStates))
  1391. {
  1392. return self::$m_aStates[$sClass];
  1393. }
  1394. else
  1395. {
  1396. return array();
  1397. }
  1398. }
  1399. /*
  1400. * Enumerate all possible initial states, including the default one
  1401. */
  1402. public static function EnumInitialStates($sClass)
  1403. {
  1404. if (array_key_exists($sClass, self::$m_aStates))
  1405. {
  1406. $aRet = array();
  1407. // Add the states for which the flag 'is_initial_state' is set to <true>
  1408. foreach(self::$m_aStates[$sClass] as $aStateCode => $aProps)
  1409. {
  1410. if (isset($aProps['initial_state_path']))
  1411. {
  1412. $aRet[$aStateCode] = $aProps['initial_state_path'];
  1413. }
  1414. }
  1415. // Add the default initial state
  1416. $sMainInitialState = self::GetDefaultState($sClass);
  1417. if (!isset($aRet[$sMainInitialState]))
  1418. {
  1419. $aRet[$sMainInitialState] = array();
  1420. }
  1421. return $aRet;
  1422. }
  1423. else
  1424. {
  1425. return array();
  1426. }
  1427. }
  1428. public static function EnumStimuli($sClass)
  1429. {
  1430. if (array_key_exists($sClass, self::$m_aStimuli))
  1431. {
  1432. return self::$m_aStimuli[$sClass];
  1433. }
  1434. else
  1435. {
  1436. return array();
  1437. }
  1438. }
  1439. public static function GetStateLabel($sClass, $sStateValue)
  1440. {
  1441. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1442. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1443. return $oAttDef->GetValueLabel($sStateValue);
  1444. }
  1445. public static function GetStateDescription($sClass, $sStateValue)
  1446. {
  1447. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1448. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1449. return $oAttDef->GetValueDescription($sStateValue);
  1450. }
  1451. public static function EnumTransitions($sClass, $sStateCode)
  1452. {
  1453. if (array_key_exists($sClass, self::$m_aTransitions))
  1454. {
  1455. if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
  1456. {
  1457. return self::$m_aTransitions[$sClass][$sStateCode];
  1458. }
  1459. }
  1460. return array();
  1461. }
  1462. public static function GetAttributeFlags($sClass, $sState, $sAttCode)
  1463. {
  1464. $iFlags = 0; // By default (if no life cycle) no flag at all
  1465. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1466. if (!empty($sStateAttCode))
  1467. {
  1468. $aStates = MetaModel::EnumStates($sClass);
  1469. if (!array_key_exists($sState, $aStates))
  1470. {
  1471. throw new CoreException("Invalid state '$sState' for class '$sClass', expecting a value in {".implode(', ', array_keys($aStates))."}");
  1472. }
  1473. $aCurrentState = $aStates[$sState];
  1474. if ( (array_key_exists('attribute_list', $aCurrentState)) && (array_key_exists($sAttCode, $aCurrentState['attribute_list'])) )
  1475. {
  1476. $iFlags = $aCurrentState['attribute_list'][$sAttCode];
  1477. }
  1478. }
  1479. return $iFlags;
  1480. }
  1481. /**
  1482. * Combines the flags from the all states that compose the initial_state_path
  1483. */
  1484. public static function GetInitialStateAttributeFlags($sClass, $sState, $sAttCode)
  1485. {
  1486. $iFlags = self::GetAttributeFlags($sClass, $sState, $sAttCode); // Be default set the same flags as the 'target' state
  1487. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1488. if (!empty($sStateAttCode))
  1489. {
  1490. $aStates = MetaModel::EnumInitialStates($sClass);
  1491. if (array_key_exists($sState, $aStates))
  1492. {
  1493. $bReadOnly = (($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY);
  1494. $bHidden = (($iFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN);
  1495. foreach($aStates[$sState] as $sPrevState)
  1496. {
  1497. $iPrevFlags = self::GetAttributeFlags($sClass, $sPrevState, $sAttCode);
  1498. if (($iPrevFlags & OPT_ATT_HIDDEN) != OPT_ATT_HIDDEN)
  1499. {
  1500. $bReadOnly = $bReadOnly && (($iPrevFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY); // if it is/was not readonly => then it's not
  1501. }
  1502. $bHidden = $bHidden && (($iPrevFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN); // if it is/was not hidden => then it's not
  1503. }
  1504. if ($bReadOnly)
  1505. {
  1506. $iFlags = $iFlags | OPT_ATT_READONLY;
  1507. }
  1508. else
  1509. {
  1510. $iFlags = $iFlags & ~OPT_ATT_READONLY;
  1511. }
  1512. if ($bHidden)
  1513. {
  1514. $iFlags = $iFlags | OPT_ATT_HIDDEN;
  1515. }
  1516. else
  1517. {
  1518. $iFlags = $iFlags & ~OPT_ATT_HIDDEN;
  1519. }
  1520. }
  1521. }
  1522. return $iFlags;
  1523. }
  1524. //
  1525. // Allowed values
  1526. //
  1527. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1528. {
  1529. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1530. return $oAttDef->GetAllowedValues($aArgs, $sContains);
  1531. }
  1532. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sContains = '')
  1533. {
  1534. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  1535. return $oFltDef->GetAllowedValues($aArgs, $sContains);
  1536. }
  1537. public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1538. {
  1539. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1540. return $oAttDef->GetAllowedValuesAsObjectSet($aArgs, $sContains);
  1541. }
  1542. //
  1543. // Businezz model declaration verbs (should be static)
  1544. //
  1545. public static function RegisterZList($sListCode, $aListInfo)
  1546. {
  1547. // Check mandatory params
  1548. $aMandatParams = array(
  1549. "description" => "detailed (though one line) description of the list",
  1550. "type" => "attributes | filters",
  1551. );
  1552. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1553. {
  1554. if (!array_key_exists($sParamName, $aListInfo))
  1555. {
  1556. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  1557. }
  1558. }
  1559. self::$m_aListInfos[$sListCode] = $aListInfo;
  1560. }
  1561. public static function RegisterRelation($sRelCode)
  1562. {
  1563. // Each item used to be an array of properties...
  1564. self::$m_aRelationInfos[$sRelCode] = $sRelCode;
  1565. }
  1566. // Must be called once and only once...
  1567. public static function InitClasses($sTablePrefix)
  1568. {
  1569. if (count(self::GetClasses()) > 0)
  1570. {
  1571. throw new CoreException("InitClasses should not be called more than once -skipped");
  1572. return;
  1573. }
  1574. self::$m_sTablePrefix = $sTablePrefix;
  1575. // Build the list of available extensions
  1576. //
  1577. $aInterfaces = array('iApplicationUIExtension', 'iApplicationObjectExtension', 'iQueryModifier', 'iOnClassInitialization', 'iPopupMenuExtension', 'iPageUIExtension');
  1578. foreach($aInterfaces as $sInterface)
  1579. {
  1580. self::$m_aExtensionClasses[$sInterface] = array();
  1581. }
  1582. foreach(get_declared_classes() as $sPHPClass)
  1583. {
  1584. $oRefClass = new ReflectionClass($sPHPClass);
  1585. $oExtensionInstance = null;
  1586. foreach($aInterfaces as $sInterface)
  1587. {
  1588. if ($oRefClass->implementsInterface($sInterface))
  1589. {
  1590. if (is_null($oExtensionInstance))
  1591. {
  1592. $oExtensionInstance = new $sPHPClass;
  1593. }
  1594. self::$m_aExtensionClasses[$sInterface][$sPHPClass] = $oExtensionInstance;
  1595. }
  1596. }
  1597. }
  1598. // Initialize the classes (declared attributes, etc.)
  1599. //
  1600. foreach(get_declared_classes() as $sPHPClass)
  1601. {
  1602. if (is_subclass_of($sPHPClass, 'DBObject'))
  1603. {
  1604. $sParent = get_parent_class($sPHPClass);
  1605. if (array_key_exists($sParent, self::$m_aIgnoredAttributes))
  1606. {
  1607. // Inherit info about attributes to ignore
  1608. self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent];
  1609. }
  1610. try
  1611. {
  1612. $oMethod = new ReflectionMethod($sPHPClass, 'Init');
  1613. if ($oMethod->getDeclaringClass()->name == $sPHPClass)
  1614. {
  1615. call_user_func(array($sPHPClass, 'Init'));
  1616. foreach (MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit)
  1617. {
  1618. $oClassInit->OnAfterClassInitialization($sPHPClass);
  1619. }
  1620. }
  1621. }
  1622. catch (ReflectionException $e)
  1623. {
  1624. // This class is only implementing methods, ignore it from the MetaModel perspective
  1625. }
  1626. }
  1627. }
  1628. // Add a 'class' attribute/filter to the root classes and their children
  1629. //
  1630. foreach(self::EnumRootClasses() as $sRootClass)
  1631. {
  1632. if (self::IsStandaloneClass($sRootClass)) continue;
  1633. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  1634. if (strlen($sDbFinalClassField) == 0)
  1635. {
  1636. $sDbFinalClassField = 'finalclass';
  1637. self::$m_aClassParams[$sRootClass]["db_finalclass_field"] = 'finalclass';
  1638. }
  1639. $oClassAtt = new AttributeFinalClass('finalclass', array(
  1640. "sql"=>$sDbFinalClassField,
  1641. "default_value"=>$sRootClass,
  1642. "is_null_allowed"=>false,
  1643. "depends_on"=>array()
  1644. ));
  1645. $oClassAtt->SetHostClass($sRootClass);
  1646. self::$m_aAttribDefs[$sRootClass]['finalclass'] = $oClassAtt;
  1647. self::$m_aAttribOrigins[$sRootClass]['finalclass'] = $sRootClass;
  1648. $oClassFlt = new FilterFromAttribute($oClassAtt);
  1649. self::$m_aFilterDefs[$sRootClass]['finalclass'] = $oClassFlt;
  1650. self::$m_aFilterOrigins[$sRootClass]['finalclass'] = $sRootClass;
  1651. foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass)
  1652. {
  1653. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass]))
  1654. {
  1655. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  1656. }
  1657. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sChildClass]))
  1658. {
  1659. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  1660. }
  1661. $oCloned = clone $oClassAtt;
  1662. $oCloned->SetFixedValue($sChildClass);
  1663. self::$m_aAttribDefs[$sChildClass]['finalclass'] = $oCloned;
  1664. self::$m_aAttribOrigins[$sChildClass]['finalclass'] = $sRootClass;
  1665. $oClassFlt = new FilterFromAttribute($oClassAtt);
  1666. self::$m_aFilterDefs[$sChildClass]['finalclass'] = $oClassFlt;
  1667. self::$m_aFilterOrigins[$sChildClass]['finalclass'] = self::GetRootClass($sChildClass);
  1668. }
  1669. }
  1670. // Prepare external fields and filters
  1671. // Add final class to external keys
  1672. //
  1673. foreach (self::GetClasses() as $sClass)
  1674. {
  1675. // Create the friendly name attribute
  1676. $sFriendlyNameAttCode = 'friendlyname';
  1677. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, 'id');
  1678. $oFriendlyName->SetHostClass($sClass);
  1679. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1680. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sClass;
  1681. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1682. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1683. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sClass;
  1684. self::$m_aExtKeyFriends[$sClass] = array();
  1685. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  1686. {
  1687. // Compute the filter codes
  1688. //
  1689. foreach ($oAttDef->GetFilterDefinitions() as $sFilterCode => $oFilterDef)
  1690. {
  1691. self::$m_aFilterDefs[$sClass][$sFilterCode] = $oFilterDef;
  1692. if ($oAttDef->IsExternalField())
  1693. {
  1694. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1695. $oKeyDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1696. self::$m_aFilterOrigins[$sClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  1697. }
  1698. else
  1699. {
  1700. self::$m_aFilterOrigins[$sClass][$sFilterCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  1701. }
  1702. }
  1703. // Compute the fields that will be used to display a pointer to another object
  1704. //
  1705. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  1706. {
  1707. // oAttDef is either
  1708. // - an external KEY / FIELD (direct),
  1709. // - an external field pointing to an external KEY / FIELD
  1710. // - an external field pointing to an external field pointing to....
  1711. $sRemoteClass = $oAttDef->GetTargetClass();
  1712. if ($oAttDef->IsExternalField())
  1713. {
  1714. // This is a key, but the value comes from elsewhere
  1715. // Create an external field pointing to the remote friendly name attribute
  1716. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1717. $sRemoteAttCode = $oAttDef->GetExtAttCode()."_friendlyname";
  1718. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1719. // propagate "is_null_allowed" ?
  1720. $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array("allowed_values"=>null, "extkey_attcode"=>$sKeyAttCode, "target_attcode"=>$sRemoteAttCode, "depends_on"=>array()));
  1721. $oFriendlyName->SetHostClass($sClass);
  1722. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1723. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1724. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1725. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1726. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1727. }
  1728. else
  1729. {
  1730. // Create the friendly name attribute
  1731. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1732. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, $sAttCode);
  1733. $oFriendlyName->SetHostClass($sClass);
  1734. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1735. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1736. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1737. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1738. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1739. if (self::HasChildrenClasses($sRemoteClass))
  1740. {
  1741. // First, create an external field attribute, that gets the final class
  1742. $sClassRecallAttCode = $sAttCode.'_finalclass_recall';
  1743. $oClassRecall = new AttributeExternalField($sClassRecallAttCode, array(
  1744. "allowed_values"=>null,
  1745. "extkey_attcode"=>$sAttCode,
  1746. "target_attcode"=>"finalclass",
  1747. "is_null_allowed"=>true,
  1748. "depends_on"=>array()
  1749. ));
  1750. $oClassRecall->SetHostClass($sClass);
  1751. self::$m_aAttribDefs[$sClass][$sClassRecallAttCode] = $oClassRecall;
  1752. self::$m_aAttribOrigins[$sClass][$sClassRecallAttCode] = $sRemoteClass;
  1753. $oClassFlt = new FilterFromAttribute($oClassRecall);
  1754. self::$m_aFilterDefs[$sClass][$sClassRecallAttCode] = $oClassFlt;
  1755. self::$m_aFilterOrigins[$sClass][$sClassRecallAttCode] = $sRemoteClass;
  1756. // Add it to the ZLists where the external key is present
  1757. //foreach(self::$m_aListData[$sClass] as $sListCode => $aAttributes)
  1758. $sListCode = 'list';
  1759. if (isset(self::$m_aListData[$sClass][$sListCode]))
  1760. {
  1761. $aAttributes = self::$m_aListData[$sClass][$sListCode];
  1762. // temporary.... no loop
  1763. {
  1764. if (in_array($sAttCode, $aAttributes))
  1765. {
  1766. $aNewList = array();
  1767. foreach($aAttributes as $iPos => $sAttToDisplay)
  1768. {
  1769. if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode))
  1770. {
  1771. // Insert the final class right before
  1772. $aNewList[] = $sClassRecallAttCode;
  1773. }
  1774. $aNewList[] = $sAttToDisplay;
  1775. }
  1776. self::$m_aListData[$sClass][$sListCode] = $aNewList;
  1777. }
  1778. }
  1779. }
  1780. }
  1781. }
  1782. // Get the real external key attribute
  1783. // It will be our reference to determine the other ext fields related to the same ext key
  1784. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1785. self::$m_aExtKeyFriends[$sClass][$sAttCode] = array();
  1786. foreach (self::GetExternalFields($sClass, $oAttDef->GetKeyAttCode($sAttCode)) as $oExtField)
  1787. {
  1788. // skip : those extfields will be processed as external keys
  1789. if ($oExtField->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1790. // Note: I could not compare the objects by the mean of '==='
  1791. // because they are copied for the inheritance, and the internal references are NOT updated
  1792. if ($oExtField->GetKeyAttDef(EXTKEY_ABSOLUTE) == $oFinalKeyAttDef)
  1793. {
  1794. self::$m_aExtKeyFriends[$sClass][$sAttCode][$oExtField->GetCode()] = $oExtField;
  1795. }
  1796. }
  1797. }
  1798. }
  1799. // Add a 'id' filter
  1800. //
  1801. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  1802. {
  1803. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  1804. }
  1805. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  1806. {
  1807. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  1808. }
  1809. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  1810. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  1811. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  1812. // Define defaults values for the standard ZLists
  1813. //
  1814. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  1815. //{
  1816. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  1817. // {
  1818. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  1819. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  1820. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  1821. // }
  1822. //}
  1823. }
  1824. }
  1825. // To be overriden, must be called for any object class (optimization)
  1826. public static function Init()
  1827. {
  1828. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1829. }
  1830. // To be overloaded by biz model declarations
  1831. public static function GetRelationQueries($sRelCode)
  1832. {
  1833. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1834. return array();
  1835. }
  1836. public static function Init_Params($aParams)
  1837. {
  1838. // Check mandatory params
  1839. $aMandatParams = array(
  1840. "category" => "group classes by modules defining their visibility in the UI",
  1841. "key_type" => "autoincrement | string",
  1842. "name_attcode" => "define wich attribute is the class name, may be an array of attributes (format specified in the dictionary as 'Class:myclass/Name' => '%1\$s %2\$s...'",
  1843. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  1844. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  1845. "db_table" => "database table",
  1846. "db_key_field" => "database field which is the key",
  1847. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  1848. );
  1849. $sClass = self::GetCallersPHPClass("Init", self::$m_bTraceSourceFiles);
  1850. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1851. {
  1852. if (!array_key_exists($sParamName, $aParams))
  1853. {
  1854. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  1855. }
  1856. }
  1857. $aCategories = explode(',', $aParams['category']);
  1858. foreach ($aCategories as $sCategory)
  1859. {
  1860. self::$m_Category2Class[$sCategory][] = $sClass;
  1861. }
  1862. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  1863. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  1864. self::$m_aParentClasses[$sClass] = array();
  1865. self::$m_aChildClasses[$sClass] = array();
  1866. self::$m_aClassParams[$sClass]= $aParams;
  1867. self::$m_aAttribDefs[$sClass] = array();
  1868. self::$m_aAttribOrigins[$sClass] = array();
  1869. self::$m_aExtKeyFriends[$sClass] = array();
  1870. self::$m_aFilterDefs[$sClass] = array();
  1871. self::$m_aFilterOrigins[$sClass] = array();
  1872. }
  1873. protected static function object_array_mergeclone($aSource1, $aSource2)
  1874. {
  1875. $aRes = array();
  1876. foreach ($aSource1 as $key=>$object)
  1877. {
  1878. $aRes[$key] = clone $object;
  1879. }
  1880. foreach ($aSource2 as $key=>$object)
  1881. {
  1882. $aRes[$key] = clone $object;
  1883. }
  1884. return $aRes;
  1885. }
  1886. public static function Init_InheritAttributes($sSourceClass = null)
  1887. {
  1888. $sTargetClass = self::GetCallersPHPClass("Init");
  1889. if (empty($sSourceClass))
  1890. {
  1891. // Default: inherit from parent class
  1892. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1893. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1894. }
  1895. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  1896. {
  1897. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  1898. {
  1899. self::$m_aAttribDefs[$sTargetClass] = array();
  1900. self::$m_aAttribOrigins[$sTargetClass] = array();
  1901. }
  1902. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  1903. foreach(self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef)
  1904. {
  1905. $oAttDef->SetHostClass($sTargetClass);
  1906. }
  1907. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  1908. }
  1909. // Build root class information
  1910. if (array_key_exists($sSourceClass, self::$m_aRootClasses))
  1911. {
  1912. // Inherit...
  1913. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  1914. }
  1915. else
  1916. {
  1917. // This class will be the root class
  1918. self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
  1919. self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
  1920. }
  1921. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  1922. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  1923. // I am the child of each and every parent...
  1924. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  1925. {
  1926. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  1927. }
  1928. }
  1929. protected static function Init_IsKnownClass($sClass)
  1930. {
  1931. // Differs from self::IsValidClass()
  1932. // because it is being called before all the classes have been initialized
  1933. if (!class_exists($sClass)) return false;
  1934. if (!is_subclass_of($sClass, 'DBObject')) return false;
  1935. return true;
  1936. }
  1937. public static function Init_AddAttribute(AttributeDefinition $oAtt, $sTargetClass = null)
  1938. {
  1939. if (!$sTargetClass)
  1940. {
  1941. $sTargetClass = self::GetCallersPHPClass("Init");
  1942. }
  1943. $sAttCode = $oAtt->GetCode();
  1944. if ($sAttCode == 'finalclass')
  1945. {
  1946. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1947. }
  1948. if ($sAttCode == 'friendlyname')
  1949. {
  1950. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1951. }
  1952. if (array_key_exists($sAttCode, self::$m_aAttribDefs[$sTargetClass]))
  1953. {
  1954. throw new Exception("Declaration of $sTargetClass: attempting to redeclare the inherited attribute '$sAttCode', originaly declared in ".self::$m_aAttribOrigins[$sTargetClass][$sAttCode]);
  1955. }
  1956. // Set the "host class" as soon as possible, since HierarchicalKeys use it for their 'target class' as well
  1957. // and this needs to be know early (for Init_IsKnowClass 19 lines below)
  1958. $oAtt->SetHostClass($sTargetClass);
  1959. // Some attributes could refer to a class
  1960. // declared in a module which is currently not installed/active
  1961. // We simply discard those attributes
  1962. //
  1963. if ($oAtt->IsLinkSet())
  1964. {
  1965. $sRemoteClass = $oAtt->GetLinkedClass();
  1966. if (!self::Init_IsKnownClass($sRemoteClass))
  1967. {
  1968. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1969. return;
  1970. }
  1971. }
  1972. elseif($oAtt->IsExternalKey())
  1973. {
  1974. $sRemoteClass = $oAtt->GetTargetClass();
  1975. if (!self::Init_IsKnownClass($sRemoteClass))
  1976. {
  1977. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1978. return;
  1979. }
  1980. }
  1981. elseif($oAtt->IsExternalField())
  1982. {
  1983. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  1984. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
  1985. {
  1986. // The corresponding external key has already been ignored
  1987. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
  1988. return;
  1989. }
  1990. // #@# todo - Check if the target attribute is still there
  1991. // this is not simple to implement because is involves
  1992. // several passes (the load order has a significant influence on that)
  1993. }
  1994. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  1995. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  1996. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  1997. }
  1998. public static function Init_SetZListItems($sListCode, $aItems, $sTargetClass = null)
  1999. {
  2000. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  2001. if (!$sTargetClass)
  2002. {
  2003. $sTargetClass = self::GetCallersPHPClass("Init");
  2004. }
  2005. // Discard attributes that do not make sense
  2006. // (missing classes in the current module combination, resulting in irrelevant ext key or link set)
  2007. //
  2008. self::Init_CheckZListItems($aItems, $sTargetClass);
  2009. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  2010. }
  2011. protected static function Init_CheckZListItems(&$aItems, $sTargetClass)
  2012. {
  2013. foreach($aItems as $iFoo => $attCode)
  2014. {
  2015. if (is_array($attCode))
  2016. {
  2017. // Note: to make sure that the values will be updated recursively,
  2018. // do not pass $attCode, but $aItems[$iFoo] instead
  2019. self::Init_CheckZListItems($aItems[$iFoo], $sTargetClass);
  2020. if (count($aItems[$iFoo]) == 0)
  2021. {
  2022. unset($aItems[$iFoo]);
  2023. }
  2024. }
  2025. else if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode]))
  2026. {
  2027. unset($aItems[$iFoo]);
  2028. }
  2029. }
  2030. }
  2031. public static function FlattenZList($aList)
  2032. {
  2033. $aResult = array();
  2034. foreach($aList as $value)
  2035. {
  2036. if (!is_array($value))
  2037. {
  2038. $aResult[] = $value;
  2039. }
  2040. else
  2041. {
  2042. $aResult = array_merge($aResult, self::FlattenZList($value));
  2043. }
  2044. }
  2045. return $aResult;
  2046. }
  2047. public static function Init_DefineState($sStateCode, $aStateDef)
  2048. {
  2049. $sTargetClass = self::GetCallersPHPClass("Init");
  2050. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  2051. $sParentState = $aStateDef['attribute_inherit'];
  2052. if (!empty($sParentState))
  2053. {
  2054. // Inherit from the given state (must be defined !)
  2055. //
  2056. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  2057. // Reset the constraint when it was mandatory to set the value at the previous state
  2058. //
  2059. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  2060. {
  2061. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  2062. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  2063. $aToInherit['attribute_list'][$sState] = $iFlags;
  2064. }
  2065. // The inherited configuration could be overriden
  2066. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  2067. }
  2068. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  2069. {
  2070. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  2071. {
  2072. unset($aStateDef['attribute_list'][$sAttCode]);
  2073. }
  2074. }
  2075. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  2076. // by default, create an empty set of transitions associated to that state
  2077. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  2078. }
  2079. public static function Init_DefineHighlightScale($aHighlightScale)
  2080. {
  2081. $sTargetClass = self::GetCallersPHPClass("Init");
  2082. self::$m_aHighlightScales[$sTargetClass] = $aHighlightScale;
  2083. }
  2084. public static function GetHighlightScale($sTargetClass)
  2085. {
  2086. $aScale = array();
  2087. $aParentScale = array();
  2088. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2089. if (!empty($sParentClass))
  2090. {
  2091. // inherit the scale from the parent class
  2092. $aParentScale = self::GetHighlightScale($sParentClass);
  2093. }
  2094. if (array_key_exists($sTargetClass, self::$m_aHighlightScales))
  2095. {
  2096. $aScale = self::$m_aHighlightScales[$sTargetClass];
  2097. }
  2098. return array_merge($aParentScale, $aScale); // Merge both arrays, the values from the last one have precedence
  2099. }
  2100. public static function GetHighlightCode($sTargetClass, $sStateCode)
  2101. {
  2102. $sCode = '';
  2103. if ( array_key_exists($sTargetClass, self::$m_aStates)
  2104. && array_key_exists($sStateCode, self::$m_aStates[$sTargetClass])
  2105. && array_key_exists('highlight', self::$m_aStates[$sTargetClass][$sStateCode]) )
  2106. {
  2107. $sCode = self::$m_aStates[$sTargetClass][$sStateCode]['highlight']['code'];
  2108. }
  2109. else
  2110. {
  2111. // Check the parent's definition
  2112. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2113. if (!empty($sParentClass))
  2114. {
  2115. $sCode = self::GetHighlightCode($sParentClass, $sStateCode);
  2116. }
  2117. }
  2118. return $sCode;
  2119. }
  2120. public static function Init_OverloadStateAttribute($sStateCode, $sAttCode, $iFlags)
  2121. {
  2122. // Warning: this is not sufficient: the flags have to be copied to the states that are inheriting from this state
  2123. $sTargetClass = self::GetCallersPHPClass("Init");
  2124. self::$m_aStates[$sTargetClass][$sStateCode]['attribute_list'][$sAttCode] = $iFlags;
  2125. }
  2126. public static function Init_DefineStimulus($oStimulus)
  2127. {
  2128. $sTargetClass = self::GetCallersPHPClass("Init");
  2129. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  2130. // I wanted to simplify the syntax of the declaration of objects in the biz model
  2131. // Therefore, the reference to the host class is set there
  2132. $oStimulus->SetHostClass($sTargetClass);
  2133. }
  2134. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  2135. {
  2136. $sTargetClass = self::GetCallersPHPClass("Init");
  2137. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  2138. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  2139. }
  2140. public static function Init_InheritLifecycle($sSourceClass = '')
  2141. {
  2142. $sTargetClass = self::GetCallersPHPClass("Init");
  2143. if (empty($sSourceClass))
  2144. {
  2145. // Default: inherit from parent class
  2146. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  2147. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  2148. }
  2149. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  2150. self::$m_aStates[$sTargetClass] = self::$m_aStates[$sSourceClass];
  2151. // #@# Note: the aim is to clone the data, could be an issue if the simuli objects are changed
  2152. self::$m_aStimuli[$sTargetClass] = self::$m_aStimuli[$sSourceClass];
  2153. self::$m_aTransitions[$sTargetClass] = self::$m_aTransitions[$sSourceClass];
  2154. }
  2155. //
  2156. // Static API
  2157. //
  2158. public static function GetRootClass($sClass = null)
  2159. {
  2160. self::_check_subclass($sClass);
  2161. return self::$m_aRootClasses[$sClass];
  2162. }
  2163. public static function IsRootClass($sClass)
  2164. {
  2165. self::_check_subclass($sClass);
  2166. return (self::GetRootClass($sClass) == $sClass);
  2167. }
  2168. public static function GetParentClass($sClass)
  2169. {
  2170. if (count(self::$m_aParentClasses[$sClass]) == 0)
  2171. {
  2172. return null;
  2173. }
  2174. else
  2175. {
  2176. return end(self::$m_aParentClasses[$sClass]);
  2177. }
  2178. }
  2179. /**
  2180. * Tells if a class contains a hierarchical key, and if so what is its AttCode
  2181. * @return mixed String = sAttCode or false if the class is not part of a hierarchy
  2182. */
  2183. public static function IsHierarchicalClass($sClass)
  2184. {
  2185. $sHierarchicalKeyCode = false;
  2186. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  2187. {
  2188. if ($oAtt->IsHierarchicalKey())
  2189. {
  2190. $sHierarchicalKeyCode = $sAttCode; // Found the hierarchical key, no need to continue
  2191. break;
  2192. }
  2193. }
  2194. return $sHierarchicalKeyCode;
  2195. }
  2196. public static function EnumRootClasses()
  2197. {
  2198. return array_unique(self::$m_aRootClasses);
  2199. }
  2200. public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF, $bRootFirst = true)
  2201. {
  2202. self::_check_subclass($sClass);
  2203. if ($bRootFirst)
  2204. {
  2205. $aRes = self::$m_aParentClasses[$sClass];
  2206. }
  2207. else
  2208. {
  2209. $aRes = array_reverse(self::$m_aParentClasses[$sClass], true);
  2210. }
  2211. if ($iOption != ENUM_PARENT_CLASSES_EXCLUDELEAF)
  2212. {
  2213. if ($bRootFirst)
  2214. {
  2215. // Leaf class at the end
  2216. $aRes[] = $sClass;
  2217. }
  2218. else
  2219. {
  2220. // Leaf class on top
  2221. array_unshift($aRes, $sClass);
  2222. }
  2223. }
  2224. return $aRes;
  2225. }
  2226. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  2227. {
  2228. self::_check_subclass($sClass);
  2229. $aRes = self::$m_aChildClasses[$sClass];
  2230. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  2231. {
  2232. // Add it to the list
  2233. $aRes[] = $sClass;
  2234. }
  2235. return $aRes;
  2236. }
  2237. public static function HasChildrenClasses($sClass)
  2238. {
  2239. return (count(self::$m_aChildClasses[$sClass]) > 0);
  2240. }
  2241. public static function EnumCategories()
  2242. {
  2243. return array_keys(self::$m_Category2Class);
  2244. }
  2245. // Note: use EnumChildClasses to take the compound objects into account
  2246. public static function GetSubclasses($sClass)
  2247. {
  2248. self::_check_subclass($sClass);
  2249. $aSubClasses = array();
  2250. foreach(self::$m_aClassParams as $sSubClass => $foo)
  2251. {
  2252. if (is_subclass_of($sSubClass, $sClass))
  2253. {
  2254. $aSubClasses[] = $sSubClass;
  2255. }
  2256. }
  2257. return $aSubClasses;
  2258. }
  2259. public static function GetClasses($sCategories = '', $bStrict = false)
  2260. {
  2261. $aCategories = explode(',', $sCategories);
  2262. $aClasses = array();
  2263. foreach($aCategories as $sCategory)
  2264. {
  2265. $sCategory = trim($sCategory);
  2266. if (strlen($sCategory) == 0)
  2267. {
  2268. return array_keys(self::$m_aClassParams);
  2269. }
  2270. if (array_key_exists($sCategory, self::$m_Category2Class))
  2271. {
  2272. $aClasses = array_merge($aClasses, self::$m_Category2Class[$sCategory]);
  2273. }
  2274. elseif ($bStrict)
  2275. {
  2276. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  2277. }
  2278. }
  2279. return array_unique($aClasses);
  2280. }
  2281. public static function HasTable($sClass)
  2282. {
  2283. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  2284. return true;
  2285. }
  2286. public static function IsAbstract($sClass)
  2287. {
  2288. $oReflection = new ReflectionClass($sClass);
  2289. return $oReflection->isAbstract();
  2290. }
  2291. protected static $m_aQueryStructCache = array();
  2292. public static function PrepareQueryArguments($aArgs)
  2293. {
  2294. // Translate any object into scalars
  2295. //
  2296. $aScalarArgs = array();
  2297. foreach($aArgs as $sArgName => $value)
  2298. {
  2299. if (self::IsValidObject($value))
  2300. {
  2301. if (strpos($sArgName, '->object()') === false)
  2302. {
  2303. // Lazy syntax - develop the object contextual parameters
  2304. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgsForQuery($sArgName));
  2305. }
  2306. else
  2307. {
  2308. // Leave as is
  2309. $aScalarArgs[$sArgName] = $value;
  2310. }
  2311. }
  2312. else
  2313. {
  2314. if (is_scalar($value))
  2315. {
  2316. $aScalarArgs[$sArgName] = (string) $value;
  2317. }
  2318. elseif (is_null($value))
  2319. {
  2320. $aScalarArgs[$sArgName] = null;
  2321. }
  2322. }
  2323. }
  2324. // Add standard contextual arguments
  2325. //
  2326. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  2327. return $aScalarArgs;
  2328. }
  2329. public static function MakeGroupByQuery(DBObjectSearch $oFilter, $aArgs, $aGroupByExpr, $bExcludeNullValues = false)
  2330. {
  2331. $aAttToLoad = array();
  2332. if ($bExcludeNullValues)
  2333. {
  2334. // Null values are not handled (though external keys set to 0 are allowed)
  2335. $oQueryFilter = $oFilter->DeepClone();
  2336. foreach ($aGroupByExpr as $oGroupByExp)
  2337. {
  2338. $oNull = new FunctionExpression('ISNULL', array($oGroupByExp));
  2339. $oNotNull = new BinaryExpression($oNull, '!=', new TrueExpression());
  2340. $oQueryFilter->AddConditionExpression($oNotNull);
  2341. }
  2342. }
  2343. else
  2344. {
  2345. $oQueryFilter = $oFilter;
  2346. }
  2347. $oSelect = self::MakeSelectStructure($oQueryFilter, array(), $aArgs, $aAttToLoad, null, 0, 0, false, $aGroupByExpr);
  2348. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2349. try
  2350. {
  2351. $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
  2352. $sRes = $oSelect->RenderGroupBy($aScalarArgs, $bBeautifulSQL);
  2353. }
  2354. catch (MissingQueryArgument $e)
  2355. {
  2356. // Add some information...
  2357. $e->addInfo('OQL', $oFilter->ToOQL());
  2358. throw $e;
  2359. }
  2360. self::AddQueryTraceGroupBy($oFilter, $aArgs, $aGroupByExpr, $sRes);
  2361. return $sRes;
  2362. }
  2363. /**
  2364. * @param hash $aOrderBy Array of '[<classalias>.]attcode' => bAscending
  2365. */
  2366. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $aAttToLoad = null, $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false)
  2367. {
  2368. // Check the order by specification, and prefix with the class alias
  2369. // and make sure that the ordering columns are going to be selected
  2370. //
  2371. $sClass = $oFilter->GetClass();
  2372. $sClassAlias = $oFilter->GetClassAlias();
  2373. $aOrderSpec = array();
  2374. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  2375. {
  2376. if (!is_bool($bAscending))
  2377. {
  2378. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  2379. }
  2380. $iDotPos = strpos($sFieldAlias, '.');
  2381. if ($iDotPos === false)
  2382. {
  2383. $sAttClass = $sClass;
  2384. $sAttClassAlias = $sClassAlias;
  2385. $sAttCode = $sFieldAlias;
  2386. }
  2387. else
  2388. {
  2389. $sAttClassAlias = substr($sFieldAlias, 0, $iDotPos);
  2390. $sAttClass = $oFilter->GetClassName($sAttClassAlias);
  2391. $sAttCode = substr($sFieldAlias, $iDotPos + 1);
  2392. }
  2393. if ($sAttCode != 'id')
  2394. {
  2395. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sAttCode, self::GetAttributesList($sAttClass));
  2396. $oAttDef = self::GetAttributeDef($sAttClass, $sAttCode);
  2397. foreach($oAttDef->GetOrderBySQLExpressions($sAttClassAlias) as $sSQLExpression)
  2398. {
  2399. $aOrderSpec[$sSQLExpression] = $bAscending;
  2400. }
  2401. }
  2402. else
  2403. {
  2404. $aOrderSpec['`'.$sAttClassAlias.$sAttCode.'`'] = $bAscending;
  2405. }
  2406. // Make sure that the columns used for sorting are present in the loaded columns
  2407. if (!is_null($aAttToLoad) && !isset($aAttToLoad[$sAttClassAlias][$sAttCode]))
  2408. {
  2409. $aAttToLoad[$sAttClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sAttClass, $sAttCode);
  2410. }
  2411. }
  2412. $oSelect = self::MakeSelectStructure($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount);
  2413. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2414. try
  2415. {
  2416. $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
  2417. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount, $bBeautifulSQL);
  2418. if ($sClassAlias == '_itop_')
  2419. {
  2420. echo $sRes."<br/>\n";
  2421. }
  2422. }
  2423. catch (MissingQueryArgument $e)
  2424. {
  2425. // Add some information...
  2426. $e->addInfo('OQL', $oFilter->ToOQL());
  2427. throw $e;
  2428. }
  2429. self::AddQueryTraceSelect($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sRes);
  2430. return $sRes;
  2431. }
  2432. protected static function MakeSelectStructure(DBObjectSearch $oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $aGroupByExpr = null)
  2433. {
  2434. // Hide objects that are not visible to the current user
  2435. //
  2436. if (!$oFilter->IsAllDataAllowed() && !$oFilter->IsDataFiltered())
  2437. {
  2438. $oVisibleObjects = UserRights::GetSelectFilter($oFilter->GetClass(), $oFilter->GetModifierProperties('UserRightsGetSelectFilter'));
  2439. if ($oVisibleObjects === false)
  2440. {
  2441. // Make sure this is a valid search object, saying NO for all
  2442. $oVisibleObjects = DBObjectSearch::FromEmptySet($oFilter->GetClass());
  2443. }
  2444. if (is_object($oVisibleObjects))
  2445. {
  2446. $oFilter->MergeWith($oVisibleObjects);
  2447. $oFilter->SetDataFiltered();
  2448. }
  2449. else
  2450. {
  2451. // should be true at this point, meaning that no additional filtering
  2452. // is required
  2453. }
  2454. }
  2455. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2456. //
  2457. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2458. // Create a unique cache id
  2459. //
  2460. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  2461. {
  2462. // Need to identify the query
  2463. $sOqlQuery = $oFilter->ToOql();
  2464. if (count($aModifierProperties))
  2465. {
  2466. array_multisort($aModifierProperties);
  2467. $sModifierProperties = json_encode($aModifierProperties);
  2468. }
  2469. else
  2470. {
  2471. $sModifierProperties = '';
  2472. }
  2473. $sRawId = $sOqlQuery.$sModifierProperties;
  2474. if (!is_null($aAttToLoad))
  2475. {
  2476. $sRawId .= json_encode($aAttToLoad);
  2477. }
  2478. if (!is_null($aGroupByExpr))
  2479. {
  2480. foreach($aGroupByExpr as $sAlias => $oExpr)
  2481. {
  2482. $sRawId .= 'g:'.$sAlias.'!'.$oExpr->Render();
  2483. }
  2484. }
  2485. $sRawId .= $bGetCount;
  2486. $sOqlId = md5($sRawId);
  2487. }
  2488. else
  2489. {
  2490. $sOqlQuery = "SELECTING... ".$oFilter->GetClass();
  2491. $sOqlId = "query id ? n/a";
  2492. }
  2493. // Query caching
  2494. //
  2495. if (self::$m_bQueryCacheEnabled)
  2496. {
  2497. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  2498. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  2499. // to use a hash (like md5) of the string as the key !
  2500. //
  2501. // Example of two queries that were found as similar by the hash array:
  2502. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTO' AND CustomerContract.customer_id = 2
  2503. // and
  2504. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTR' AND CustomerContract.customer_id = 2
  2505. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  2506. //
  2507. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  2508. {
  2509. // hit!
  2510. $oSelect = unserialize(serialize(self::$m_aQueryStructCache[$sOqlId]));
  2511. // Note: cloning is not enough because the subtree is made of objects
  2512. }
  2513. elseif (self::$m_bUseAPCCache)
  2514. {
  2515. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  2516. //
  2517. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-query-cache-'.$sOqlId;
  2518. $oKPI = new ExecutionKPI();
  2519. $result = apc_fetch($sOqlAPCCacheId);
  2520. $oKPI->ComputeStats('Query APC (fetch)', $sOqlQuery);
  2521. if (is_object($result))
  2522. {
  2523. $oSelect = $result;
  2524. self::$m_aQueryStructCache[$sOqlId] = $oSelect;
  2525. }
  2526. }
  2527. }
  2528. if (!isset($oSelect))
  2529. {
  2530. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties, $aGroupByExpr);
  2531. $oKPI = new ExecutionKPI();
  2532. $oSelect = self::MakeQuery($oBuild, $oFilter, $aAttToLoad, array(), true /* main query */);
  2533. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2534. $oSelect->SetSourceOQL($sOqlQuery);
  2535. if ($aGroupByExpr)
  2536. {
  2537. $aCols = $oBuild->m_oQBExpressions->GetGroupBy();
  2538. $oSelect->SetGroupBy($aCols);
  2539. $oSelect->SetSelect($aCols);
  2540. }
  2541. else
  2542. {
  2543. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2544. }
  2545. if (self::$m_bOptimizeQueries)
  2546. {
  2547. if ($bGetCount)
  2548. {
  2549. // Simplify the query if just getting the count
  2550. $oSelect->SetSelect(array());
  2551. }
  2552. $oBuild->m_oQBExpressions->GetMandatoryTables($aMandatoryTables);
  2553. $oSelect->OptimizeJoins($aMandatoryTables);
  2554. }
  2555. $oKPI->ComputeStats('MakeQuery (select)', $sOqlQuery);
  2556. if (self::$m_bQueryCacheEnabled)
  2557. {
  2558. if (self::$m_bUseAPCCache)
  2559. {
  2560. $oKPI = new ExecutionKPI();
  2561. apc_store($sOqlAPCCacheId, $oSelect, self::$m_iQueryCacheTTL);
  2562. $oKPI->ComputeStats('Query APC (store)', $sOqlQuery);
  2563. }
  2564. self::$m_aQueryStructCache[$sOqlId] = $oSelect->DeepClone();
  2565. }
  2566. }
  2567. // Join to an additional table, if required...
  2568. //
  2569. if ($aExtendedDataSpec != null)
  2570. {
  2571. $sTableAlias = '_extended_data_';
  2572. $aExtendedFields = array();
  2573. foreach($aExtendedDataSpec['fields'] as $sColumn)
  2574. {
  2575. $sColRef = $oFilter->GetClassAlias().'_extdata_'.$sColumn;
  2576. $aExtendedFields[$sColRef] = new FieldExpressionResolved($sColumn, $sTableAlias);
  2577. }
  2578. $oSelectExt = new SQLQuery($aExtendedDataSpec['table'], $sTableAlias, $aExtendedFields);
  2579. $oSelect->AddInnerJoin($oSelectExt, 'id', $aExtendedDataSpec['join_key'] /*, $sTableAlias*/);
  2580. }
  2581. return $oSelect;
  2582. }
  2583. protected static function AddQueryTraceSelect($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sSql)
  2584. {
  2585. if (self::$m_bTraceQueries)
  2586. {
  2587. $aQueryData = array(
  2588. 'type' => 'select',
  2589. 'filter' => $oFilter,
  2590. 'order_by' => $aOrderBy,
  2591. 'args' => $aArgs,
  2592. 'att_to_load' => $aAttToLoad,
  2593. 'extended_data_spec' => $aExtendedDataSpec,
  2594. 'limit_count' => $iLimitCount,
  2595. 'limit_start' => $iLimitStart,
  2596. 'is_count' => $bGetCount
  2597. );
  2598. $sOql = $oFilter->ToOQL(true, $aArgs);
  2599. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  2600. }
  2601. }
  2602. protected static function AddQueryTraceGroupBy($oFilter, $aArgs, $aGroupByExpr, $sSql)
  2603. {
  2604. if (self::$m_bTraceQueries)
  2605. {
  2606. $aQueryData = array(
  2607. 'type' => 'group_by',
  2608. 'filter' => $oFilter,
  2609. 'args' => $aArgs,
  2610. 'group_by_expr' => $aGroupByExpr
  2611. );
  2612. $sOql = $oFilter->ToOQL(true, $aArgs);
  2613. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  2614. }
  2615. }
  2616. protected static function AddQueryTrace($aQueryData, $sOql, $sSql)
  2617. {
  2618. if (self::$m_bTraceQueries)
  2619. {
  2620. $sQueryId = md5(serialize($aQueryData));
  2621. $sMySQLQueryId = md5($sSql);
  2622. if(!isset(self::$m_aQueriesLog[$sQueryId]))
  2623. {
  2624. self::$m_aQueriesLog[$sQueryId]['data'] = serialize($aQueryData);
  2625. self::$m_aQueriesLog[$sQueryId]['oql'] = $sOql;
  2626. self::$m_aQueriesLog[$sQueryId]['hits'] = 1;
  2627. }
  2628. else
  2629. {
  2630. self::$m_aQueriesLog[$sQueryId]['hits']++;
  2631. }
  2632. if(!isset(self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]))
  2633. {
  2634. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['sql'] = $sSql;
  2635. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count'] = 1;
  2636. $iTableCount = count(CMDBSource::ExplainQuery($sSql));
  2637. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['table_count'] = $iTableCount;
  2638. }
  2639. else
  2640. {
  2641. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count']++;
  2642. }
  2643. }
  2644. }
  2645. public static function RecordQueryTrace()
  2646. {
  2647. if (!self::$m_bTraceQueries) return;
  2648. $iOqlCount = count(self::$m_aQueriesLog);
  2649. $iSqlCount = 0;
  2650. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2651. {
  2652. $iSqlCount += $aOqlData['hits'];
  2653. }
  2654. $sHtml = "<h2>Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount</h2>\n";
  2655. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2656. {
  2657. $sOql = $aOqlData['oql'];
  2658. $sHits = $aOqlData['hits'];
  2659. $sHtml .= "<p><b>$sHits</b> hits for OQL query: $sOql</p>\n";
  2660. $sHtml .= "<ul id=\"ClassesRelationships\" class=\"treeview\">\n";
  2661. foreach($aOqlData['queries'] as $aSqlData)
  2662. {
  2663. $sQuery = $aSqlData['sql'];
  2664. $sSqlHits = $aSqlData['count'];
  2665. $iTableCount = $aSqlData['table_count'];
  2666. $sHtml .= "<li><b>$sSqlHits</b> hits for SQL ($iTableCount tables): <pre style=\"font-size:60%\">$sQuery</pre></li>\n";
  2667. }
  2668. $sHtml .= "</ul>\n";
  2669. }
  2670. $sLogFile = 'queries.latest';
  2671. file_put_contents(APPROOT.'data/'.$sLogFile.'.html', $sHtml);
  2672. $sLog = "<?php\n\$aQueriesLog = ".var_export(self::$m_aQueriesLog, true).";";
  2673. file_put_contents(APPROOT.'data/'.$sLogFile.'.log', $sLog);
  2674. // Cumulate the queries
  2675. $sAllQueries = APPROOT.'data/queries.log';
  2676. if (file_exists($sAllQueries))
  2677. {
  2678. // Merge the new queries into the existing log
  2679. include($sAllQueries);
  2680. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2681. {
  2682. if (!array_key_exists($sQueryId, $aQueriesLog))
  2683. {
  2684. $aQueriesLog[$sQueryId] = $aOqlData;
  2685. }
  2686. }
  2687. }
  2688. else
  2689. {
  2690. $aQueriesLog = self::$m_aQueriesLog;
  2691. }
  2692. $sLog = "<?php\n\$aQueriesLog = ".var_export($aQueriesLog, true).";";
  2693. file_put_contents($sAllQueries, $sLog);
  2694. }
  2695. protected static function MakeModifierProperties($oFilter)
  2696. {
  2697. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2698. //
  2699. $aModifierProperties = array();
  2700. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  2701. {
  2702. // Lowest precedence: the application context
  2703. $aPluginProps = ApplicationContext::GetPluginProperties($sPluginClass);
  2704. // Highest precedence: programmatically specified (or OQL)
  2705. foreach($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value)
  2706. {
  2707. $aPluginProps[$sProp] = $value;
  2708. }
  2709. if (count($aPluginProps) > 0)
  2710. {
  2711. $aModifierProperties[$sPluginClass] = $aPluginProps;
  2712. }
  2713. }
  2714. return $aModifierProperties;
  2715. }
  2716. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  2717. {
  2718. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2719. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties);
  2720. $oSelect = self::MakeQuery($oBuild, $oFilter, null, array(), true /* main query */);
  2721. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2722. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2723. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2724. return $oSelect->RenderDelete($aScalarArgs);
  2725. }
  2726. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  2727. {
  2728. // $aValues is an array of $sAttCode => $value
  2729. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2730. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties);
  2731. $oSelect = self::MakeQuery($oBuild, $oFilter, null, $aValues, true /* main query */);
  2732. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2733. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2734. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2735. return $oSelect->RenderUpdate($aScalarArgs);
  2736. }
  2737. private static function MakeQuery(&$oBuild, DBObjectSearch $oFilter, $aAttToLoad = null, $aValues = array(), $bIsMainQueryUNUSED = false)
  2738. {
  2739. // Note: query class might be different than the class of the filter
  2740. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  2741. $sClass = $oFilter->GetFirstJoinedClass();
  2742. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  2743. $bIsOnQueriedClass = array_key_exists($sClassAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  2744. self::DbgTrace("Entering: ".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  2745. $sRootClass = self::GetRootClass($sClass);
  2746. $sKeyField = self::DBGetKey($sClass);
  2747. if ($bIsOnQueriedClass)
  2748. {
  2749. // default to the whole list of attributes + the very std id/finalclass
  2750. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.'id', new FieldExpression('id', $sClassAlias));
  2751. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  2752. {
  2753. $aAttList = self::ListAttributeDefs($sClass);
  2754. }
  2755. else
  2756. {
  2757. $aAttList = $aAttToLoad[$sClassAlias];
  2758. }
  2759. foreach ($aAttList as $sAttCode => $oAttDef)
  2760. {
  2761. if (!$oAttDef->IsScalar()) continue;
  2762. // keep because it can be used for sorting - if (!$oAttDef->LoadInObject()) continue;
  2763. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  2764. {
  2765. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.$sAttCode.$sColId, new FieldExpression($sAttCode.$sColId, $sClassAlias));
  2766. }
  2767. }
  2768. // Transform the full text condition into additional condition expression
  2769. $aFullText = $oFilter->GetCriteria_FullText();
  2770. if (count($aFullText) > 0)
  2771. {
  2772. $aFullTextFields = array();
  2773. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2774. {
  2775. if (!$oAttDef->IsScalar()) continue;
  2776. if ($oAttDef->IsExternalKey()) continue;
  2777. $aFullTextFields[] = new FieldExpression($sAttCode, $sClassAlias);
  2778. }
  2779. $oTextFields = new CharConcatWSExpression(' ', $aFullTextFields);
  2780. foreach($aFullText as $sFTNeedle)
  2781. {
  2782. $oNewCond = new BinaryExpression($oTextFields, 'LIKE', new ScalarExpression("%$sFTNeedle%"));
  2783. $oBuild->m_oQBExpressions->AddCondition($oNewCond);
  2784. }
  2785. }
  2786. }
  2787. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  2788. $aExpectedAtts = array(); // array of (attcode => fieldexpression)
  2789. //echo "<p>".__LINE__.": GetUnresolvedFields($sClassAlias, ...)</p>\n";
  2790. $oBuild->m_oQBExpressions->GetUnresolvedFields($sClassAlias, $aExpectedAtts);
  2791. // Compute a clear view of required joins (from the current class)
  2792. // Build the list of external keys:
  2793. // -> ext keys required by an explicit join
  2794. // -> ext keys mentionned in a 'pointing to' condition
  2795. // -> ext keys required for an external field
  2796. // -> ext keys required for a friendly name
  2797. //
  2798. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  2799. //
  2800. // Optimization: could be partially computed once for all (cached) ?
  2801. //
  2802. if ($bIsOnQueriedClass)
  2803. {
  2804. // Get all Ext keys for the queried class (??)
  2805. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  2806. {
  2807. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2808. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  2809. }
  2810. }
  2811. // Get all Ext keys used by the filter
  2812. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $aPointingTo)
  2813. {
  2814. if (array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  2815. {
  2816. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2817. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  2818. }
  2819. }
  2820. $aFNJoinAlias = array(); // array of (subclass => alias)
  2821. if (array_key_exists('friendlyname', $aExpectedAtts))
  2822. {
  2823. // To optimize: detect a restriction on child classes in the condition expression
  2824. // e.g. SELECT FunctionalCI WHERE finalclass IN ('Server', 'VirtualMachine')
  2825. $oNameExpression = self::GetExtendedNameExpression($sClass);
  2826. $aNameFields = array();
  2827. $oNameExpression->GetUnresolvedFields('', $aNameFields);
  2828. $aTranslateNameFields = array();
  2829. foreach($aNameFields as $sSubClass => $aFields)
  2830. {
  2831. foreach($aFields as $sAttCode => $oField)
  2832. {
  2833. $oAttDef = self::GetAttributeDef($sSubClass, $sAttCode);
  2834. if ($oAttDef->IsExternalKey())
  2835. {
  2836. $sClassOfAttribute = self::$m_aAttribOrigins[$sSubClass][$sAttCode];
  2837. $aExtKeys[$sClassOfAttribute][$sAttCode] = array();
  2838. }
  2839. elseif ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  2840. {
  2841. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2842. $sClassOfAttribute = self::$m_aAttribOrigins[$sSubClass][$sKeyAttCode];
  2843. $aExtKeys[$sClassOfAttribute][$sKeyAttCode][$sAttCode] = $oAttDef;
  2844. }
  2845. else
  2846. {
  2847. $sClassOfAttribute = self::GetAttributeOrigin($sSubClass, $sAttCode);
  2848. }
  2849. if (self::IsParentClass($sClassOfAttribute, $sClass))
  2850. {
  2851. // The attribute is part of the standard query
  2852. //
  2853. $sAliasForAttribute = $sClassAlias;
  2854. }
  2855. else
  2856. {
  2857. // The attribute will be available from an additional outer join
  2858. // For each subclass (table) one single join is enough
  2859. //
  2860. if (!array_key_exists($sClassOfAttribute, $aFNJoinAlias))
  2861. {
  2862. $sAliasForAttribute = $oBuild->GenerateClassAlias($sClassAlias.'_fn_'.$sClassOfAttribute, $sClassOfAttribute);
  2863. $aFNJoinAlias[$sClassOfAttribute] = $sAliasForAttribute;
  2864. }
  2865. else
  2866. {
  2867. $sAliasForAttribute = $aFNJoinAlias[$sClassOfAttribute];
  2868. }
  2869. }
  2870. $aTranslateNameFields[$sSubClass][$sAttCode] = new FieldExpression($sAttCode, $sAliasForAttribute);
  2871. }
  2872. }
  2873. $oNameExpression = $oNameExpression->Translate($aTranslateNameFields, false);
  2874. $aTranslateNow = array();
  2875. $aTranslateNow[$sClassAlias]['friendlyname'] = $oNameExpression;
  2876. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  2877. }
  2878. // Add the ext fields used in the select (eventually adds an external key)
  2879. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2880. {
  2881. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  2882. {
  2883. if (array_key_exists($sAttCode, $aExpectedAtts))
  2884. {
  2885. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2886. if ($sKeyAttCode != 'id')
  2887. {
  2888. // Add the external attribute
  2889. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2890. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  2891. }
  2892. }
  2893. }
  2894. }
  2895. // First query built upon on the leaf (ie current) class
  2896. //
  2897. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  2898. if (self::HasTable($sClass))
  2899. {
  2900. $oSelectBase = self::MakeQuerySingleTable($oBuild, $oFilter, $sClass, $aExtKeys, $aValues);
  2901. }
  2902. else
  2903. {
  2904. $oSelectBase = null;
  2905. // As the join will not filter on the expected classes, we have to specify it explicitely
  2906. $sExpectedClasses = implode("', '", self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  2907. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  2908. $oBuild->m_oQBExpressions->AddCondition($oFinalClassRestriction);
  2909. }
  2910. // Then we join the queries of the eventual parent classes (compound model)
  2911. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  2912. {
  2913. if (!self::HasTable($sParentClass)) continue;
  2914. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  2915. $oSelectParentTable = self::MakeQuerySingleTable($oBuild, $oFilter, $sParentClass, $aExtKeys, $aValues);
  2916. if (is_null($oSelectBase))
  2917. {
  2918. $oSelectBase = $oSelectParentTable;
  2919. }
  2920. else
  2921. {
  2922. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  2923. }
  2924. }
  2925. // Filter on objects referencing me
  2926. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  2927. {
  2928. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  2929. {
  2930. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  2931. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  2932. //self::DbgTrace($oForeignFilter);
  2933. //self::DbgTrace($oForeignFilter->ToOQL());
  2934. //self::DbgTrace($oSelectForeign);
  2935. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  2936. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  2937. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sForeignKeyAttCode, $sForeignClassAlias));
  2938. if ($oForeignKeyAttDef instanceof AttributeObjectKey)
  2939. {
  2940. $sClassAttCode = $oForeignKeyAttDef->Get('class_attcode');
  2941. // Add the condition: `$sForeignClassAlias`.$sClassAttCode IN (subclasses of $sClass')
  2942. $oClassListExpr = ListExpression::FromScalars(self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  2943. $oClassExpr = new FieldExpression($sClassAttCode, $sForeignClassAlias);
  2944. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  2945. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  2946. }
  2947. $oSelectForeign = self::MakeQuery($oBuild, $oForeignFilter, $aAttToLoad);
  2948. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  2949. $sForeignKeyTable = $oJoinExpr->GetParent();
  2950. $sForeignKeyColumn = $oJoinExpr->GetName();
  2951. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  2952. }
  2953. }
  2954. // Filter on related objects
  2955. //
  2956. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  2957. {
  2958. $oSubFilter = $aCritInfo['flt'];
  2959. $sRelCode = $aCritInfo['relcode'];
  2960. $iMaxDepth = $aCritInfo['maxdepth'];
  2961. // Get the starting point objects
  2962. $oStartSet = new CMDBObjectSet($oSubFilter);
  2963. // Get the objects related to those objects... recursively...
  2964. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  2965. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  2966. // #@# todo - related objects and expressions...
  2967. // Create condition
  2968. if (count($aRestriction) > 0)
  2969. {
  2970. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  2971. }
  2972. else
  2973. {
  2974. // Quick N'dirty -> generate an empty set
  2975. $oSelectBase->AddCondition('false');
  2976. }
  2977. }
  2978. // Additional JOINS for Friendly names
  2979. //
  2980. foreach ($aFNJoinAlias as $sSubClass => $sSubClassAlias)
  2981. {
  2982. $oSubClassFilter = new DBObjectSearch($sSubClass, $sSubClassAlias);
  2983. $oSelectFN = self::MakeQuerySingleTable($oBuild, $oSubClassFilter, $sSubClass, $aExtKeys, array());
  2984. $oSelectBase->AddLeftJoin($oSelectFN, $sKeyField, self::DBGetKey($sSubClass));
  2985. }
  2986. // That's all... cross fingers and we'll get some working query
  2987. //MyHelpers::var_dump_html($oSelectBase, true);
  2988. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  2989. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  2990. return $oSelectBase;
  2991. }
  2992. protected static function MakeQuerySingleTable(&$oBuild, $oFilter, $sTableClass, $aExtKeys, $aValues)
  2993. {
  2994. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  2995. //echo "MAKEQUERY($sTableClass)-liste des clefs externes($sTableClass): <pre>".print_r($aExtKeys, true)."</pre><br/>\n";
  2996. // Prepare the query for a single table (compound objects)
  2997. // Ignores the items (attributes/filters) that are not on the target table
  2998. // Perform an (inner or left) join for every external key (and specify the expected fields)
  2999. //
  3000. // Returns an SQLQuery
  3001. //
  3002. $sTargetClass = $oFilter->GetFirstJoinedClass();
  3003. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  3004. $sTable = self::DBGetTable($sTableClass);
  3005. $sTableAlias = $oBuild->GenerateTableAlias($sTargetAlias.'_'.$sTable, $sTable);
  3006. $aTranslation = array();
  3007. $aExpectedAtts = array();
  3008. $oBuild->m_oQBExpressions->GetUnresolvedFields($sTargetAlias, $aExpectedAtts);
  3009. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  3010. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  3011. // 1 - SELECT and UPDATE
  3012. //
  3013. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  3014. //
  3015. $aUpdateValues = array();
  3016. // 1/a - Get the key and friendly name
  3017. //
  3018. // We need one pkey to be the key, let's take the first one available
  3019. $oSelectedIdField = null;
  3020. $oIdField = new FieldExpressionResolved(self::DBGetKey($sTableClass), $sTableAlias);
  3021. $aTranslation[$sTargetAlias]['id'] = $oIdField;
  3022. if ($bIsOnQueriedClass)
  3023. {
  3024. // Add this field to the list of queried fields (required for the COUNT to work fine)
  3025. $oSelectedIdField = $oIdField;
  3026. }
  3027. // 1/b - Get the other attributes
  3028. //
  3029. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  3030. {
  3031. // Skip this attribute if not defined in this table
  3032. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  3033. // Skip this attribute if not made of SQL columns
  3034. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  3035. // Update...
  3036. //
  3037. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  3038. {
  3039. assert ($oAttDef->IsDirectField());
  3040. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  3041. {
  3042. $aUpdateValues[$sColumn] = $sValue;
  3043. }
  3044. }
  3045. }
  3046. // 2 - The SQL query, for this table only
  3047. //
  3048. $oSelectBase = new SQLQuery($sTable, $sTableAlias, array(), $bIsOnQueriedClass, $aUpdateValues, $oSelectedIdField);
  3049. // 3 - Resolve expected expressions (translation table: alias.attcode => table.column)
  3050. //
  3051. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  3052. {
  3053. // Skip this attribute if not defined in this table
  3054. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  3055. // Select...
  3056. //
  3057. if ($oAttDef->IsExternalField())
  3058. {
  3059. // skip, this will be handled in the joined tables (done hereabove)
  3060. }
  3061. else
  3062. {
  3063. //echo "<p>MakeQuerySingleTable: Field $sAttCode is part of the table $sTable (named: $sTableAlias)</p>";
  3064. // standard field, or external key
  3065. // add it to the output
  3066. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  3067. {
  3068. if (array_key_exists($sAttCode.$sColId, $aExpectedAtts))
  3069. {
  3070. $oFieldSQLExp = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  3071. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  3072. {
  3073. $oFieldSQLExp = $oQueryModifier->GetFieldExpression($oBuild, $sTargetClass, $sAttCode, $sColId, $oFieldSQLExp, $oSelectBase);
  3074. }
  3075. $aTranslation[$sTargetAlias][$sAttCode.$sColId] = $oFieldSQLExp;
  3076. }
  3077. }
  3078. }
  3079. }
  3080. //echo "MAKEQUERY- Classe $sTableClass<br/>\n";
  3081. // 4 - The external keys -> joins...
  3082. //
  3083. $aAllPointingTo = $oFilter->GetCriteria_PointingTo();
  3084. if (array_key_exists($sTableClass, $aExtKeys))
  3085. {
  3086. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  3087. {
  3088. $oKeyAttDef = self::GetAttributeDef($sTableClass, $sKeyAttCode);
  3089. $aPointingTo = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  3090. //echo "MAKEQUERY-Cle '$sKeyAttCode'<br/>\n";
  3091. if (!array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  3092. {
  3093. //echo "MAKEQUERY-Ajoutons l'operateur TREE_OPERATOR_EQUALS pour $sKeyAttCode<br/>\n";
  3094. // The join was not explicitely defined in the filter,
  3095. // we need to do it now
  3096. $sKeyClass = $oKeyAttDef->GetTargetClass();
  3097. $sKeyClassAlias = $oBuild->GenerateClassAlias($sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  3098. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  3099. $aAllPointingTo[$sKeyAttCode][TREE_OPERATOR_EQUALS][$sKeyClassAlias] = $oExtFilter;
  3100. }
  3101. }
  3102. }
  3103. //echo "MAKEQUERY-liste des clefs de jointure: <pre>".print_r(array_keys($aAllPointingTo), true)."</pre><br/>\n";
  3104. foreach ($aAllPointingTo as $sKeyAttCode => $aPointingTo)
  3105. {
  3106. foreach($aPointingTo as $iOperatorCode => $aFilter)
  3107. {
  3108. foreach($aFilter as $oExtFilter)
  3109. {
  3110. if (!MetaModel::IsValidAttCode($sTableClass, $sKeyAttCode)) continue; // Not defined in the class, skip it
  3111. // The aliases should not conflict because normalization occured while building the filter
  3112. $oKeyAttDef = self::GetAttributeDef($sTableClass, $sKeyAttCode);
  3113. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  3114. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  3115. //echo "MAKEQUERY-$sTableClass::$sKeyAttCode Foreach PointingTo($iOperatorCode) <span style=\"color:red\">$sKeyClass (alias:$sKeyClassAlias)</span><br/>\n";
  3116. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  3117. //echo "MAKEQUERY-array_key_exists($sTableClass, \$aExtKeys)<br/>\n";
  3118. if ($iOperatorCode == TREE_OPERATOR_EQUALS)
  3119. {
  3120. if (array_key_exists($sTableClass, $aExtKeys) && array_key_exists($sKeyAttCode, $aExtKeys[$sTableClass]))
  3121. {
  3122. // Specify expected attributes for the target class query
  3123. // ... and use the current alias !
  3124. $aTranslateNow = array(); // Translation for external fields - must be performed before the join is done (recursion...)
  3125. foreach($aExtKeys[$sTableClass][$sKeyAttCode] as $sAttCode => $oAtt)
  3126. {
  3127. //echo "MAKEQUERY aExtKeys[$sTableClass][$sKeyAttCode] => $sAttCode-oAtt: <pre>".print_r($oAtt, true)."</pre><br/>\n";
  3128. if ($oAtt instanceof AttributeFriendlyName)
  3129. {
  3130. // Note: for a given ext key, there is one single attribute "friendly name"
  3131. $aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);
  3132. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);</b></p>\n";
  3133. }
  3134. else
  3135. {
  3136. $sExtAttCode = $oAtt->GetExtAttCode();
  3137. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  3138. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  3139. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  3140. {
  3141. $aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);
  3142. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);</b></p>\n";
  3143. }
  3144. //echo "<p><b>ExtAttr2: $sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</b></p>\n";
  3145. }
  3146. }
  3147. if ($oKeyAttDef instanceof AttributeObjectKey)
  3148. {
  3149. // Add the condition: `$sTargetAlias`.$sClassAttCode IN (subclasses of $sKeyClass')
  3150. $sClassAttCode = $oKeyAttDef->Get('class_attcode');
  3151. $oClassAttDef = self::GetAttributeDef($sTargetClass, $sClassAttCode);
  3152. foreach ($oClassAttDef->GetSQLExpressions() as $sColID => $sSQLExpr)
  3153. {
  3154. $aTranslateNow[$sTargetAlias][$sClassAttCode.$sColId] = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  3155. }
  3156. $oClassListExpr = ListExpression::FromScalars(self::EnumChildClasses($sKeyClass, ENUM_CHILD_CLASSES_ALL));
  3157. $oClassExpr = new FieldExpression($sClassAttCode, $sTargetAlias);
  3158. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  3159. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  3160. }
  3161. // Translate prior to recursing
  3162. //
  3163. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."\n".print_r($aTranslateNow, true)."</pre></p>\n";
  3164. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  3165. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  3166. //echo "<p>External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()/p>\n";
  3167. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  3168. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression('id', $sKeyClassAlias));
  3169. //echo "<p>Recursive MakeQuery ".__LINE__.": <pre>\n".print_r($oBuild->GetRootFilter()->GetSelectedClasses(), true)."</pre></p>\n";
  3170. $oSelectExtKey = self::MakeQuery($oBuild, $oExtFilter);
  3171. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  3172. $sExternalKeyTable = $oJoinExpr->GetParent();
  3173. $sExternalKeyField = $oJoinExpr->GetName();
  3174. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3175. $sLocalKeyField = current($aCols); // get the first column for an external key
  3176. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  3177. if ($oKeyAttDef->IsNullAllowed())
  3178. {
  3179. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  3180. }
  3181. else
  3182. {
  3183. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  3184. }
  3185. }
  3186. }
  3187. elseif(self::$m_aAttribOrigins[$sKeyClass][$sKeyAttCode] == $sTableClass)
  3188. {
  3189. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sKeyAttCode, $sKeyClassAlias));
  3190. $oSelectExtKey = self::MakeQuery($oBuild, $oExtFilter);
  3191. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  3192. //echo "MAKEQUERY-PopJoinField pour $sKeyAttCode, $sKeyClassAlias: <pre>".print_r($oJoinExpr, true)."</pre><br/>\n";
  3193. $sExternalKeyTable = $oJoinExpr->GetParent();
  3194. $sExternalKeyField = $oJoinExpr->GetName();
  3195. $sLeftIndex = $sExternalKeyField.'_left'; // TODO use GetSQLLeft()
  3196. $sRightIndex = $sExternalKeyField.'_right'; // TODO use GetSQLRight()
  3197. $LocalKeyLeft = $oKeyAttDef->GetSQLLeft();
  3198. $LocalKeyRight = $oKeyAttDef->GetSQLRight();
  3199. //echo "MAKEQUERY-LocalKeyLeft pour $sKeyAttCode => $LocalKeyLeft<br/>\n";
  3200. $oSelectBase->AddInnerJoinTree($oSelectExtKey, $LocalKeyLeft, $LocalKeyRight, $sLeftIndex, $sRightIndex, $sExternalKeyTable, $iOperatorCode);
  3201. }
  3202. }
  3203. }
  3204. }
  3205. // Translate the selected columns
  3206. //
  3207. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  3208. $oBuild->m_oQBExpressions->Translate($aTranslation, false);
  3209. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  3210. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  3211. return $oSelectBase;
  3212. }
  3213. /**
  3214. * Special processing for the hierarchical keys stored as nested sets
  3215. * @param $iId integer The identifier of the parent
  3216. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  3217. * @param $stable string The name of the database table containing the hierarchical key
  3218. */
  3219. public static function HKInsertChildUnder($iId, $oAttDef, $sTable)
  3220. {
  3221. // Get the parent id.right value
  3222. if ($iId == 0)
  3223. {
  3224. // No parent, insert completely at the right of the tree
  3225. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  3226. $aRes = CMDBSource::QueryToArray($sSQL);
  3227. if (count($aRes) == 0)
  3228. {
  3229. $iMyRight = 1;
  3230. }
  3231. else
  3232. {
  3233. $iMyRight = $aRes[0]['max']+1;
  3234. }
  3235. }
  3236. else
  3237. {
  3238. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".$iId;
  3239. $iMyRight = CMDBSource::QueryToScalar($sSQL);
  3240. $sSQLUpdateRight = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + 2 WHERE `".$oAttDef->GetSQLRight()."` >= $iMyRight";
  3241. CMDBSource::Query($sSQLUpdateRight);
  3242. $sSQLUpdateLeft = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + 2 WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  3243. CMDBSource::Query($sSQLUpdateLeft);
  3244. }
  3245. return array($oAttDef->GetSQLRight() => $iMyRight+1, $oAttDef->GetSQLLeft() => $iMyRight);
  3246. }
  3247. /**
  3248. * Special processing for the hierarchical keys stored as nested sets: temporary remove the branch
  3249. * @param $iId integer The identifier of the parent
  3250. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  3251. * @param $sTable string The name of the database table containing the hierarchical key
  3252. */
  3253. public static function HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable)
  3254. {
  3255. $iDelta = $iMyRight - $iMyLeft + 1;
  3256. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iMyLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iMyLeft - `".$oAttDef->GetSQLLeft();
  3257. $sSQL .= "` WHERE `".$oAttDef->GetSQLLeft()."`> $iMyLeft AND `".$oAttDef->GetSQLRight()."`< $iMyRight";
  3258. CMDBSource::Query($sSQL);
  3259. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` - $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  3260. CMDBSource::Query($sSQL);
  3261. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` - $iDelta WHERE `".$oAttDef->GetSQLRight()."` > $iMyRight";
  3262. CMDBSource::Query($sSQL);
  3263. }
  3264. /**
  3265. * Special processing for the hierarchical keys stored as nested sets: replug the temporary removed branch
  3266. * @param $iId integer The identifier of the parent
  3267. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  3268. * @param $sTable string The name of the database table containing the hierarchical key
  3269. */
  3270. public static function HKReplugBranch($iNewLeft, $iNewRight, $oAttDef, $sTable)
  3271. {
  3272. $iDelta = $iNewRight - $iNewLeft + 1;
  3273. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iNewLeft";
  3274. CMDBSource::Query($sSQL);
  3275. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + $iDelta WHERE `".$oAttDef->GetSQLRight()."` >= $iNewLeft";
  3276. CMDBSource::Query($sSQL);
  3277. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iNewLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iNewLeft - `".$oAttDef->GetSQLLeft()."` WHERE `".$oAttDef->GetSQLRight()."`< 0";
  3278. CMDBSource::Query($sSQL);
  3279. }
  3280. /**
  3281. * Check (and updates if needed) the hierarchical keys
  3282. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  3283. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  3284. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  3285. */
  3286. public static function CheckHKeys($bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  3287. {
  3288. $bChangeNeeded = false;
  3289. foreach (self::GetClasses() as $sClass)
  3290. {
  3291. if (!self::HasTable($sClass)) continue;
  3292. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3293. {
  3294. // Check (once) all the attributes that are hierarchical keys
  3295. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey())
  3296. {
  3297. if ($bVerbose)
  3298. {
  3299. echo "The attribute $sAttCode from $sClass is a hierarchical key.\n";
  3300. }
  3301. $bResult = self::HKInit($sClass, $sAttCode, $bDiagnosticsOnly, $bVerbose, $bForceComputation);
  3302. $bChangeNeeded |= $bResult;
  3303. if ($bVerbose && !$bResult)
  3304. {
  3305. echo "Ok, the attribute $sAttCode from class $sClass seems up to date.\n";
  3306. }
  3307. }
  3308. }
  3309. }
  3310. return $bChangeNeeded;
  3311. }
  3312. /**
  3313. * Initializes (i.e converts) a hierarchy stored using a 'parent_id' external key
  3314. * into a hierarchy stored with a HierarchicalKey, by initializing the _left and _right values
  3315. * to correspond to the existing hierarchy in the database
  3316. * @param $sClass string Name of the class to process
  3317. * @param $sAttCode string Code of the attribute to process
  3318. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  3319. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  3320. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  3321. * @return true if an update is needed (diagnostics only) / was performed
  3322. */
  3323. public static function HKInit($sClass, $sAttCode, $bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  3324. {
  3325. $idx = 1;
  3326. $bUpdateNeeded = $bForceComputation;
  3327. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  3328. $sTable = self::DBGetTable($sClass, $sAttCode);
  3329. if ($oAttDef->IsHierarchicalKey())
  3330. {
  3331. // Check if some values already exist in the table for the _right value, if so, do nothing
  3332. $sRight = $oAttDef->GetSQLRight();
  3333. $sSQL = "SELECT MAX(`$sRight`) AS MaxRight FROM `$sTable`";
  3334. $iMaxRight = CMDBSource::QueryToScalar($sSQL);
  3335. $sSQL = "SELECT COUNT(*) AS Count FROM `$sTable`"; // Note: COUNT(field) returns zero if the given field contains only NULLs
  3336. $iCount = CMDBSource::QueryToScalar($sSQL);
  3337. if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0))
  3338. {
  3339. $bUpdateNeeded = true;
  3340. if ($bVerbose)
  3341. {
  3342. echo "The table '$sTable' must be updated to compute the fields $sRight and ".$oAttDef->GetSQLLeft()."\n";
  3343. }
  3344. }
  3345. if ($bForceComputation && !$bDiagnosticsOnly)
  3346. {
  3347. echo "Rebuilding the fields $sRight and ".$oAttDef->GetSQLLeft()." from table '$sTable'...\n";
  3348. }
  3349. if ($bUpdateNeeded && !$bDiagnosticsOnly)
  3350. {
  3351. try
  3352. {
  3353. CMDBSource::Query('START TRANSACTION');
  3354. self::HKInitChildren($sTable, $sAttCode, $oAttDef, 0, $idx);
  3355. CMDBSource::Query('COMMIT');
  3356. if ($bVerbose)
  3357. {
  3358. echo "Ok, table '$sTable' successfully updated.\n";
  3359. }
  3360. }
  3361. catch(Exception $e)
  3362. {
  3363. CMDBSource::Query('ROLLBACK');
  3364. throw new Exception("An error occured (".$e->getMessage().") while initializing the hierarchy for ($sClass, $sAttCode). The database was not modified.");
  3365. }
  3366. }
  3367. }
  3368. return $bUpdateNeeded;
  3369. }
  3370. /**
  3371. * Recursive helper function called by HKInit
  3372. */
  3373. protected static function HKInitChildren($sTable, $sAttCode, $oAttDef, $iId, &$iCurrIndex)
  3374. {
  3375. $sSQL = "SELECT id FROM `$sTable` WHERE `$sAttCode` = $iId";
  3376. $aRes = CMDBSource::QueryToArray($sSQL);
  3377. $aTree = array();
  3378. $sLeft = $oAttDef->GetSQLLeft();
  3379. $sRight = $oAttDef->GetSQLRight();
  3380. foreach($aRes as $aValues)
  3381. {
  3382. $iChildId = $aValues['id'];
  3383. $iLeft = $iCurrIndex++;
  3384. $aChildren = self::HKInitChildren($sTable, $sAttCode, $oAttDef, $iChildId, $iCurrIndex);
  3385. $iRight = $iCurrIndex++;
  3386. $sSQL = "UPDATE `$sTable` SET `$sLeft` = $iLeft, `$sRight` = $iRight WHERE id= $iChildId";
  3387. CMDBSource::Query($sSQL);
  3388. }
  3389. }
  3390. public static function CheckDataSources($bDiagnostics, $bVerbose)
  3391. {
  3392. $sOQL = 'SELECT SynchroDataSource';
  3393. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  3394. $bFixNeeded = false;
  3395. if ($bVerbose && $oSet->Count() == 0)
  3396. {
  3397. echo "There are no Data Sources in the database.\n";
  3398. }
  3399. while($oSource = $oSet->Fetch())
  3400. {
  3401. if ($bVerbose)
  3402. {
  3403. echo "Checking Data Source '".$oSource->GetName()."'...\n";
  3404. $bFixNeeded = $bFixNeeded | $oSource->CheckDBConsistency($bDiagnostics, $bVerbose);
  3405. }
  3406. }
  3407. if (!$bFixNeeded && $bVerbose)
  3408. {
  3409. echo "Ok.\n";
  3410. }
  3411. return $bFixNeeded;
  3412. }
  3413. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  3414. {
  3415. if (!array_key_exists($sNewName, $aAliases))
  3416. {
  3417. $aAliases[$sNewName] = $sRealName;
  3418. return $sNewName;
  3419. }
  3420. for ($i = 1 ; $i < 100 ; $i++)
  3421. {
  3422. $sAnAlias = $sNewName.$i;
  3423. if (!array_key_exists($sAnAlias, $aAliases))
  3424. {
  3425. // Create that new alias
  3426. $aAliases[$sAnAlias] = $sRealName;
  3427. return $sAnAlias;
  3428. }
  3429. }
  3430. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  3431. }
  3432. public static function CheckDefinitions($bExitOnError = true)
  3433. {
  3434. if (count(self::GetClasses()) == 0)
  3435. {
  3436. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  3437. }
  3438. $aErrors = array();
  3439. $aSugFix = array();
  3440. foreach (self::GetClasses() as $sClass)
  3441. {
  3442. $sTable = self::DBGetTable($sClass);
  3443. $sTableLowercase = strtolower($sTable);
  3444. if ($sTableLowercase != $sTable)
  3445. {
  3446. $aErrors[$sClass][] = "Table name '".$sTable."' has upper case characters. You might encounter issues when moving your installation between Linux and Windows.";
  3447. $aSugFix[$sClass][] = "Use '$sTableLowercase' instead. Step 1: If already installed, then rename manually in the DB: RENAME TABLE `$sTable` TO `{$sTableLowercase}_tempname`, `{$sTableLowercase}_tempname` TO `$sTableLowercase`; Step 2: Rename the table in the datamodel and compile the application. Note: the MySQL statement provided in step 1 has been designed to be compatible with Windows or Linux.";
  3448. }
  3449. $aNameSpec = self::GetNameSpec($sClass);
  3450. foreach($aNameSpec[1] as $i => $sAttCode)
  3451. {
  3452. if(!self::IsValidAttCode($sClass, $sAttCode))
  3453. {
  3454. $aErrors[$sClass][] = "Unknown attribute code '".$sAttCode."' for the name definition";
  3455. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  3456. }
  3457. }
  3458. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  3459. {
  3460. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  3461. {
  3462. $aErrors[$sClass][] = "Unknown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  3463. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  3464. }
  3465. }
  3466. $bHasWritableAttribute = false;
  3467. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3468. {
  3469. // It makes no sense to check the attributes again and again in the subclasses
  3470. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3471. if ($oAttDef->IsExternalKey())
  3472. {
  3473. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  3474. {
  3475. $aErrors[$sClass][] = "Unknown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  3476. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  3477. }
  3478. }
  3479. elseif ($oAttDef->IsExternalField())
  3480. {
  3481. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  3482. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  3483. {
  3484. $aErrors[$sClass][] = "Unknown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  3485. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  3486. }
  3487. else
  3488. {
  3489. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  3490. $sTargetClass = $oKeyAttDef->GetTargetClass();
  3491. $sExtAttCode = $oAttDef->GetExtAttCode();
  3492. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  3493. {
  3494. $aErrors[$sClass][] = "Unknown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  3495. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  3496. }
  3497. }
  3498. }
  3499. else if ($oAttDef->IsLinkSet())
  3500. {
  3501. // Do nothing...
  3502. }
  3503. else if ($oAttDef instanceof AttributeStopWatch)
  3504. {
  3505. $aThresholds = $oAttDef->ListThresholds();
  3506. if (is_array($aThresholds))
  3507. {
  3508. foreach($aThresholds as $iPercent => $aDef)
  3509. {
  3510. if (array_key_exists('highlight', $aDef))
  3511. {
  3512. if(!array_key_exists('code', $aDef['highlight']))
  3513. {
  3514. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of the $iPercent% threshold in the attribute: '$sAttCode'.";
  3515. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this threshold.";
  3516. }
  3517. else
  3518. {
  3519. $aScale = self::GetHighlightScale($sClass);
  3520. if (!array_key_exists($aDef['highlight']['code'], $aScale))
  3521. {
  3522. $aErrors[$sClass][] = "'{$aDef['highlight']['code']}' is not a valid value for the 'code' element of the $iPercent% threshold in the attribute: '$sAttCode'.";
  3523. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  3524. }
  3525. }
  3526. }
  3527. }
  3528. }
  3529. }
  3530. else // standard attributes
  3531. {
  3532. // Check that the default values definition is a valid object!
  3533. $oValSetDef = $oAttDef->GetValuesDef();
  3534. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  3535. {
  3536. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  3537. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  3538. }
  3539. else
  3540. {
  3541. // Default value must be listed in the allowed values (if defined)
  3542. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  3543. if (!is_null($aAllowedValues))
  3544. {
  3545. $sDefaultValue = $oAttDef->GetDefaultValue();
  3546. if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues))
  3547. {
  3548. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  3549. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  3550. }
  3551. }
  3552. }
  3553. }
  3554. // Check dependencies
  3555. if ($oAttDef->IsWritable())
  3556. {
  3557. $bHasWritableAttribute = true;
  3558. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  3559. {
  3560. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  3561. {
  3562. $aErrors[$sClass][] = "Unknown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  3563. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  3564. }
  3565. }
  3566. }
  3567. }
  3568. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  3569. {
  3570. if (method_exists($oFilterDef, '__GetRefAttribute'))
  3571. {
  3572. $oAttDef = $oFilterDef->__GetRefAttribute();
  3573. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  3574. {
  3575. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  3576. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3577. }
  3578. }
  3579. }
  3580. // Lifecycle
  3581. //
  3582. $sStateAttCode = self::GetStateAttributeCode($sClass);
  3583. if (strlen($sStateAttCode) > 0)
  3584. {
  3585. // Lifecycle - check that the state attribute does exist as an attribute
  3586. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  3587. {
  3588. $aErrors[$sClass][] = "Unknown attribute code '".$sStateAttCode."' for the state definition";
  3589. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3590. }
  3591. else
  3592. {
  3593. // Lifecycle - check that there is a value set constraint on the state attribute
  3594. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  3595. $aStates = array_keys(self::EnumStates($sClass));
  3596. if (is_null($aAllowedValuesRaw))
  3597. {
  3598. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  3599. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  3600. }
  3601. else
  3602. {
  3603. $aAllowedValues = array_keys($aAllowedValuesRaw);
  3604. // Lifecycle - check the the state attribute allowed values are defined states
  3605. foreach($aAllowedValues as $sValue)
  3606. {
  3607. if (!in_array($sValue, $aStates))
  3608. {
  3609. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  3610. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  3611. }
  3612. }
  3613. // Lifecycle - check that defined states are allowed values
  3614. foreach($aStates as $sStateValue)
  3615. {
  3616. if (!in_array($sStateValue, $aAllowedValues))
  3617. {
  3618. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  3619. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  3620. }
  3621. }
  3622. }
  3623. // Lifecycle - check that the action handlers are defined
  3624. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  3625. {
  3626. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  3627. {
  3628. foreach ($aTransitionDef['actions'] as $actionHandler)
  3629. {
  3630. if (is_string($actionHandler))
  3631. {
  3632. if (!method_exists($sClass, $actionHandler))
  3633. {
  3634. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  3635. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  3636. }
  3637. }
  3638. else // if(is_array($actionHandler))
  3639. {
  3640. $sActionHandler = $actionHandler['verb'];
  3641. if (!method_exists($sClass, $sActionHandler))
  3642. {
  3643. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  3644. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(...){return true;}]";
  3645. }
  3646. }
  3647. }
  3648. }
  3649. if (array_key_exists('highlight', $aStateDef))
  3650. {
  3651. if(!array_key_exists('code', $aStateDef['highlight']))
  3652. {
  3653. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of state: '$sStateCode'.";
  3654. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this state.";
  3655. }
  3656. else
  3657. {
  3658. $aScale = self::GetHighlightScale($sClass);
  3659. if (!array_key_exists($aStateDef['highlight']['code'], $aScale))
  3660. {
  3661. $aErrors[$sClass][] = "'{$aStateDef['highlight']['code']}' is not a valid value for the 'code' element in the 'highlight' property of state: '$sStateCode'.";
  3662. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  3663. }
  3664. }
  3665. }
  3666. }
  3667. }
  3668. }
  3669. if ($bHasWritableAttribute)
  3670. {
  3671. if (!self::HasTable($sClass))
  3672. {
  3673. $aErrors[$sClass][] = "No table has been defined for this class";
  3674. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  3675. }
  3676. }
  3677. // ZList
  3678. //
  3679. foreach(self::EnumZLists() as $sListCode)
  3680. {
  3681. foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode)
  3682. {
  3683. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  3684. {
  3685. $aErrors[$sClass][] = "Unknown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  3686. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3687. }
  3688. }
  3689. }
  3690. // Check unicity of the SQL columns
  3691. //
  3692. if (self::HasTable($sClass))
  3693. {
  3694. $aTableColumns = array(); // array of column => attcode (the column is used by this attribute)
  3695. $aTableColumns[self::DBGetKey($sClass)] = 'id';
  3696. // Check that SQL columns are declared only once
  3697. //
  3698. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3699. {
  3700. // Skip this attribute if not originaly defined in this class
  3701. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3702. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  3703. {
  3704. if (array_key_exists($sField, $aTableColumns))
  3705. {
  3706. $aErrors[$sClass][] = "Column '$sField' declared for attribute $sAttCode, but already used for attribute ".$aTableColumns[$sField];
  3707. $aSugFix[$sClass][] = "Please find another name for the SQL column";
  3708. }
  3709. else
  3710. {
  3711. $aTableColumns[$sField] = $sAttCode;
  3712. }
  3713. }
  3714. }
  3715. }
  3716. } // foreach class
  3717. if (count($aErrors) > 0)
  3718. {
  3719. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3720. echo "<h3>Business model inconsistencies have been found</h3>\n";
  3721. // #@# later -> this is the responsibility of the caller to format the output
  3722. foreach ($aErrors as $sClass => $aMessages)
  3723. {
  3724. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  3725. echo "<ul class=\"treeview\">\n";
  3726. $i = 0;
  3727. foreach ($aMessages as $sMsg)
  3728. {
  3729. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  3730. $i++;
  3731. }
  3732. echo "</ul>\n";
  3733. }
  3734. if ($bExitOnError) echo "<p>Aborting...</p>\n";
  3735. echo "</div>\n";
  3736. if ($bExitOnError) exit;
  3737. }
  3738. }
  3739. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  3740. {
  3741. if (empty($sRepairUrl)) return;
  3742. // By design, some queries might be blank, we have to ignore them
  3743. $aCleanFixes = array();
  3744. foreach($aSQLFixes as $sSQLFix)
  3745. {
  3746. if (!empty($sSQLFix))
  3747. {
  3748. $aCleanFixes[] = $sSQLFix;
  3749. }
  3750. }
  3751. if (count($aCleanFixes) == 0) return;
  3752. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  3753. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes), ENT_QUOTES, 'UTF-8')."\">\n";
  3754. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  3755. echo "</form>\n";
  3756. }
  3757. public static function DBExists($bMustBeComplete = true)
  3758. {
  3759. // returns true if at least one table exists
  3760. //
  3761. if (!CMDBSource::IsDB(self::$m_sDBName))
  3762. {
  3763. return false;
  3764. }
  3765. CMDBSource::SelectDB(self::$m_sDBName);
  3766. $aFound = array();
  3767. $aMissing = array();
  3768. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3769. {
  3770. if (CMDBSource::IsTable($sTable))
  3771. {
  3772. $aFound[] = $sTable;
  3773. }
  3774. else
  3775. {
  3776. $aMissing[] = $sTable;
  3777. }
  3778. }
  3779. if (count($aFound) == 0)
  3780. {
  3781. // no expected table has been found
  3782. return false;
  3783. }
  3784. else
  3785. {
  3786. if (count($aMissing) == 0)
  3787. {
  3788. // the database is complete (still, could be some fields missing!)
  3789. return true;
  3790. }
  3791. else
  3792. {
  3793. // not all the tables, could be an older version
  3794. if ($bMustBeComplete)
  3795. {
  3796. return false;
  3797. }
  3798. else
  3799. {
  3800. return true;
  3801. }
  3802. }
  3803. }
  3804. }
  3805. public static function DBDrop()
  3806. {
  3807. $bDropEntireDB = true;
  3808. if (!empty(self::$m_sTablePrefix))
  3809. {
  3810. // Do drop only tables corresponding to the sub-database (table prefix)
  3811. // then possibly drop the DB itself (if no table remain)
  3812. foreach (CMDBSource::EnumTables() as $sTable)
  3813. {
  3814. // perform a case insensitive test because on Windows the table names become lowercase :-(
  3815. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  3816. {
  3817. CMDBSource::DropTable($sTable);
  3818. }
  3819. else
  3820. {
  3821. // There is at least one table which is out of the scope of the current application
  3822. $bDropEntireDB = false;
  3823. }
  3824. }
  3825. }
  3826. if ($bDropEntireDB)
  3827. {
  3828. CMDBSource::DropDB(self::$m_sDBName);
  3829. }
  3830. }
  3831. public static function DBCreate($aCallback = null)
  3832. {
  3833. // Note: we have to check if the DB does exist, because we may share the DB
  3834. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  3835. if (!CMDBSource::IsDB(self::$m_sDBName))
  3836. {
  3837. CMDBSource::CreateDB(self::$m_sDBName);
  3838. }
  3839. self::DBCreateTables($aCallback);
  3840. self::DBCreateViews();
  3841. }
  3842. protected static function DBCreateTables($aCallback = null)
  3843. {
  3844. list($aErrors, $aSugFix, $aCondensedQueries) = self::DBCheckFormat();
  3845. //$sSQL = implode('; ', $aCondensedQueries); Does not work - multiple queries not allowed
  3846. foreach($aCondensedQueries as $sQuery)
  3847. {
  3848. $fStart = microtime(true);
  3849. CMDBSource::CreateTable($sQuery);
  3850. $fDuration = microtime(true) - $fStart;
  3851. if ($aCallback != null)
  3852. {
  3853. call_user_func($aCallback, $sQuery, $fDuration);
  3854. }
  3855. }
  3856. }
  3857. protected static function DBCreateViews()
  3858. {
  3859. list($aErrors, $aSugFix) = self::DBCheckViews();
  3860. $aSQL = array();
  3861. foreach ($aSugFix as $sClass => $aTarget)
  3862. {
  3863. foreach ($aTarget as $aQueries)
  3864. {
  3865. foreach ($aQueries as $sQuery)
  3866. {
  3867. if (!empty($sQuery))
  3868. {
  3869. //$aSQL[] = $sQuery;
  3870. // forces a refresh of cached information
  3871. CMDBSource::CreateTable($sQuery);
  3872. }
  3873. }
  3874. }
  3875. }
  3876. }
  3877. public static function DBDump()
  3878. {
  3879. $aDataDump = array();
  3880. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3881. {
  3882. $aRows = CMDBSource::DumpTable($sTable);
  3883. $aDataDump[$sTable] = $aRows;
  3884. }
  3885. return $aDataDump;
  3886. }
  3887. /*
  3888. * Determines wether the target DB is frozen or not
  3889. */
  3890. public static function DBIsReadOnly()
  3891. {
  3892. // Improvement: check the mySQL variable -> Read-only
  3893. if (UserRights::IsAdministrator())
  3894. {
  3895. return (!self::DBHasAccess(ACCESS_ADMIN_WRITE));
  3896. }
  3897. else
  3898. {
  3899. return (!self::DBHasAccess(ACCESS_USER_WRITE));
  3900. }
  3901. }
  3902. public static function DBHasAccess($iRequested = ACCESS_FULL)
  3903. {
  3904. $iMode = self::$m_oConfig->Get('access_mode');
  3905. if (($iMode & $iRequested) == 0) return false;
  3906. return true;
  3907. }
  3908. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  3909. {
  3910. $sValue = Dict::S($sKey, 'x-no-nothing');
  3911. if ($sValue == 'x-no-nothing')
  3912. {
  3913. $bNotInDico = true;
  3914. $sValue = $sValueFromOldSystem;
  3915. if (strlen($sValue) == 0)
  3916. {
  3917. $sValue = $sDefaultValue;
  3918. }
  3919. }
  3920. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  3921. }
  3922. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  3923. {
  3924. $sRes = '';
  3925. $sRes .= "// Dictionnay conventions\n";
  3926. $sRes .= htmlentities("// Class:<class_name>\n", ENT_QUOTES, 'UTF-8');
  3927. $sRes .= htmlentities("// Class:<class_name>+\n", ENT_QUOTES, 'UTF-8');
  3928. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n", ENT_QUOTES, 'UTF-8');
  3929. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n", ENT_QUOTES, 'UTF-8');
  3930. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n", ENT_QUOTES, 'UTF-8');
  3931. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n", ENT_QUOTES, 'UTF-8');
  3932. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n", ENT_QUOTES, 'UTF-8');
  3933. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n", ENT_QUOTES, 'UTF-8');
  3934. $sRes .= "\n";
  3935. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  3936. // Need to invent the "module", to characterize the origins of a class
  3937. if (strlen($sModules) == 0)
  3938. {
  3939. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  3940. }
  3941. else
  3942. {
  3943. $aModules = explode(', ', $sModules);
  3944. }
  3945. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3946. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  3947. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3948. foreach ($aModules as $sCategory)
  3949. {
  3950. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3951. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  3952. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3953. $sRes .= "//\n";
  3954. $sRes .= "\n";
  3955. foreach (self::GetClasses($sCategory) as $sClass)
  3956. {
  3957. if (!self::HasTable($sClass)) continue;
  3958. $bNotInDico = false;
  3959. $sClassRes = "//\n";
  3960. $sClassRes .= "// Class: $sClass\n";
  3961. $sClassRes .= "//\n";
  3962. $sClassRes .= "\n";
  3963. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  3964. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  3965. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  3966. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  3967. {
  3968. // Skip this attribute if not originaly defined in this class
  3969. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3970. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  3971. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  3972. if ($oAttDef instanceof AttributeEnum)
  3973. {
  3974. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  3975. {
  3976. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  3977. {
  3978. if (array_key_exists('label', $aStateData))
  3979. {
  3980. $sValue = $aStateData['label'];
  3981. }
  3982. else
  3983. {
  3984. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  3985. }
  3986. if (array_key_exists('description', $aStateData))
  3987. {
  3988. $sValuePlus = $aStateData['description'];
  3989. }
  3990. else
  3991. {
  3992. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  3993. }
  3994. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  3995. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  3996. }
  3997. }
  3998. else
  3999. {
  4000. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  4001. {
  4002. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  4003. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  4004. }
  4005. }
  4006. }
  4007. }
  4008. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  4009. {
  4010. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  4011. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  4012. }
  4013. $sClassRes .= "));\n";
  4014. $sClassRes .= "\n";
  4015. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  4016. {
  4017. $sRes .= $sClassRes;
  4018. }
  4019. }
  4020. }
  4021. return $sRes;
  4022. }
  4023. public static function DBCheckFormat()
  4024. {
  4025. $aErrors = array();
  4026. $aSugFix = array();
  4027. // A new way of representing things to be done - quicker to execute !
  4028. $aCreateTable = array(); // array of <table> => <table options>
  4029. $aCreateTableItems = array(); // array of <table> => array of <create definition>
  4030. $aAlterTableItems = array(); // array of <table> => <alter specification>
  4031. foreach (self::GetClasses() as $sClass)
  4032. {
  4033. if (!self::HasTable($sClass)) continue;
  4034. // Check that the table exists
  4035. //
  4036. $sTable = self::DBGetTable($sClass);
  4037. $sKeyField = self::DBGetKey($sClass);
  4038. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  4039. $sKeyFieldDefinition = "`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  4040. if (!CMDBSource::IsTable($sTable))
  4041. {
  4042. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  4043. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` ($sKeyFieldDefinition) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  4044. $aCreateTable[$sTable] = "ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  4045. $aCreateTableItems[$sTable][$sKeyField] = $sKeyFieldDefinition;
  4046. }
  4047. // Check that the key field exists
  4048. //
  4049. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  4050. {
  4051. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  4052. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD $sKeyFieldDefinition";
  4053. if (!array_key_exists($sTable, $aCreateTable))
  4054. {
  4055. $aAlterTableItems[$sTable][$sKeyField] = "ADD $sKeyFieldDefinition";
  4056. }
  4057. }
  4058. else
  4059. {
  4060. // Check the key field properties
  4061. //
  4062. if (!CMDBSource::IsKey($sTable, $sKeyField))
  4063. {
  4064. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  4065. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  4066. if (!array_key_exists($sTable, $aCreateTable))
  4067. {
  4068. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  4069. }
  4070. }
  4071. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  4072. {
  4073. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  4074. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` $sKeyFieldDefinition";
  4075. if (!array_key_exists($sTable, $aCreateTable))
  4076. {
  4077. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  4078. }
  4079. }
  4080. }
  4081. // Check that any defined field exists
  4082. //
  4083. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  4084. $aTableInfo['Fields'][$sKeyField]['used'] = true;
  4085. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  4086. {
  4087. // Skip this attribute if not originaly defined in this class
  4088. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  4089. foreach($oAttDef->GetSQLColumns(true) as $sField => $sDBFieldSpec)
  4090. {
  4091. // Keep track of columns used by iTop
  4092. $aTableInfo['Fields'][$sField]['used'] = true;
  4093. $bIndexNeeded = $oAttDef->RequiresIndex();
  4094. $sFieldDefinition = "`$sField` $sDBFieldSpec";
  4095. if (!CMDBSource::IsField($sTable, $sField))
  4096. {
  4097. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  4098. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD $sFieldDefinition";
  4099. if ($bIndexNeeded)
  4100. {
  4101. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  4102. }
  4103. if (array_key_exists($sTable, $aCreateTable))
  4104. {
  4105. $aCreateTableItems[$sTable][$sField] = $sFieldDefinition;
  4106. if ($bIndexNeeded)
  4107. {
  4108. $aCreateTableItems[$sTable][] = "INDEX (`$sField`)";
  4109. }
  4110. }
  4111. else
  4112. {
  4113. $aAlterTableItems[$sTable][$sField] = "ADD $sFieldDefinition";
  4114. if ($bIndexNeeded)
  4115. {
  4116. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  4117. }
  4118. }
  4119. }
  4120. else
  4121. {
  4122. // The field already exists, does it have the relevant properties?
  4123. //
  4124. $bToBeChanged = false;
  4125. $sActualFieldSpec = CMDBSource::GetFieldSpec($sTable, $sField);
  4126. if (strcasecmp($sDBFieldSpec, $sActualFieldSpec) != 0)
  4127. {
  4128. $bToBeChanged = true;
  4129. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldSpec' while expecting '$sDBFieldSpec'";
  4130. }
  4131. if ($bToBeChanged)
  4132. {
  4133. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  4134. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  4135. }
  4136. // Create indexes (external keys only... so far)
  4137. //
  4138. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField, array($sField)))
  4139. {
  4140. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  4141. if (CMDBSource::HasIndex($sTable, $sField))
  4142. {
  4143. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` DROP INDEX `$sField`, ADD INDEX (`$sField`)";
  4144. $aAlterTableItems[$sTable][] = "DROP INDEX `$sField`";
  4145. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  4146. }
  4147. else
  4148. {
  4149. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  4150. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  4151. }
  4152. }
  4153. }
  4154. }
  4155. }
  4156. // Check indexes
  4157. foreach (self::DBGetIndexes($sClass) as $aColumns)
  4158. {
  4159. $sIndexId = implode('_', $aColumns);
  4160. if(!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns))
  4161. {
  4162. $sColumns = "`".implode("`, `", $aColumns)."`";
  4163. if (CMDBSource::HasIndex($sTable, $sIndexId))
  4164. {
  4165. $aErrors[$sClass]['*'][] = "Wrong index '$sIndexId' ($sColumns) in table '$sTable'";
  4166. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`, ADD INDEX `$sIndexId` ($sColumns)";
  4167. }
  4168. else
  4169. {
  4170. $aErrors[$sClass]['*'][] = "Missing index '$sIndexId' ($sColumns) in table '$sTable'";
  4171. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)";
  4172. }
  4173. if (array_key_exists($sTable, $aCreateTable))
  4174. {
  4175. $aCreateTableItems[$sTable][] = "INDEX `$sIndexId` ($sColumns)";
  4176. }
  4177. else
  4178. {
  4179. if (CMDBSource::HasIndex($sTable, $sIndexId))
  4180. {
  4181. $aAlterTableItems[$sTable][] = "DROP INDEX `$sIndexId`";
  4182. }
  4183. $aAlterTableItems[$sTable][] = "ADD INDEX `$sIndexId` ($sColumns)";
  4184. }
  4185. }
  4186. }
  4187. // Find out unused columns
  4188. //
  4189. foreach($aTableInfo['Fields'] as $sField => $aFieldData)
  4190. {
  4191. if (!isset($aFieldData['used']) || !$aFieldData['used'])
  4192. {
  4193. $aErrors[$sClass]['*'][] = "Column '$sField' in table '$sTable' is not used";
  4194. if (!CMDBSource::IsNullAllowed($sTable, $sField))
  4195. {
  4196. // Allow null values so that new record can be inserted
  4197. // without specifying the value of this unknown column
  4198. $sFieldDefinition = "`$sField` ".CMDBSource::GetFieldType($sTable, $sField).' NULL';
  4199. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  4200. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  4201. }
  4202. }
  4203. }
  4204. }
  4205. $aCondensedQueries = array();
  4206. foreach($aCreateTable as $sTable => $sTableOptions)
  4207. {
  4208. $sTableItems = implode(', ', $aCreateTableItems[$sTable]);
  4209. $aCondensedQueries[] = "CREATE TABLE `$sTable` ($sTableItems) $sTableOptions";
  4210. }
  4211. foreach($aAlterTableItems as $sTable => $aChangeList)
  4212. {
  4213. $sChangeList = implode(', ', $aChangeList);
  4214. $aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList";
  4215. }
  4216. return array($aErrors, $aSugFix, $aCondensedQueries);
  4217. }
  4218. public static function DBCheckViews()
  4219. {
  4220. $aErrors = array();
  4221. $aSugFix = array();
  4222. // Reporting views (must be created after any other table)
  4223. //
  4224. foreach (self::GetClasses('bizmodel') as $sClass)
  4225. {
  4226. $sView = self::DBGetView($sClass);
  4227. if (CMDBSource::IsTable($sView))
  4228. {
  4229. // Check that the view is complete
  4230. //
  4231. // Note: checking the list of attributes is not enough because the columns can be stable while the SELECT is not stable
  4232. // Example: new way to compute the friendly name
  4233. // The correct comparison algorithm is to compare the queries,
  4234. // by using "SHOW CREATE VIEW" (MySQL 5.0.1 required) or to look into INFORMATION_SCHEMA/views
  4235. // both requiring some privileges
  4236. // Decision: to simplify, let's consider the views as being wrong anytime
  4237. if (true)
  4238. {
  4239. // Rework the view
  4240. //
  4241. $oFilter = new DBObjectSearch($sClass, '');
  4242. $oFilter->AllowAllData();
  4243. $sSQL = self::MakeSelectQuery($oFilter);
  4244. $aErrors[$sClass]['*'][] = "Redeclare view '$sView' (systematic - to support an eventual change in the friendly name computation)";
  4245. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  4246. }
  4247. }
  4248. else
  4249. {
  4250. // Create the view
  4251. //
  4252. $oFilter = new DBObjectSearch($sClass, '');
  4253. $oFilter->AllowAllData();
  4254. $sSQL = self::MakeSelectQuery($oFilter);
  4255. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  4256. $aSugFix[$sClass]['*'][] = "DROP VIEW IF EXISTS `$sView`";
  4257. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  4258. }
  4259. }
  4260. return array($aErrors, $aSugFix);
  4261. }
  4262. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  4263. {
  4264. $sRootClass = self::GetRootClass($sClass);
  4265. $sTable = self::DBGetTable($sClass);
  4266. $sKeyField = self::DBGetKey($sClass);
  4267. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  4268. {
  4269. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  4270. }
  4271. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  4272. if (count($aWrongRecords) == 0) return;
  4273. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  4274. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  4275. foreach ($aWrongRecords as $iRecordId)
  4276. {
  4277. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  4278. {
  4279. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  4280. {
  4281. case 'Delete':
  4282. // Already planned for a deletion
  4283. // Let's concatenate the errors description together
  4284. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  4285. break;
  4286. case 'Update':
  4287. // Let's plan a deletion
  4288. break;
  4289. }
  4290. }
  4291. else
  4292. {
  4293. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  4294. }
  4295. if (!$bProcessingFriends)
  4296. {
  4297. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  4298. {
  4299. // Something new to be deleted...
  4300. $iNewDelCount++;
  4301. }
  4302. }
  4303. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  4304. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  4305. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  4306. $aPlannedDel[$sTable][] = $iRecordId;
  4307. }
  4308. // Now make sure that we would delete the records of the other tables for that class
  4309. //
  4310. if (!$bProcessingFriends)
  4311. {
  4312. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  4313. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  4314. {
  4315. $sFriendTable = self::DBGetTable($sFriendClass);
  4316. $sFriendKey = self::DBGetKey($sFriendClass);
  4317. // skip the current table
  4318. if ($sFriendTable == $sTable) continue;
  4319. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  4320. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  4321. }
  4322. }
  4323. }
  4324. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  4325. {
  4326. $sRootClass = self::GetRootClass($sClass);
  4327. $sTable = self::DBGetTable($sClass);
  4328. $sKeyField = self::DBGetKey($sClass);
  4329. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  4330. {
  4331. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  4332. }
  4333. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  4334. if (count($aWrongRecords) == 0) return;
  4335. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  4336. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  4337. foreach ($aWrongRecords as $iRecordId)
  4338. {
  4339. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  4340. {
  4341. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  4342. {
  4343. case 'Delete':
  4344. // No need to update, the record will be deleted!
  4345. break;
  4346. case 'Update':
  4347. // Already planned for an update
  4348. // Add this new update spec to the list
  4349. $bFoundSameSpec = false;
  4350. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  4351. {
  4352. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  4353. {
  4354. $bFoundSameSpec = true;
  4355. }
  4356. }
  4357. if (!$bFoundSameSpec)
  4358. {
  4359. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  4360. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  4361. }
  4362. break;
  4363. }
  4364. }
  4365. else
  4366. {
  4367. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  4368. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  4369. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  4370. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  4371. }
  4372. }
  4373. }
  4374. // returns the count of records found for deletion
  4375. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  4376. {
  4377. foreach (self::GetClasses() as $sClass)
  4378. {
  4379. if (!self::HasTable($sClass)) continue;
  4380. $sRootClass = self::GetRootClass($sClass);
  4381. $sTable = self::DBGetTable($sClass);
  4382. $sKeyField = self::DBGetKey($sClass);
  4383. if (!self::IsStandaloneClass($sClass))
  4384. {
  4385. if (self::IsRootClass($sClass))
  4386. {
  4387. // Check that the final class field contains the name of a class which inherited from the current class
  4388. //
  4389. $sFinalClassField = self::DBGetClassField($sClass);
  4390. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  4391. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  4392. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  4393. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4394. }
  4395. else
  4396. {
  4397. $sRootTable = self::DBGetTable($sRootClass);
  4398. $sRootKey = self::DBGetKey($sRootClass);
  4399. $sFinalClassField = self::DBGetClassField($sRootClass);
  4400. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  4401. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  4402. // Check that any record found here has its counterpart in the root table
  4403. // and which refers to a child class
  4404. //
  4405. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` as maintable LEFT JOIN `$sRootTable` ON maintable.`$sKeyField` = `$sRootTable`.`$sRootKey` AND `$sRootTable`.`$sFinalClassField` IN ($sExpectedClasses) WHERE `$sRootTable`.`$sRootKey` IS NULL";
  4406. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Found a record in `<em>$sTable</em>`, but no counterpart in root table `<em>$sRootTable</em>` (inc. records pointing to a class in {".$sExpectedClasses."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4407. // Check that any record found in the root table and referring to a child class
  4408. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  4409. //
  4410. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sRootKey` AS id FROM `$sRootTable` AS maintable LEFT JOIN `$sTable` ON maintable.`$sRootKey` = `$sTable`.`$sKeyField` WHERE `$sTable`.`$sKeyField` IS NULL AND maintable.`$sFinalClassField` IN ($sExpectedClasses)";
  4411. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Found a record in root table `<em>$sRootTable</em>`, but no counterpart in table `<em>$sTable</em>` (root records pointing to a class in {".$sExpectedClasses."})", $sRootClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4412. }
  4413. }
  4414. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  4415. {
  4416. // Skip this attribute if not defined in this table
  4417. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  4418. if ($oAttDef->IsExternalKey())
  4419. {
  4420. // Check that any external field is pointing to an existing object
  4421. //
  4422. $sRemoteClass = $oAttDef->GetTargetClass();
  4423. $sRemoteTable = self::DBGetTable($sRemoteClass);
  4424. $sRemoteKey = self::DBGetKey($sRemoteClass);
  4425. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  4426. $sExtKeyField = current($aCols); // get the first column for an external key
  4427. // Note: a class/table may have an external key on itself
  4428. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  4429. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  4430. if ($oAttDef->IsNullAllowed())
  4431. {
  4432. // Exclude the records pointing to 0/null from the errors
  4433. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  4434. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  4435. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4436. }
  4437. else
  4438. {
  4439. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4440. }
  4441. // Do almost the same, taking into account the records planned for deletion
  4442. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  4443. {
  4444. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  4445. // but in that case you won't be able to track the root cause (cascading)
  4446. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  4447. if ($oAttDef->IsNullAllowed())
  4448. {
  4449. // Exclude the records pointing to 0/null from the errors
  4450. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  4451. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  4452. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4453. }
  4454. else
  4455. {
  4456. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4457. }
  4458. }
  4459. }
  4460. else if ($oAttDef->IsDirectField())
  4461. {
  4462. // Check that the values fit the allowed values
  4463. //
  4464. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  4465. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  4466. {
  4467. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  4468. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  4469. $sMyAttributeField = current($aCols); // get the first column for the moment
  4470. $sDefaultValue = $oAttDef->GetDefaultValue();
  4471. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  4472. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4473. }
  4474. }
  4475. }
  4476. }
  4477. }
  4478. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  4479. {
  4480. // Records in error, and action to be taken: delete or update
  4481. // by RootClass/Table/Record
  4482. $aErrorsAndFixes = array();
  4483. // Records to be ignored in the current/next pass
  4484. // by Table = array of RecordId
  4485. $aPlannedDel = array();
  4486. // Count of errors in the next pass: no error means that we can leave...
  4487. $iErrorCount = 0;
  4488. // Limit in case of a bug in the algorythm
  4489. $iLoopCount = 0;
  4490. $iNewDelCount = 1; // startup...
  4491. while ($iNewDelCount > 0)
  4492. {
  4493. $iNewDelCount = 0;
  4494. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4495. $iErrorCount += $iNewDelCount;
  4496. // Safety net #1 - limit the planned deletions
  4497. //
  4498. $iMaxDel = 1000;
  4499. $iPlannedDel = 0;
  4500. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  4501. {
  4502. $iPlannedDel += count($aPlannedDelOnTable);
  4503. }
  4504. if ($iPlannedDel > $iMaxDel)
  4505. {
  4506. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  4507. break;
  4508. }
  4509. // Safety net #2 - limit the iterations
  4510. //
  4511. $iLoopCount++;
  4512. $iMaxLoops = 10;
  4513. if ($iLoopCount > $iMaxLoops)
  4514. {
  4515. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  4516. break;
  4517. }
  4518. }
  4519. // Display the results
  4520. //
  4521. $iIssueCount = 0;
  4522. $aFixesDelete = array();
  4523. $aFixesUpdate = array();
  4524. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  4525. {
  4526. foreach ($aTables as $sTable => $aRecords)
  4527. {
  4528. foreach ($aRecords as $iRecord => $aError)
  4529. {
  4530. $sAction = $aError['Action'];
  4531. $sReason = $aError['Reason'];
  4532. $iPass = $aError['Pass'];
  4533. switch ($sAction)
  4534. {
  4535. case 'Delete':
  4536. $sActionDetails = "";
  4537. $aFixesDelete[$sTable][] = $iRecord;
  4538. break;
  4539. case 'Update':
  4540. $aUpdateDesc = array();
  4541. foreach($aError['Action_Details'] as $aUpdateSpec)
  4542. {
  4543. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  4544. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  4545. }
  4546. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  4547. break;
  4548. default:
  4549. $sActionDetails = "bug: unknown action '$sAction'";
  4550. }
  4551. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  4552. $iIssueCount++;
  4553. }
  4554. }
  4555. }
  4556. if ($iIssueCount > 0)
  4557. {
  4558. // Build the queries to fix in the database
  4559. //
  4560. // First step, be able to get class data out of the table name
  4561. // Could be optimized, because we've made the job earlier... but few benefits, so...
  4562. $aTable2ClassProp = array();
  4563. foreach (self::GetClasses() as $sClass)
  4564. {
  4565. if (!self::HasTable($sClass)) continue;
  4566. $sRootClass = self::GetRootClass($sClass);
  4567. $sTable = self::DBGetTable($sClass);
  4568. $sKeyField = self::DBGetKey($sClass);
  4569. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  4570. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  4571. }
  4572. // Second step, build a flat list of SQL queries
  4573. $aSQLFixes = array();
  4574. $iPlannedUpdate = 0;
  4575. foreach ($aFixesUpdate as $sTable => $aColumns)
  4576. {
  4577. foreach ($aColumns as $sColumn => $aNewValues)
  4578. {
  4579. foreach ($aNewValues as $sNewValue => $aRecords)
  4580. {
  4581. $iPlannedUpdate += count($aRecords);
  4582. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  4583. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  4584. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  4585. }
  4586. }
  4587. }
  4588. $iPlannedDel = 0;
  4589. foreach ($aFixesDelete as $sTable => $aRecords)
  4590. {
  4591. $iPlannedDel += count($aRecords);
  4592. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  4593. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  4594. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  4595. }
  4596. // Report the results
  4597. //
  4598. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  4599. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  4600. // #@# later -> this is the responsibility of the caller to format the output
  4601. echo "<ul class=\"treeview\">\n";
  4602. foreach ($aIssues as $sIssueDesc)
  4603. {
  4604. echo "<li>$sIssueDesc</li>\n";
  4605. }
  4606. echo "</ul>\n";
  4607. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  4608. echo "<p>Aborting...</p>\n";
  4609. echo "</div>\n";
  4610. exit;
  4611. }
  4612. }
  4613. public static function Startup($config, $bModelOnly = false, $bAllowCache = true, $bTraceSourceFiles = false)
  4614. {
  4615. if (!defined('MODULESROOT'))
  4616. {
  4617. define('MODULESROOT', APPROOT.'env-'.utils::GetCurrentEnvironment().'/');
  4618. self::$m_bTraceSourceFiles = $bTraceSourceFiles;
  4619. // $config can be either a filename, or a Configuration object (volatile!)
  4620. if ($config instanceof Config)
  4621. {
  4622. self::LoadConfig($config, $bAllowCache);
  4623. }
  4624. else
  4625. {
  4626. self::LoadConfig(new Config($config), $bAllowCache);
  4627. }
  4628. if ($bModelOnly) return;
  4629. }
  4630. CMDBSource::SelectDB(self::$m_sDBName);
  4631. foreach(get_declared_classes() as $sPHPClass)
  4632. {
  4633. if (is_subclass_of($sPHPClass, 'ModuleHandlerAPI'))
  4634. {
  4635. $aCallSpec = array($sPHPClass, 'OnMetaModelStarted');
  4636. call_user_func_array($aCallSpec, array());
  4637. }
  4638. }
  4639. if (false)
  4640. {
  4641. echo "Debug<br/>\n";
  4642. self::static_var_dump();
  4643. }
  4644. }
  4645. public static function LoadConfig($oConfiguration, $bAllowCache = false)
  4646. {
  4647. self::$m_oConfig = $oConfiguration;
  4648. // Set log ASAP
  4649. if (self::$m_oConfig->GetLogGlobal())
  4650. {
  4651. if (self::$m_oConfig->GetLogIssue())
  4652. {
  4653. self::$m_bLogIssue = true;
  4654. IssueLog::Enable(APPROOT.'log/error.log');
  4655. }
  4656. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  4657. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  4658. ToolsLog::Enable(APPROOT.'log/tools.log');
  4659. }
  4660. else
  4661. {
  4662. self::$m_bLogIssue = false;
  4663. self::$m_bLogNotification = false;
  4664. self::$m_bLogWebService = false;
  4665. }
  4666. ExecutionKPI::EnableDuration(self::$m_oConfig->Get('log_kpi_duration'));
  4667. ExecutionKPI::EnableMemory(self::$m_oConfig->Get('log_kpi_memory'));
  4668. ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id'));
  4669. self::$m_bTraceQueries = self::$m_oConfig->GetLogQueries();
  4670. self::$m_bIndentQueries = self::$m_oConfig->Get('query_indentation_enabled');
  4671. self::$m_bQueryCacheEnabled = self::$m_oConfig->GetQueryCacheEnabled();
  4672. self::$m_bOptimizeQueries = self::$m_oConfig->Get('query_optimization_enabled');
  4673. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  4674. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  4675. self::$m_bUseAPCCache = $bAllowCache
  4676. && self::$m_oConfig->Get('apc_cache.enabled')
  4677. && function_exists('apc_fetch')
  4678. && function_exists('apc_store');
  4679. self::$m_iQueryCacheTTL = self::$m_oConfig->Get('apc_cache.query_ttl');
  4680. // PHP timezone first...
  4681. //
  4682. $sPHPTimezone = self::$m_oConfig->Get('timezone');
  4683. if ($sPHPTimezone == '')
  4684. {
  4685. // Leave as is... up to the admin to set a value somewhere...
  4686. //$sPHPTimezone = date_default_timezone_get();
  4687. }
  4688. else
  4689. {
  4690. date_default_timezone_set($sPHPTimezone);
  4691. }
  4692. // Note: load the dictionary as soon as possible, because it might be
  4693. // needed when some error occur
  4694. $sAppIdentity = 'itop-'.MetaModel::GetEnvironmentId();
  4695. $bDictInitializedFromData = false;
  4696. if (!self::$m_bUseAPCCache || !Dict::InCache($sAppIdentity))
  4697. {
  4698. $bDictInitializedFromData = true;
  4699. foreach (self::$m_oConfig->GetDictionaries() as $sModule => $sToInclude)
  4700. {
  4701. self::IncludeModule('dictionaries', $sToInclude);
  4702. }
  4703. }
  4704. // Set the language... after the dictionaries have been loaded!
  4705. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  4706. // Romain: this is the only way I've found to cope with the fact that
  4707. // classes have to be derived from cmdbabstract (to be editable in the UI)
  4708. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  4709. foreach (self::$m_oConfig->GetAppModules() as $sModule => $sToInclude)
  4710. {
  4711. self::IncludeModule('application', $sToInclude);
  4712. }
  4713. foreach (self::$m_oConfig->GetDataModels() as $sModule => $sToInclude)
  4714. {
  4715. self::IncludeModule('business', $sToInclude);
  4716. }
  4717. foreach (self::$m_oConfig->GetWebServiceCategories() as $sModule => $sToInclude)
  4718. {
  4719. self::IncludeModule('webservice', $sToInclude);
  4720. }
  4721. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  4722. {
  4723. self::IncludeModule('addons', $sToInclude);
  4724. }
  4725. $sServer = self::$m_oConfig->GetDBHost();
  4726. $sUser = self::$m_oConfig->GetDBUser();
  4727. $sPwd = self::$m_oConfig->GetDBPwd();
  4728. $sSource = self::$m_oConfig->GetDBName();
  4729. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  4730. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  4731. $sCollation = self::$m_oConfig->GetDBCollation();
  4732. if (self::$m_bUseAPCCache)
  4733. {
  4734. $oKPI = new ExecutionKPI();
  4735. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  4736. //
  4737. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-metamodel';
  4738. $result = apc_fetch($sOqlAPCCacheId);
  4739. if (is_array($result))
  4740. {
  4741. // todo - verifier que toutes les classes mentionnees ici sont chargees dans InitClasses()
  4742. self::$m_aExtensionClasses = $result['m_aExtensionClasses'];
  4743. self::$m_Category2Class = $result['m_Category2Class'];
  4744. self::$m_aRootClasses = $result['m_aRootClasses'];
  4745. self::$m_aParentClasses = $result['m_aParentClasses'];
  4746. self::$m_aChildClasses = $result['m_aChildClasses'];
  4747. self::$m_aClassParams = $result['m_aClassParams'];
  4748. self::$m_aAttribDefs = $result['m_aAttribDefs'];
  4749. self::$m_aAttribOrigins = $result['m_aAttribOrigins'];
  4750. self::$m_aExtKeyFriends = $result['m_aExtKeyFriends'];
  4751. self::$m_aIgnoredAttributes = $result['m_aIgnoredAttributes'];
  4752. self::$m_aFilterDefs = $result['m_aFilterDefs'];
  4753. self::$m_aFilterOrigins = $result['m_aFilterOrigins'];
  4754. self::$m_aListInfos = $result['m_aListInfos'];
  4755. self::$m_aListData = $result['m_aListData'];
  4756. self::$m_aRelationInfos = $result['m_aRelationInfos'];
  4757. self::$m_aStates = $result['m_aStates'];
  4758. self::$m_aStimuli = $result['m_aStimuli'];
  4759. self::$m_aTransitions = $result['m_aTransitions'];
  4760. self::$m_aHighlightScales = $result['m_aHighlightScales'];
  4761. }
  4762. $oKPI->ComputeAndReport('Metamodel APC (fetch + read)');
  4763. }
  4764. if (count(self::$m_aAttribDefs) == 0)
  4765. {
  4766. // The includes have been included, let's browse the existing classes and
  4767. // develop some data based on the proposed model
  4768. $oKPI = new ExecutionKPI();
  4769. self::InitClasses($sTablePrefix);
  4770. $oKPI->ComputeAndReport('Initialization of Data model structures');
  4771. if (self::$m_bUseAPCCache)
  4772. {
  4773. $oKPI = new ExecutionKPI();
  4774. $aCache = array();
  4775. $aCache['m_aExtensionClasses'] = self::$m_aExtensionClasses;
  4776. $aCache['m_Category2Class'] = self::$m_Category2Class;
  4777. $aCache['m_aRootClasses'] = self::$m_aRootClasses; // array of "classname" => "rootclass"
  4778. $aCache['m_aParentClasses'] = self::$m_aParentClasses; // array of ("classname" => array of "parentclass")
  4779. $aCache['m_aChildClasses'] = self::$m_aChildClasses; // array of ("classname" => array of "childclass")
  4780. $aCache['m_aClassParams'] = self::$m_aClassParams; // array of ("classname" => array of class information)
  4781. $aCache['m_aAttribDefs'] = self::$m_aAttribDefs; // array of ("classname" => array of attributes)
  4782. $aCache['m_aAttribOrigins'] = self::$m_aAttribOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4783. $aCache['m_aExtKeyFriends'] = self::$m_aExtKeyFriends; // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  4784. $aCache['m_aIgnoredAttributes'] = self::$m_aIgnoredAttributes; //array of ("classname" => array of ("attcode")
  4785. $aCache['m_aFilterDefs'] = self::$m_aFilterDefs; // array of ("classname" => array filterdef)
  4786. $aCache['m_aFilterOrigins'] = self::$m_aFilterOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4787. $aCache['m_aListInfos'] = self::$m_aListInfos; // array of ("listcode" => various info on the list, common to every classes)
  4788. $aCache['m_aListData'] = self::$m_aListData; // array of ("classname" => array of "listcode" => list)
  4789. $aCache['m_aRelationInfos'] = self::$m_aRelationInfos; // array of ("relcode" => various info on the list, common to every classes)
  4790. $aCache['m_aStates'] = self::$m_aStates; // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  4791. $aCache['m_aStimuli'] = self::$m_aStimuli; // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  4792. $aCache['m_aTransitions'] = self::$m_aTransitions; // array of ("classname" => array of ("statcode_from"=>array of ("stimuluscode" => array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD)))
  4793. $aCache['m_aHighlightScales'] = self::$m_aHighlightScales; // array of ("classname" => array of higlightcodes)))
  4794. apc_store($sOqlAPCCacheId, $aCache);
  4795. $oKPI->ComputeAndReport('Metamodel APC (store)');
  4796. }
  4797. }
  4798. if (self::$m_bUseAPCCache && $bDictInitializedFromData)
  4799. {
  4800. Dict::InitCache($sAppIdentity);
  4801. }
  4802. self::$m_sDBName = $sSource;
  4803. self::$m_sTablePrefix = $sTablePrefix;
  4804. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  4805. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  4806. // Later when timezone implementation is correctly done: CMDBSource::SetTimezone($sDBTimezone);
  4807. }
  4808. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  4809. {
  4810. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  4811. }
  4812. public static function GetModuleParameter($sModule, $sProperty, $defaultvalue = null)
  4813. {
  4814. $value = $defaultvalue;
  4815. if (!array_key_exists($sModule, self::$m_aModulesParameters))
  4816. {
  4817. }
  4818. if (!self::$m_aModulesParameters[$sModule] == null)
  4819. {
  4820. $value = self::$m_aModulesParameters[$sModule]->Get($sProperty, $defaultvalue);
  4821. }
  4822. return $value;
  4823. }
  4824. public static function GetConfig()
  4825. {
  4826. return self::$m_oConfig;
  4827. }
  4828. public static function GetEnvironmentId()
  4829. {
  4830. return md5(APPROOT).'-'.utils::GetCurrentEnvironment();
  4831. }
  4832. protected static $m_aExtensionClasses = array();
  4833. protected static function IncludeModule($sModuleType, $sToInclude)
  4834. {
  4835. $sFirstChar = substr($sToInclude, 0, 1);
  4836. $sSecondChar = substr($sToInclude, 1, 1);
  4837. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  4838. {
  4839. // It is a relative path, prepend APPROOT
  4840. if (substr($sToInclude, 0, 3) == '../')
  4841. {
  4842. // Preserve compatibility with config files written before 1.0.1
  4843. // Replace '../' by '<root>/'
  4844. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  4845. }
  4846. else
  4847. {
  4848. $sFile = APPROOT.'/'.$sToInclude;
  4849. }
  4850. }
  4851. else
  4852. {
  4853. // Leave as is - should be an absolute path
  4854. $sFile = $sToInclude;
  4855. }
  4856. if (!file_exists($sFile))
  4857. {
  4858. $sConfigFile = self::$m_oConfig->GetLoadedFile();
  4859. if (strlen($sConfigFile) > 0)
  4860. {
  4861. throw new CoreException('Include: wrong file name in configuration file', array('config file' => $sConfigFile, 'section' => $sModuleType, 'filename' => $sFile));
  4862. }
  4863. else
  4864. {
  4865. // The configuration is in memory only
  4866. throw new CoreException('Include: wrong file name in configuration file (in memory)', array('section' => $sModuleType, 'filename' => $sFile));
  4867. }
  4868. }
  4869. // Note: We do not expect the modules to output characters while loading them.
  4870. // Therefore, and because unexpected characters can corrupt the output,
  4871. // they must be trashed here.
  4872. // Additionnaly, pages aiming at delivering data in their output can call WebPage::TrashUnexpectedOutput()
  4873. // to get rid of chars that could be generated during the execution of the code
  4874. ob_start();
  4875. require_once($sFile);
  4876. $sPreviousContent = ob_get_clean();
  4877. if (self::$m_oConfig->Get('debug_report_spurious_chars'))
  4878. {
  4879. if ($sPreviousContent != '')
  4880. {
  4881. IssueLog::Error("Spurious characters injected by $sModuleType/$sToInclude");
  4882. }
  4883. }
  4884. }
  4885. // Building an object
  4886. //
  4887. //
  4888. private static $aQueryCacheGetObject = array();
  4889. private static $aQueryCacheGetObjectHits = array();
  4890. public static function GetQueryCacheStatus()
  4891. {
  4892. $aRes = array();
  4893. $iTotalHits = 0;
  4894. foreach(self::$aQueryCacheGetObjectHits as $sClassSign => $iHits)
  4895. {
  4896. $aRes[] = "$sClassSign: $iHits";
  4897. $iTotalHits += $iHits;
  4898. }
  4899. return $iTotalHits.' ('.implode(', ', $aRes).')';
  4900. }
  4901. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4902. {
  4903. // Build the query cache signature
  4904. //
  4905. $sQuerySign = $sClass;
  4906. if($bAllowAllData)
  4907. {
  4908. $sQuerySign .= '_all_';
  4909. }
  4910. if (count($aModifierProperties))
  4911. {
  4912. array_multisort($aModifierProperties);
  4913. $sModifierProperties = json_encode($aModifierProperties);
  4914. $sQuerySign .= '_all_'.md5($sModifierProperties);
  4915. }
  4916. if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject))
  4917. {
  4918. // NOTE: Quick and VERY dirty caching mechanism which relies on
  4919. // the fact that the string '987654321' will never appear in the
  4920. // standard query
  4921. // This could be simplified a little, relying solely on the query cache,
  4922. // but this would slow down -by how much time?- the application
  4923. $oFilter = new DBObjectSearch($sClass);
  4924. $oFilter->AddCondition('id', 987654321, '=');
  4925. if ($aModifierProperties)
  4926. {
  4927. foreach ($aModifierProperties as $sPluginClass => $aProperties)
  4928. {
  4929. foreach ($aProperties as $sProperty => $value)
  4930. {
  4931. $oFilter->SetModifierProperty($sPluginClass, $sProperty, $value);
  4932. }
  4933. }
  4934. }
  4935. if ($bAllowAllData)
  4936. {
  4937. $oFilter->AllowAllData();
  4938. }
  4939. $sSQL = self::MakeSelectQuery($oFilter);
  4940. self::$aQueryCacheGetObject[$sQuerySign] = $sSQL;
  4941. self::$aQueryCacheGetObjectHits[$sQuerySign] = 0;
  4942. }
  4943. else
  4944. {
  4945. $sSQL = self::$aQueryCacheGetObject[$sQuerySign];
  4946. self::$aQueryCacheGetObjectHits[$sQuerySign] += 1;
  4947. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sQuerySign]."<br/>\n";
  4948. }
  4949. $sSQL = str_replace(CMDBSource::Quote(987654321), CMDBSource::Quote($iKey), $sSQL);
  4950. $res = CMDBSource::Query($sSQL);
  4951. $aRow = CMDBSource::FetchArray($res);
  4952. CMDBSource::FreeResult($res);
  4953. if ($bMustBeFound && empty($aRow))
  4954. {
  4955. throw new CoreException("No result for the single row query: '$sSQL'");
  4956. }
  4957. return $aRow;
  4958. }
  4959. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  4960. {
  4961. self::_check_subclass($sClass);
  4962. if (strlen($sClassAlias) == 0)
  4963. {
  4964. $sClassAlias = $sClass;
  4965. }
  4966. // Compound objects: if available, get the final object class
  4967. //
  4968. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  4969. {
  4970. // Either this is a bug (forgot to specify a root class with a finalclass field
  4971. // Or this is the expected behavior, because the object is not made of several tables
  4972. }
  4973. elseif (empty($aRow[$sClassAlias."finalclass"]))
  4974. {
  4975. // The data is missing in the DB
  4976. // @#@ possible improvement: check that the class is valid !
  4977. $sRootClass = self::GetRootClass($sClass);
  4978. $sFinalClassField = self::DBGetClassField($sRootClass);
  4979. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  4980. }
  4981. else
  4982. {
  4983. // do the job for the real target class
  4984. $sClass = $aRow[$sClassAlias."finalclass"];
  4985. }
  4986. return new $sClass($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  4987. }
  4988. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4989. {
  4990. self::_check_subclass($sClass);
  4991. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
  4992. if (empty($aRow))
  4993. {
  4994. return null;
  4995. }
  4996. return self::GetObjectByRow($sClass, $aRow);
  4997. }
  4998. public static function GetObjectByName($sClass, $sName, $bMustBeFound = true)
  4999. {
  5000. self::_check_subclass($sClass);
  5001. $oObjSearch = new DBObjectSearch($sClass);
  5002. $oObjSearch->AddNameCondition($sName);
  5003. $oSet = new DBObjectSet($oObjSearch);
  5004. if ($oSet->Count() != 1)
  5005. {
  5006. if ($bMustBeFound) throw new CoreException('Failed to get an object by its name', array('class'=>$sClass, 'name'=>$sName));
  5007. return null;
  5008. }
  5009. $oObj = $oSet->fetch();
  5010. return $oObj;
  5011. }
  5012. static protected $m_aCacheObjectByColumn = array();
  5013. public static function GetObjectByColumn($sClass, $sAttCode, $value, $bMustBeFoundUnique = true)
  5014. {
  5015. if (!isset(self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value]))
  5016. {
  5017. self::_check_subclass($sClass);
  5018. $oObjSearch = new DBObjectSearch($sClass);
  5019. $oObjSearch->AddCondition($sAttCode, $value, '=');
  5020. $oSet = new DBObjectSet($oObjSearch);
  5021. if ($oSet->Count() == 1)
  5022. {
  5023. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch();
  5024. }
  5025. else
  5026. {
  5027. if ($bMustBeFoundUnique) throw new CoreException('Failed to get an object by column', array('class'=>$sClass, 'attcode'=>$sAttCode, 'value'=>$value, 'matches' => $oSet->Count()));
  5028. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null;
  5029. }
  5030. }
  5031. return self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value];
  5032. }
  5033. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  5034. {
  5035. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  5036. if ($bAllowAllData)
  5037. {
  5038. $oFilter->AllowAllData();
  5039. }
  5040. $oSet = new DBObjectSet($oFilter);
  5041. $oObject = $oSet->Fetch();
  5042. return $oObject;
  5043. }
  5044. public static function GetHyperLink($sTargetClass, $iKey)
  5045. {
  5046. if ($iKey < 0)
  5047. {
  5048. return "$sTargetClass: $iKey (invalid value)";
  5049. }
  5050. $oObj = self::GetObject($sTargetClass, $iKey, false);
  5051. if (is_null($oObj))
  5052. {
  5053. // Whatever we are looking for, the root class is the key to search for
  5054. $sRootClass = self::GetRootClass($sTargetClass);
  5055. $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', array('objclass' => $sRootClass, 'objkey' => $iKey));
  5056. $oSet = new DBObjectSet($oSearch);
  5057. $oRecord = $oSet->Fetch();
  5058. // An empty fname is obtained with iTop < 2.0
  5059. if (is_null($oRecord) || (strlen(trim($oRecord->Get('fname'))) == 0))
  5060. {
  5061. $sName = Dict::Format('Core:UnknownObjectLabel', $sTargetClass, $iKey);
  5062. $sTitle = Dict::S('Core:UnknownObjectTip');
  5063. }
  5064. else
  5065. {
  5066. $sName = $oRecord->Get('fname');
  5067. $sTitle = Dict::Format('Core:DeletedObjectTip', $oRecord->Get('date'), $oRecord->Get('userinfo'));
  5068. }
  5069. return '<span class="itop-deleted-object" title="'.htmlentities($sTitle, ENT_QUOTES, 'UTF-8').'">'.htmlentities($sName, ENT_QUOTES, 'UTF-8').'</span>';
  5070. }
  5071. return $oObj->GetHyperLink();
  5072. }
  5073. public static function NewObject($sClass)
  5074. {
  5075. self::_check_subclass($sClass);
  5076. return new $sClass();
  5077. }
  5078. public static function GetNextKey($sClass)
  5079. {
  5080. $sRootClass = MetaModel::GetRootClass($sClass);
  5081. $sRootTable = MetaModel::DBGetTable($sRootClass);
  5082. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  5083. return $iNextKey;
  5084. }
  5085. /**
  5086. * Deletion of records, bypassing DBObject::DBDelete !!!
  5087. * It is NOT recommended to use this shortcut
  5088. * In particular, it will not work
  5089. * - if the class is not a final class
  5090. * - if the class has a hierarchical key (need to rebuild the indexes)
  5091. * - if the class overload DBDelete !
  5092. * Todo: protect it against forbidden usages (in such a case, delete objects one by one)
  5093. */
  5094. public static function BulkDelete(DBObjectSearch $oFilter)
  5095. {
  5096. $sSQL = self::MakeDeleteQuery($oFilter);
  5097. if (!self::DBIsReadOnly())
  5098. {
  5099. CMDBSource::Query($sSQL);
  5100. }
  5101. }
  5102. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  5103. {
  5104. // $aValues is an array of $sAttCode => $value
  5105. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  5106. if (!self::DBIsReadOnly())
  5107. {
  5108. CMDBSource::Query($sSQL);
  5109. }
  5110. }
  5111. /**
  5112. * Helper to remove selected objects without calling any handler
  5113. * Surpasses BulkDelete as it can handle abstract classes, but has the other limitation as it bypasses standard objects handlers
  5114. *
  5115. * @param string $oFilter Scope of objects to wipe out
  5116. * @return The count of deleted objects
  5117. */
  5118. public static function PurgeData($oFilter)
  5119. {
  5120. $sTargetClass = $oFilter->GetClass();
  5121. $oSet = new DBObjectSet($oFilter);
  5122. $oSet->OptimizeColumnLoad(array($sTargetClass => array('finalclass')));
  5123. $aIdToClass = $oSet->GetColumnAsArray('finalclass', true);
  5124. $aIds = array_keys($aIdToClass);
  5125. if (count($aIds) > 0)
  5126. {
  5127. $aQuotedIds = CMDBSource::Quote($aIds);
  5128. $sIdList = implode(',', $aQuotedIds);
  5129. $aTargetClasses = array_merge(
  5130. self::EnumChildClasses($sTargetClass, ENUM_CHILD_CLASSES_ALL),
  5131. self::EnumParentClasses($sTargetClass, ENUM_PARENT_CLASSES_EXCLUDELEAF)
  5132. );
  5133. foreach ($aTargetClasses as $sSomeClass)
  5134. {
  5135. $sTable = MetaModel::DBGetTable($sSomeClass);
  5136. $sPKField = MetaModel::DBGetKey($sSomeClass);
  5137. $sDeleteSQL = "DELETE FROM `$sTable` WHERE `$sPKField` IN ($sIdList)";
  5138. CMDBSource::DeleteFrom($sDeleteSQL);
  5139. }
  5140. }
  5141. return count($aIds);
  5142. }
  5143. // Links
  5144. //
  5145. //
  5146. public static function EnumReferencedClasses($sClass)
  5147. {
  5148. self::_check_subclass($sClass);
  5149. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  5150. $aResult = array();
  5151. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  5152. {
  5153. if ($oAttDef->IsExternalKey())
  5154. {
  5155. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  5156. }
  5157. }
  5158. return $aResult;
  5159. }
  5160. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  5161. {
  5162. self::_check_subclass($sClass);
  5163. if ($bSkipLinkingClasses)
  5164. {
  5165. $aLinksClasses = self::EnumLinksClasses();
  5166. }
  5167. // 1-N links (referencing my class), array of sClass => array of sAttcode
  5168. $aResult = array();
  5169. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  5170. {
  5171. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  5172. $aExtKeys = array();
  5173. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  5174. {
  5175. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  5176. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  5177. {
  5178. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  5179. // Ok, I want this one
  5180. $aExtKeys[$sAttCode] = $oAttDef;
  5181. }
  5182. }
  5183. if (count($aExtKeys) != 0)
  5184. {
  5185. $aResult[$sSomeClass] = $aExtKeys;
  5186. }
  5187. }
  5188. return $aResult;
  5189. }
  5190. /**
  5191. * It is not recommended to use this function: call GetLinkClasses instead
  5192. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  5193. * The only difference with EnumLinkingClasses is the output format
  5194. */
  5195. public static function EnumLinksClasses()
  5196. {
  5197. // Returns a flat array of classes having at least two external keys
  5198. $aResult = array();
  5199. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  5200. {
  5201. $iExtKeyCount = 0;
  5202. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  5203. {
  5204. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  5205. if ($oAttDef->IsExternalKey())
  5206. {
  5207. $iExtKeyCount++;
  5208. }
  5209. }
  5210. if ($iExtKeyCount >= 2)
  5211. {
  5212. $aResult[] = $sSomeClass;
  5213. }
  5214. }
  5215. return $aResult;
  5216. }
  5217. /**
  5218. * It is not recommended to use this function: call GetLinkClasses instead
  5219. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  5220. * The only difference with EnumLinksClasses is the output format
  5221. */
  5222. public static function EnumLinkingClasses($sClass = "")
  5223. {
  5224. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  5225. $aResult = array();
  5226. foreach (self::EnumLinksClasses() as $sSomeClass)
  5227. {
  5228. $aTargets = array();
  5229. $bFoundClass = false;
  5230. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  5231. {
  5232. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  5233. if ($oAttDef->IsExternalKey())
  5234. {
  5235. $sRemoteClass = $oAttDef->GetTargetClass();
  5236. if (empty($sClass))
  5237. {
  5238. $aTargets[$sAttCode] = $sRemoteClass;
  5239. }
  5240. elseif ($sClass == $sRemoteClass)
  5241. {
  5242. $bFoundClass = true;
  5243. }
  5244. else
  5245. {
  5246. $aTargets[$sAttCode] = $sRemoteClass;
  5247. }
  5248. }
  5249. }
  5250. if (empty($sClass) || $bFoundClass)
  5251. {
  5252. $aResult[$sSomeClass] = $aTargets;
  5253. }
  5254. }
  5255. return $aResult;
  5256. }
  5257. /**
  5258. * This function has two siblings that will be soon deprecated:
  5259. * EnumLinkingClasses and EnumLinkClasses
  5260. *
  5261. * Using GetLinkClasses is the recommended way to determine if a class is
  5262. * actually an N-N relation because it is based on the decision made by the
  5263. * designer the data model
  5264. */
  5265. public static function GetLinkClasses()
  5266. {
  5267. $aRet = array();
  5268. foreach(self::GetClasses() as $sClass)
  5269. {
  5270. if (isset(self::$m_aClassParams[$sClass]["is_link"]))
  5271. {
  5272. if (self::$m_aClassParams[$sClass]["is_link"])
  5273. {
  5274. $aExtKeys = array();
  5275. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  5276. {
  5277. if ($oAttDef->IsExternalKey())
  5278. {
  5279. $aExtKeys[$sAttCode] = $oAttDef->GetTargetClass();
  5280. }
  5281. }
  5282. $aRet[$sClass] = $aExtKeys;
  5283. }
  5284. }
  5285. }
  5286. return $aRet;
  5287. }
  5288. public static function GetLinkLabel($sLinkClass, $sAttCode)
  5289. {
  5290. self::_check_subclass($sLinkClass);
  5291. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  5292. return self::GetLabel($sLinkClass, $sAttCode);
  5293. }
  5294. /**
  5295. * Replaces all the parameters by the values passed in the hash array
  5296. */
  5297. static public function ApplyParams($sInput, $aParams)
  5298. {
  5299. // Declare magic parameters
  5300. $aParams['APP_URL'] = utils::GetAbsoluteUrlAppRoot();
  5301. $aParams['MODULES_URL'] = utils::GetAbsoluteUrlModulesRoot();
  5302. $aSearches = array();
  5303. $aReplacements = array();
  5304. foreach($aParams as $sSearch => $replace)
  5305. {
  5306. // Some environment parameters are objects, we just need scalars
  5307. if (is_object($replace))
  5308. {
  5309. $iPos = strpos($sSearch, '->object()');
  5310. if ($iPos !== false)
  5311. {
  5312. // Expand the parameters for the object
  5313. $sName = substr($sSearch, 0, $iPos);
  5314. if (preg_match_all('/\\$'.$sName.'->([^\\$]+)\\$/', $sInput, $aMatches))
  5315. {
  5316. foreach($aMatches[1] as $sPlaceholderAttCode)
  5317. {
  5318. try
  5319. {
  5320. $sReplacement = $replace->GetForTemplate($sPlaceholderAttCode);
  5321. if ($sReplacement !== null)
  5322. {
  5323. $aReplacements[] = $sReplacement;
  5324. $aSearches[] = '$'.$sName.'->'.$sPlaceholderAttCode.'$';
  5325. }
  5326. }
  5327. catch(Exception $e)
  5328. {
  5329. // No replacement will occur
  5330. }
  5331. }
  5332. }
  5333. }
  5334. else
  5335. {
  5336. continue; // Ignore this non-scalar value
  5337. }
  5338. }
  5339. $aSearches[] = '$'.$sSearch.'$';
  5340. $aReplacements[] = (string) $replace;
  5341. }
  5342. return str_replace($aSearches, $aReplacements, $sInput);
  5343. }
  5344. /**
  5345. * Returns an array of classes=>instance implementing the given interface
  5346. */
  5347. public static function EnumPlugins($sInterface)
  5348. {
  5349. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  5350. {
  5351. return self::$m_aExtensionClasses[$sInterface];
  5352. }
  5353. else
  5354. {
  5355. return array();
  5356. }
  5357. }
  5358. /**
  5359. * Returns the instance of the specified plug-ins for the given interface
  5360. */
  5361. public static function GetPlugins($sInterface, $sClassName)
  5362. {
  5363. $oInstance = null;
  5364. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  5365. {
  5366. if (array_key_exists($sClassName, self::$m_aExtensionClasses[$sInterface]))
  5367. {
  5368. return self::$m_aExtensionClasses[$sInterface][$sClassName];
  5369. }
  5370. }
  5371. return $oInstance;
  5372. }
  5373. public static function GetCacheEntries($sEnvironment = null)
  5374. {
  5375. if (!function_exists('apc_cache_info')) return array();
  5376. if (is_null($sEnvironment))
  5377. {
  5378. $sEnvironment = MetaModel::GetEnvironmentId();
  5379. }
  5380. $aEntries = array();
  5381. if (extension_loaded('apcu'))
  5382. {
  5383. // Beware: APCu behaves slightly differently from APC !!
  5384. $aCacheUserData = @apc_cache_info();
  5385. }
  5386. else
  5387. {
  5388. $aCacheUserData = @apc_cache_info('user');
  5389. }
  5390. if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list']))
  5391. {
  5392. $sPrefix = 'itop-'.$sEnvironment.'-';
  5393. foreach($aCacheUserData['cache_list'] as $i => $aEntry)
  5394. {
  5395. $sEntryKey = array_key_exists('info', $aEntry) ? $aEntry['info'] : $aEntry['key'];
  5396. if (strpos($sEntryKey, $sPrefix) === 0)
  5397. {
  5398. $sCleanKey = substr($sEntryKey, strlen($sPrefix));
  5399. $aEntries[$sCleanKey] = $aEntry;
  5400. $aEntries[$sCleanKey]['info'] = $sEntryKey;
  5401. }
  5402. }
  5403. }
  5404. return $aEntries;
  5405. }
  5406. public static function ResetCache($sEnvironmentId = null)
  5407. {
  5408. if (!function_exists('apc_delete')) return;
  5409. if (is_null($sEnvironmentId))
  5410. {
  5411. $sEnvironmentId = MetaModel::GetEnvironmentId();
  5412. }
  5413. $sAppIdentity = 'itop-'.$sEnvironmentId;
  5414. Dict::ResetCache($sAppIdentity);
  5415. foreach(self::GetCacheEntries($sEnvironmentId) as $sKey => $aAPCInfo)
  5416. {
  5417. $sAPCKey = $aAPCInfo['info'];
  5418. apc_delete($sAPCKey);
  5419. }
  5420. }
  5421. } // class MetaModel
  5422. // Standard attribute lists
  5423. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  5424. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  5425. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  5426. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  5427. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  5428. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));