metamodel.class.php 200 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937
  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. else
  1292. {
  1293. 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)");
  1294. }
  1295. }
  1296. }
  1297. }
  1298. // Foreach "down" legacy query, update its "up" counterpart (if any)
  1299. foreach ($aQueries[$sClass]['down'] as $sNeighbourId => $aNeighbourData)
  1300. {
  1301. if (!$aNeighbourData['_legacy_']) continue; // Skip modern definitions
  1302. $sLocalClass = $aNeighbourData['sFromClass'];
  1303. foreach (self::EnumChildClasses($aNeighbourData['sToClass'], ENUM_CHILD_CLASSES_ALL) as $sRemoteClass)
  1304. {
  1305. if (isset($aQueries[$sRemoteClass]['up'][$sLocalClass]))
  1306. {
  1307. $aQueries[$sRemoteClass]['up'][$sLocalClass]['sQueryDown'] = $aNeighbourData['sQueryDown'];
  1308. }
  1309. }
  1310. }
  1311. }
  1312. }
  1313. return $aQueries;
  1314. }
  1315. public static function EnumRelationQueries($sClass, $sRelCode, $bDown = true)
  1316. {
  1317. static $aQueries = array();
  1318. if (!isset($aQueries[$sRelCode]))
  1319. {
  1320. $aQueries[$sRelCode] = self::ComputeRelationQueries($sRelCode);
  1321. }
  1322. $sDirection = $bDown ? 'down' : 'up';
  1323. if (isset($aQueries[$sRelCode][$sClass][$sDirection]))
  1324. {
  1325. return $aQueries[$sRelCode][$sClass][$sDirection];
  1326. }
  1327. else
  1328. {
  1329. return array();
  1330. }
  1331. }
  1332. /**
  1333. * Compute the "RelatedObjects" for a whole set of DBObjects
  1334. *
  1335. * @param string $sRelCode The code of the relation to use for the computation
  1336. * @param array $asourceObjects The objects to start with
  1337. * @param int $iMaxDepth
  1338. * @param boolean $bEnableReduncancy
  1339. * @param array $aUnreachable Array of objects to be considered as 'unreachable'
  1340. *
  1341. * @return RelationGraph The graph of all the related objects
  1342. */
  1343. static public function GetRelatedObjectsDown($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aUnreachable = array())
  1344. {
  1345. $oGraph = new RelationGraph();
  1346. foreach ($aSourceObjects as $oObject)
  1347. {
  1348. $oGraph->AddSourceObject($oObject);
  1349. }
  1350. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy, $aUnreachable);
  1351. return $oGraph;
  1352. }
  1353. /**
  1354. * Compute the "RelatedObjects" in the reverse way
  1355. *
  1356. * @param string $sRelCode The code of the relation to use for the computation
  1357. * @param array $asourceObjects The objects to start with
  1358. * @param int $iMaxDepth
  1359. * @param boolean $bEnableReduncancy
  1360. *
  1361. * @return RelationGraph The graph of all the related objects
  1362. */
  1363. static public function GetRelatedObjectsUp($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true)
  1364. {
  1365. $oGraph = new RelationGraph();
  1366. foreach ($aSourceObjects as $oObject)
  1367. {
  1368. $oGraph->AddSinkObject($oObject);
  1369. }
  1370. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  1371. return $oGraph;
  1372. }
  1373. //
  1374. // Object lifecycle model
  1375. //
  1376. private static $m_aStates = array(); // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  1377. private static $m_aStimuli = array(); // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  1378. 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)))
  1379. public static function EnumStates($sClass)
  1380. {
  1381. if (array_key_exists($sClass, self::$m_aStates))
  1382. {
  1383. return self::$m_aStates[$sClass];
  1384. }
  1385. else
  1386. {
  1387. return array();
  1388. }
  1389. }
  1390. /*
  1391. * Enumerate all possible initial states, including the default one
  1392. */
  1393. public static function EnumInitialStates($sClass)
  1394. {
  1395. if (array_key_exists($sClass, self::$m_aStates))
  1396. {
  1397. $aRet = array();
  1398. // Add the states for which the flag 'is_initial_state' is set to <true>
  1399. foreach(self::$m_aStates[$sClass] as $aStateCode => $aProps)
  1400. {
  1401. if (isset($aProps['initial_state_path']))
  1402. {
  1403. $aRet[$aStateCode] = $aProps['initial_state_path'];
  1404. }
  1405. }
  1406. // Add the default initial state
  1407. $sMainInitialState = self::GetDefaultState($sClass);
  1408. if (!isset($aRet[$sMainInitialState]))
  1409. {
  1410. $aRet[$sMainInitialState] = array();
  1411. }
  1412. return $aRet;
  1413. }
  1414. else
  1415. {
  1416. return array();
  1417. }
  1418. }
  1419. public static function EnumStimuli($sClass)
  1420. {
  1421. if (array_key_exists($sClass, self::$m_aStimuli))
  1422. {
  1423. return self::$m_aStimuli[$sClass];
  1424. }
  1425. else
  1426. {
  1427. return array();
  1428. }
  1429. }
  1430. public static function GetStateLabel($sClass, $sStateValue)
  1431. {
  1432. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1433. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1434. return $oAttDef->GetValueLabel($sStateValue);
  1435. }
  1436. public static function GetStateDescription($sClass, $sStateValue)
  1437. {
  1438. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1439. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1440. return $oAttDef->GetValueDescription($sStateValue);
  1441. }
  1442. public static function EnumTransitions($sClass, $sStateCode)
  1443. {
  1444. if (array_key_exists($sClass, self::$m_aTransitions))
  1445. {
  1446. if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
  1447. {
  1448. return self::$m_aTransitions[$sClass][$sStateCode];
  1449. }
  1450. }
  1451. return array();
  1452. }
  1453. public static function GetAttributeFlags($sClass, $sState, $sAttCode)
  1454. {
  1455. $iFlags = 0; // By default (if no life cycle) no flag at all
  1456. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1457. if (!empty($sStateAttCode))
  1458. {
  1459. $aStates = MetaModel::EnumStates($sClass);
  1460. if (!array_key_exists($sState, $aStates))
  1461. {
  1462. throw new CoreException("Invalid state '$sState' for class '$sClass', expecting a value in {".implode(', ', array_keys($aStates))."}");
  1463. }
  1464. $aCurrentState = $aStates[$sState];
  1465. if ( (array_key_exists('attribute_list', $aCurrentState)) && (array_key_exists($sAttCode, $aCurrentState['attribute_list'])) )
  1466. {
  1467. $iFlags = $aCurrentState['attribute_list'][$sAttCode];
  1468. }
  1469. }
  1470. return $iFlags;
  1471. }
  1472. /**
  1473. * Combines the flags from the all states that compose the initial_state_path
  1474. */
  1475. public static function GetInitialStateAttributeFlags($sClass, $sState, $sAttCode)
  1476. {
  1477. $iFlags = self::GetAttributeFlags($sClass, $sState, $sAttCode); // Be default set the same flags as the 'target' state
  1478. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1479. if (!empty($sStateAttCode))
  1480. {
  1481. $aStates = MetaModel::EnumInitialStates($sClass);
  1482. if (array_key_exists($sState, $aStates))
  1483. {
  1484. $bReadOnly = (($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY);
  1485. $bHidden = (($iFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN);
  1486. foreach($aStates[$sState] as $sPrevState)
  1487. {
  1488. $iPrevFlags = self::GetAttributeFlags($sClass, $sPrevState, $sAttCode);
  1489. if (($iPrevFlags & OPT_ATT_HIDDEN) != OPT_ATT_HIDDEN)
  1490. {
  1491. $bReadOnly = $bReadOnly && (($iPrevFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY); // if it is/was not readonly => then it's not
  1492. }
  1493. $bHidden = $bHidden && (($iPrevFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN); // if it is/was not hidden => then it's not
  1494. }
  1495. if ($bReadOnly)
  1496. {
  1497. $iFlags = $iFlags | OPT_ATT_READONLY;
  1498. }
  1499. else
  1500. {
  1501. $iFlags = $iFlags & ~OPT_ATT_READONLY;
  1502. }
  1503. if ($bHidden)
  1504. {
  1505. $iFlags = $iFlags | OPT_ATT_HIDDEN;
  1506. }
  1507. else
  1508. {
  1509. $iFlags = $iFlags & ~OPT_ATT_HIDDEN;
  1510. }
  1511. }
  1512. }
  1513. return $iFlags;
  1514. }
  1515. //
  1516. // Allowed values
  1517. //
  1518. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1519. {
  1520. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1521. return $oAttDef->GetAllowedValues($aArgs, $sContains);
  1522. }
  1523. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sContains = '')
  1524. {
  1525. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  1526. return $oFltDef->GetAllowedValues($aArgs, $sContains);
  1527. }
  1528. public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1529. {
  1530. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1531. return $oAttDef->GetAllowedValuesAsObjectSet($aArgs, $sContains);
  1532. }
  1533. //
  1534. // Businezz model declaration verbs (should be static)
  1535. //
  1536. public static function RegisterZList($sListCode, $aListInfo)
  1537. {
  1538. // Check mandatory params
  1539. $aMandatParams = array(
  1540. "description" => "detailed (though one line) description of the list",
  1541. "type" => "attributes | filters",
  1542. );
  1543. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1544. {
  1545. if (!array_key_exists($sParamName, $aListInfo))
  1546. {
  1547. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  1548. }
  1549. }
  1550. self::$m_aListInfos[$sListCode] = $aListInfo;
  1551. }
  1552. public static function RegisterRelation($sRelCode)
  1553. {
  1554. // Each item used to be an array of properties...
  1555. self::$m_aRelationInfos[$sRelCode] = $sRelCode;
  1556. }
  1557. // Must be called once and only once...
  1558. public static function InitClasses($sTablePrefix)
  1559. {
  1560. if (count(self::GetClasses()) > 0)
  1561. {
  1562. throw new CoreException("InitClasses should not be called more than once -skipped");
  1563. return;
  1564. }
  1565. self::$m_sTablePrefix = $sTablePrefix;
  1566. // Build the list of available extensions
  1567. //
  1568. $aInterfaces = array('iApplicationUIExtension', 'iApplicationObjectExtension', 'iQueryModifier', 'iOnClassInitialization', 'iPopupMenuExtension', 'iPageUIExtension');
  1569. foreach($aInterfaces as $sInterface)
  1570. {
  1571. self::$m_aExtensionClasses[$sInterface] = array();
  1572. }
  1573. foreach(get_declared_classes() as $sPHPClass)
  1574. {
  1575. $oRefClass = new ReflectionClass($sPHPClass);
  1576. $oExtensionInstance = null;
  1577. foreach($aInterfaces as $sInterface)
  1578. {
  1579. if ($oRefClass->implementsInterface($sInterface))
  1580. {
  1581. if (is_null($oExtensionInstance))
  1582. {
  1583. $oExtensionInstance = new $sPHPClass;
  1584. }
  1585. self::$m_aExtensionClasses[$sInterface][$sPHPClass] = $oExtensionInstance;
  1586. }
  1587. }
  1588. }
  1589. // Initialize the classes (declared attributes, etc.)
  1590. //
  1591. foreach(get_declared_classes() as $sPHPClass)
  1592. {
  1593. if (is_subclass_of($sPHPClass, 'DBObject'))
  1594. {
  1595. $sParent = get_parent_class($sPHPClass);
  1596. if (array_key_exists($sParent, self::$m_aIgnoredAttributes))
  1597. {
  1598. // Inherit info about attributes to ignore
  1599. self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent];
  1600. }
  1601. try
  1602. {
  1603. $oMethod = new ReflectionMethod($sPHPClass, 'Init');
  1604. if ($oMethod->getDeclaringClass()->name == $sPHPClass)
  1605. {
  1606. call_user_func(array($sPHPClass, 'Init'));
  1607. foreach (MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit)
  1608. {
  1609. $oClassInit->OnAfterClassInitialization($sPHPClass);
  1610. }
  1611. }
  1612. }
  1613. catch (ReflectionException $e)
  1614. {
  1615. // This class is only implementing methods, ignore it from the MetaModel perspective
  1616. }
  1617. }
  1618. }
  1619. // Add a 'class' attribute/filter to the root classes and their children
  1620. //
  1621. foreach(self::EnumRootClasses() as $sRootClass)
  1622. {
  1623. if (self::IsStandaloneClass($sRootClass)) continue;
  1624. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  1625. if (strlen($sDbFinalClassField) == 0)
  1626. {
  1627. $sDbFinalClassField = 'finalclass';
  1628. self::$m_aClassParams[$sRootClass]["db_finalclass_field"] = 'finalclass';
  1629. }
  1630. $oClassAtt = new AttributeFinalClass('finalclass', array(
  1631. "sql"=>$sDbFinalClassField,
  1632. "default_value"=>$sRootClass,
  1633. "is_null_allowed"=>false,
  1634. "depends_on"=>array()
  1635. ));
  1636. $oClassAtt->SetHostClass($sRootClass);
  1637. self::$m_aAttribDefs[$sRootClass]['finalclass'] = $oClassAtt;
  1638. self::$m_aAttribOrigins[$sRootClass]['finalclass'] = $sRootClass;
  1639. $oClassFlt = new FilterFromAttribute($oClassAtt);
  1640. self::$m_aFilterDefs[$sRootClass]['finalclass'] = $oClassFlt;
  1641. self::$m_aFilterOrigins[$sRootClass]['finalclass'] = $sRootClass;
  1642. foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass)
  1643. {
  1644. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass]))
  1645. {
  1646. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  1647. }
  1648. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sChildClass]))
  1649. {
  1650. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  1651. }
  1652. $oCloned = clone $oClassAtt;
  1653. $oCloned->SetFixedValue($sChildClass);
  1654. self::$m_aAttribDefs[$sChildClass]['finalclass'] = $oCloned;
  1655. self::$m_aAttribOrigins[$sChildClass]['finalclass'] = $sRootClass;
  1656. $oClassFlt = new FilterFromAttribute($oClassAtt);
  1657. self::$m_aFilterDefs[$sChildClass]['finalclass'] = $oClassFlt;
  1658. self::$m_aFilterOrigins[$sChildClass]['finalclass'] = self::GetRootClass($sChildClass);
  1659. }
  1660. }
  1661. // Prepare external fields and filters
  1662. // Add final class to external keys
  1663. //
  1664. foreach (self::GetClasses() as $sClass)
  1665. {
  1666. // Create the friendly name attribute
  1667. $sFriendlyNameAttCode = 'friendlyname';
  1668. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, 'id');
  1669. $oFriendlyName->SetHostClass($sClass);
  1670. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1671. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sClass;
  1672. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1673. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1674. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sClass;
  1675. self::$m_aExtKeyFriends[$sClass] = array();
  1676. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  1677. {
  1678. // Compute the filter codes
  1679. //
  1680. foreach ($oAttDef->GetFilterDefinitions() as $sFilterCode => $oFilterDef)
  1681. {
  1682. self::$m_aFilterDefs[$sClass][$sFilterCode] = $oFilterDef;
  1683. if ($oAttDef->IsExternalField())
  1684. {
  1685. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1686. $oKeyDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1687. self::$m_aFilterOrigins[$sClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  1688. }
  1689. else
  1690. {
  1691. self::$m_aFilterOrigins[$sClass][$sFilterCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  1692. }
  1693. }
  1694. // Compute the fields that will be used to display a pointer to another object
  1695. //
  1696. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  1697. {
  1698. // oAttDef is either
  1699. // - an external KEY / FIELD (direct),
  1700. // - an external field pointing to an external KEY / FIELD
  1701. // - an external field pointing to an external field pointing to....
  1702. $sRemoteClass = $oAttDef->GetTargetClass();
  1703. if ($oAttDef->IsExternalField())
  1704. {
  1705. // This is a key, but the value comes from elsewhere
  1706. // Create an external field pointing to the remote friendly name attribute
  1707. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1708. $sRemoteAttCode = $oAttDef->GetExtAttCode()."_friendlyname";
  1709. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1710. // propagate "is_null_allowed" ?
  1711. $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array("allowed_values"=>null, "extkey_attcode"=>$sKeyAttCode, "target_attcode"=>$sRemoteAttCode, "depends_on"=>array()));
  1712. $oFriendlyName->SetHostClass($sClass);
  1713. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1714. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1715. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1716. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1717. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1718. }
  1719. else
  1720. {
  1721. // Create the friendly name attribute
  1722. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1723. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, $sAttCode);
  1724. $oFriendlyName->SetHostClass($sClass);
  1725. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1726. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1727. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1728. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1729. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1730. if (self::HasChildrenClasses($sRemoteClass))
  1731. {
  1732. // First, create an external field attribute, that gets the final class
  1733. $sClassRecallAttCode = $sAttCode.'_finalclass_recall';
  1734. $oClassRecall = new AttributeExternalField($sClassRecallAttCode, array(
  1735. "allowed_values"=>null,
  1736. "extkey_attcode"=>$sAttCode,
  1737. "target_attcode"=>"finalclass",
  1738. "is_null_allowed"=>true,
  1739. "depends_on"=>array()
  1740. ));
  1741. $oClassRecall->SetHostClass($sClass);
  1742. self::$m_aAttribDefs[$sClass][$sClassRecallAttCode] = $oClassRecall;
  1743. self::$m_aAttribOrigins[$sClass][$sClassRecallAttCode] = $sRemoteClass;
  1744. $oClassFlt = new FilterFromAttribute($oClassRecall);
  1745. self::$m_aFilterDefs[$sClass][$sClassRecallAttCode] = $oClassFlt;
  1746. self::$m_aFilterOrigins[$sClass][$sClassRecallAttCode] = $sRemoteClass;
  1747. // Add it to the ZLists where the external key is present
  1748. //foreach(self::$m_aListData[$sClass] as $sListCode => $aAttributes)
  1749. $sListCode = 'list';
  1750. if (isset(self::$m_aListData[$sClass][$sListCode]))
  1751. {
  1752. $aAttributes = self::$m_aListData[$sClass][$sListCode];
  1753. // temporary.... no loop
  1754. {
  1755. if (in_array($sAttCode, $aAttributes))
  1756. {
  1757. $aNewList = array();
  1758. foreach($aAttributes as $iPos => $sAttToDisplay)
  1759. {
  1760. if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode))
  1761. {
  1762. // Insert the final class right before
  1763. $aNewList[] = $sClassRecallAttCode;
  1764. }
  1765. $aNewList[] = $sAttToDisplay;
  1766. }
  1767. self::$m_aListData[$sClass][$sListCode] = $aNewList;
  1768. }
  1769. }
  1770. }
  1771. }
  1772. }
  1773. // Get the real external key attribute
  1774. // It will be our reference to determine the other ext fields related to the same ext key
  1775. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1776. self::$m_aExtKeyFriends[$sClass][$sAttCode] = array();
  1777. foreach (self::GetExternalFields($sClass, $oAttDef->GetKeyAttCode($sAttCode)) as $oExtField)
  1778. {
  1779. // skip : those extfields will be processed as external keys
  1780. if ($oExtField->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1781. // Note: I could not compare the objects by the mean of '==='
  1782. // because they are copied for the inheritance, and the internal references are NOT updated
  1783. if ($oExtField->GetKeyAttDef(EXTKEY_ABSOLUTE) == $oFinalKeyAttDef)
  1784. {
  1785. self::$m_aExtKeyFriends[$sClass][$sAttCode][$oExtField->GetCode()] = $oExtField;
  1786. }
  1787. }
  1788. }
  1789. }
  1790. // Add a 'id' filter
  1791. //
  1792. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  1793. {
  1794. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  1795. }
  1796. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  1797. {
  1798. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  1799. }
  1800. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  1801. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  1802. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  1803. // Define defaults values for the standard ZLists
  1804. //
  1805. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  1806. //{
  1807. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  1808. // {
  1809. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  1810. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  1811. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  1812. // }
  1813. //}
  1814. }
  1815. }
  1816. // To be overriden, must be called for any object class (optimization)
  1817. public static function Init()
  1818. {
  1819. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1820. }
  1821. // To be overloaded by biz model declarations
  1822. public static function GetRelationQueries($sRelCode)
  1823. {
  1824. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1825. return array();
  1826. }
  1827. public static function Init_Params($aParams)
  1828. {
  1829. // Check mandatory params
  1830. $aMandatParams = array(
  1831. "category" => "group classes by modules defining their visibility in the UI",
  1832. "key_type" => "autoincrement | string",
  1833. "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...'",
  1834. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  1835. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  1836. "db_table" => "database table",
  1837. "db_key_field" => "database field which is the key",
  1838. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  1839. );
  1840. $sClass = self::GetCallersPHPClass("Init", self::$m_bTraceSourceFiles);
  1841. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1842. {
  1843. if (!array_key_exists($sParamName, $aParams))
  1844. {
  1845. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  1846. }
  1847. }
  1848. $aCategories = explode(',', $aParams['category']);
  1849. foreach ($aCategories as $sCategory)
  1850. {
  1851. self::$m_Category2Class[$sCategory][] = $sClass;
  1852. }
  1853. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  1854. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  1855. self::$m_aParentClasses[$sClass] = array();
  1856. self::$m_aChildClasses[$sClass] = array();
  1857. self::$m_aClassParams[$sClass]= $aParams;
  1858. self::$m_aAttribDefs[$sClass] = array();
  1859. self::$m_aAttribOrigins[$sClass] = array();
  1860. self::$m_aExtKeyFriends[$sClass] = array();
  1861. self::$m_aFilterDefs[$sClass] = array();
  1862. self::$m_aFilterOrigins[$sClass] = array();
  1863. }
  1864. protected static function object_array_mergeclone($aSource1, $aSource2)
  1865. {
  1866. $aRes = array();
  1867. foreach ($aSource1 as $key=>$object)
  1868. {
  1869. $aRes[$key] = clone $object;
  1870. }
  1871. foreach ($aSource2 as $key=>$object)
  1872. {
  1873. $aRes[$key] = clone $object;
  1874. }
  1875. return $aRes;
  1876. }
  1877. public static function Init_InheritAttributes($sSourceClass = null)
  1878. {
  1879. $sTargetClass = self::GetCallersPHPClass("Init");
  1880. if (empty($sSourceClass))
  1881. {
  1882. // Default: inherit from parent class
  1883. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1884. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1885. }
  1886. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  1887. {
  1888. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  1889. {
  1890. self::$m_aAttribDefs[$sTargetClass] = array();
  1891. self::$m_aAttribOrigins[$sTargetClass] = array();
  1892. }
  1893. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  1894. foreach(self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef)
  1895. {
  1896. $oAttDef->SetHostClass($sTargetClass);
  1897. }
  1898. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  1899. }
  1900. // Build root class information
  1901. if (array_key_exists($sSourceClass, self::$m_aRootClasses))
  1902. {
  1903. // Inherit...
  1904. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  1905. }
  1906. else
  1907. {
  1908. // This class will be the root class
  1909. self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
  1910. self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
  1911. }
  1912. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  1913. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  1914. // I am the child of each and every parent...
  1915. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  1916. {
  1917. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  1918. }
  1919. }
  1920. protected static function Init_IsKnownClass($sClass)
  1921. {
  1922. // Differs from self::IsValidClass()
  1923. // because it is being called before all the classes have been initialized
  1924. if (!class_exists($sClass)) return false;
  1925. if (!is_subclass_of($sClass, 'DBObject')) return false;
  1926. return true;
  1927. }
  1928. public static function Init_AddAttribute(AttributeDefinition $oAtt, $sTargetClass = null)
  1929. {
  1930. if (!$sTargetClass)
  1931. {
  1932. $sTargetClass = self::GetCallersPHPClass("Init");
  1933. }
  1934. $sAttCode = $oAtt->GetCode();
  1935. if ($sAttCode == 'finalclass')
  1936. {
  1937. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1938. }
  1939. if ($sAttCode == 'friendlyname')
  1940. {
  1941. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1942. }
  1943. if (array_key_exists($sAttCode, self::$m_aAttribDefs[$sTargetClass]))
  1944. {
  1945. throw new Exception("Declaration of $sTargetClass: attempting to redeclare the inherited attribute '$sAttCode', originaly declared in ".self::$m_aAttribOrigins[$sTargetClass][$sAttCode]);
  1946. }
  1947. // Set the "host class" as soon as possible, since HierarchicalKeys use it for their 'target class' as well
  1948. // and this needs to be know early (for Init_IsKnowClass 19 lines below)
  1949. $oAtt->SetHostClass($sTargetClass);
  1950. // Some attributes could refer to a class
  1951. // declared in a module which is currently not installed/active
  1952. // We simply discard those attributes
  1953. //
  1954. if ($oAtt->IsLinkSet())
  1955. {
  1956. $sRemoteClass = $oAtt->GetLinkedClass();
  1957. if (!self::Init_IsKnownClass($sRemoteClass))
  1958. {
  1959. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1960. return;
  1961. }
  1962. }
  1963. elseif($oAtt->IsExternalKey())
  1964. {
  1965. $sRemoteClass = $oAtt->GetTargetClass();
  1966. if (!self::Init_IsKnownClass($sRemoteClass))
  1967. {
  1968. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1969. return;
  1970. }
  1971. }
  1972. elseif($oAtt->IsExternalField())
  1973. {
  1974. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  1975. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
  1976. {
  1977. // The corresponding external key has already been ignored
  1978. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
  1979. return;
  1980. }
  1981. // #@# todo - Check if the target attribute is still there
  1982. // this is not simple to implement because is involves
  1983. // several passes (the load order has a significant influence on that)
  1984. }
  1985. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  1986. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  1987. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  1988. }
  1989. public static function Init_SetZListItems($sListCode, $aItems, $sTargetClass = null)
  1990. {
  1991. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  1992. if (!$sTargetClass)
  1993. {
  1994. $sTargetClass = self::GetCallersPHPClass("Init");
  1995. }
  1996. // Discard attributes that do not make sense
  1997. // (missing classes in the current module combination, resulting in irrelevant ext key or link set)
  1998. //
  1999. self::Init_CheckZListItems($aItems, $sTargetClass);
  2000. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  2001. }
  2002. protected static function Init_CheckZListItems(&$aItems, $sTargetClass)
  2003. {
  2004. foreach($aItems as $iFoo => $attCode)
  2005. {
  2006. if (is_array($attCode))
  2007. {
  2008. // Note: to make sure that the values will be updated recursively,
  2009. // do not pass $attCode, but $aItems[$iFoo] instead
  2010. self::Init_CheckZListItems($aItems[$iFoo], $sTargetClass);
  2011. if (count($aItems[$iFoo]) == 0)
  2012. {
  2013. unset($aItems[$iFoo]);
  2014. }
  2015. }
  2016. else if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode]))
  2017. {
  2018. unset($aItems[$iFoo]);
  2019. }
  2020. }
  2021. }
  2022. public static function FlattenZList($aList)
  2023. {
  2024. $aResult = array();
  2025. foreach($aList as $value)
  2026. {
  2027. if (!is_array($value))
  2028. {
  2029. $aResult[] = $value;
  2030. }
  2031. else
  2032. {
  2033. $aResult = array_merge($aResult, self::FlattenZList($value));
  2034. }
  2035. }
  2036. return $aResult;
  2037. }
  2038. public static function Init_DefineState($sStateCode, $aStateDef)
  2039. {
  2040. $sTargetClass = self::GetCallersPHPClass("Init");
  2041. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  2042. $sParentState = $aStateDef['attribute_inherit'];
  2043. if (!empty($sParentState))
  2044. {
  2045. // Inherit from the given state (must be defined !)
  2046. //
  2047. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  2048. // Reset the constraint when it was mandatory to set the value at the previous state
  2049. //
  2050. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  2051. {
  2052. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  2053. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  2054. $aToInherit['attribute_list'][$sState] = $iFlags;
  2055. }
  2056. // The inherited configuration could be overriden
  2057. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  2058. }
  2059. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  2060. {
  2061. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  2062. {
  2063. unset($aStateDef['attribute_list'][$sAttCode]);
  2064. }
  2065. }
  2066. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  2067. // by default, create an empty set of transitions associated to that state
  2068. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  2069. }
  2070. public static function Init_DefineHighlightScale($aHighlightScale)
  2071. {
  2072. $sTargetClass = self::GetCallersPHPClass("Init");
  2073. self::$m_aHighlightScales[$sTargetClass] = $aHighlightScale;
  2074. }
  2075. public static function GetHighlightScale($sTargetClass)
  2076. {
  2077. $aScale = array();
  2078. $aParentScale = array();
  2079. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2080. if (!empty($sParentClass))
  2081. {
  2082. // inherit the scale from the parent class
  2083. $aParentScale = self::GetHighlightScale($sParentClass);
  2084. }
  2085. if (array_key_exists($sTargetClass, self::$m_aHighlightScales))
  2086. {
  2087. $aScale = self::$m_aHighlightScales[$sTargetClass];
  2088. }
  2089. return array_merge($aParentScale, $aScale); // Merge both arrays, the values from the last one have precedence
  2090. }
  2091. public static function GetHighlightCode($sTargetClass, $sStateCode)
  2092. {
  2093. $sCode = '';
  2094. if ( array_key_exists($sTargetClass, self::$m_aStates)
  2095. && array_key_exists($sStateCode, self::$m_aStates[$sTargetClass])
  2096. && array_key_exists('highlight', self::$m_aStates[$sTargetClass][$sStateCode]) )
  2097. {
  2098. $sCode = self::$m_aStates[$sTargetClass][$sStateCode]['highlight']['code'];
  2099. }
  2100. else
  2101. {
  2102. // Check the parent's definition
  2103. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2104. if (!empty($sParentClass))
  2105. {
  2106. $sCode = self::GetHighlightCode($sParentClass, $sStateCode);
  2107. }
  2108. }
  2109. return $sCode;
  2110. }
  2111. public static function Init_OverloadStateAttribute($sStateCode, $sAttCode, $iFlags)
  2112. {
  2113. // Warning: this is not sufficient: the flags have to be copied to the states that are inheriting from this state
  2114. $sTargetClass = self::GetCallersPHPClass("Init");
  2115. self::$m_aStates[$sTargetClass][$sStateCode]['attribute_list'][$sAttCode] = $iFlags;
  2116. }
  2117. public static function Init_DefineStimulus($oStimulus)
  2118. {
  2119. $sTargetClass = self::GetCallersPHPClass("Init");
  2120. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  2121. // I wanted to simplify the syntax of the declaration of objects in the biz model
  2122. // Therefore, the reference to the host class is set there
  2123. $oStimulus->SetHostClass($sTargetClass);
  2124. }
  2125. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  2126. {
  2127. $sTargetClass = self::GetCallersPHPClass("Init");
  2128. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  2129. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  2130. }
  2131. public static function Init_InheritLifecycle($sSourceClass = '')
  2132. {
  2133. $sTargetClass = self::GetCallersPHPClass("Init");
  2134. if (empty($sSourceClass))
  2135. {
  2136. // Default: inherit from parent class
  2137. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  2138. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  2139. }
  2140. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  2141. self::$m_aStates[$sTargetClass] = self::$m_aStates[$sSourceClass];
  2142. // #@# Note: the aim is to clone the data, could be an issue if the simuli objects are changed
  2143. self::$m_aStimuli[$sTargetClass] = self::$m_aStimuli[$sSourceClass];
  2144. self::$m_aTransitions[$sTargetClass] = self::$m_aTransitions[$sSourceClass];
  2145. }
  2146. //
  2147. // Static API
  2148. //
  2149. public static function GetRootClass($sClass = null)
  2150. {
  2151. self::_check_subclass($sClass);
  2152. return self::$m_aRootClasses[$sClass];
  2153. }
  2154. public static function IsRootClass($sClass)
  2155. {
  2156. self::_check_subclass($sClass);
  2157. return (self::GetRootClass($sClass) == $sClass);
  2158. }
  2159. public static function GetParentClass($sClass)
  2160. {
  2161. if (count(self::$m_aParentClasses[$sClass]) == 0)
  2162. {
  2163. return null;
  2164. }
  2165. else
  2166. {
  2167. return end(self::$m_aParentClasses[$sClass]);
  2168. }
  2169. }
  2170. /**
  2171. * Tells if a class contains a hierarchical key, and if so what is its AttCode
  2172. * @return mixed String = sAttCode or false if the class is not part of a hierarchy
  2173. */
  2174. public static function IsHierarchicalClass($sClass)
  2175. {
  2176. $sHierarchicalKeyCode = false;
  2177. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  2178. {
  2179. if ($oAtt->IsHierarchicalKey())
  2180. {
  2181. $sHierarchicalKeyCode = $sAttCode; // Found the hierarchical key, no need to continue
  2182. break;
  2183. }
  2184. }
  2185. return $sHierarchicalKeyCode;
  2186. }
  2187. public static function EnumRootClasses()
  2188. {
  2189. return array_unique(self::$m_aRootClasses);
  2190. }
  2191. public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF, $bRootFirst = true)
  2192. {
  2193. self::_check_subclass($sClass);
  2194. if ($bRootFirst)
  2195. {
  2196. $aRes = self::$m_aParentClasses[$sClass];
  2197. }
  2198. else
  2199. {
  2200. $aRes = array_reverse(self::$m_aParentClasses[$sClass], true);
  2201. }
  2202. if ($iOption != ENUM_PARENT_CLASSES_EXCLUDELEAF)
  2203. {
  2204. if ($bRootFirst)
  2205. {
  2206. // Leaf class at the end
  2207. $aRes[] = $sClass;
  2208. }
  2209. else
  2210. {
  2211. // Leaf class on top
  2212. array_unshift($aRes, $sClass);
  2213. }
  2214. }
  2215. return $aRes;
  2216. }
  2217. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  2218. {
  2219. self::_check_subclass($sClass);
  2220. $aRes = self::$m_aChildClasses[$sClass];
  2221. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  2222. {
  2223. // Add it to the list
  2224. $aRes[] = $sClass;
  2225. }
  2226. return $aRes;
  2227. }
  2228. public static function HasChildrenClasses($sClass)
  2229. {
  2230. return (count(self::$m_aChildClasses[$sClass]) > 0);
  2231. }
  2232. public static function EnumCategories()
  2233. {
  2234. return array_keys(self::$m_Category2Class);
  2235. }
  2236. // Note: use EnumChildClasses to take the compound objects into account
  2237. public static function GetSubclasses($sClass)
  2238. {
  2239. self::_check_subclass($sClass);
  2240. $aSubClasses = array();
  2241. foreach(self::$m_aClassParams as $sSubClass => $foo)
  2242. {
  2243. if (is_subclass_of($sSubClass, $sClass))
  2244. {
  2245. $aSubClasses[] = $sSubClass;
  2246. }
  2247. }
  2248. return $aSubClasses;
  2249. }
  2250. public static function GetClasses($sCategories = '', $bStrict = false)
  2251. {
  2252. $aCategories = explode(',', $sCategories);
  2253. $aClasses = array();
  2254. foreach($aCategories as $sCategory)
  2255. {
  2256. $sCategory = trim($sCategory);
  2257. if (strlen($sCategory) == 0)
  2258. {
  2259. return array_keys(self::$m_aClassParams);
  2260. }
  2261. if (array_key_exists($sCategory, self::$m_Category2Class))
  2262. {
  2263. $aClasses = array_merge($aClasses, self::$m_Category2Class[$sCategory]);
  2264. }
  2265. elseif ($bStrict)
  2266. {
  2267. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  2268. }
  2269. }
  2270. return array_unique($aClasses);
  2271. }
  2272. public static function HasTable($sClass)
  2273. {
  2274. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  2275. return true;
  2276. }
  2277. public static function IsAbstract($sClass)
  2278. {
  2279. $oReflection = new ReflectionClass($sClass);
  2280. return $oReflection->isAbstract();
  2281. }
  2282. protected static $m_aQueryStructCache = array();
  2283. public static function PrepareQueryArguments($aArgs)
  2284. {
  2285. // Translate any object into scalars
  2286. //
  2287. $aScalarArgs = array();
  2288. foreach($aArgs as $sArgName => $value)
  2289. {
  2290. if (self::IsValidObject($value))
  2291. {
  2292. if (strpos($sArgName, '->object()') === false)
  2293. {
  2294. // Lazy syntax - develop the object contextual parameters
  2295. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgsForQuery($sArgName));
  2296. }
  2297. else
  2298. {
  2299. // Leave as is
  2300. $aScalarArgs[$sArgName] = $value;
  2301. }
  2302. }
  2303. else
  2304. {
  2305. if (is_scalar($value))
  2306. {
  2307. $aScalarArgs[$sArgName] = (string) $value;
  2308. }
  2309. elseif (is_null($value))
  2310. {
  2311. $aScalarArgs[$sArgName] = null;
  2312. }
  2313. }
  2314. }
  2315. // Add standard contextual arguments
  2316. //
  2317. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  2318. return $aScalarArgs;
  2319. }
  2320. public static function MakeGroupByQuery(DBObjectSearch $oFilter, $aArgs, $aGroupByExpr, $bExcludeNullValues = false)
  2321. {
  2322. $aAttToLoad = array();
  2323. if ($bExcludeNullValues)
  2324. {
  2325. // Null values are not handled (though external keys set to 0 are allowed)
  2326. $oQueryFilter = $oFilter->DeepClone();
  2327. foreach ($aGroupByExpr as $oGroupByExp)
  2328. {
  2329. $oNull = new FunctionExpression('ISNULL', array($oGroupByExp));
  2330. $oNotNull = new BinaryExpression($oNull, '!=', new TrueExpression());
  2331. $oQueryFilter->AddConditionExpression($oNotNull);
  2332. }
  2333. }
  2334. else
  2335. {
  2336. $oQueryFilter = $oFilter;
  2337. }
  2338. $oSelect = self::MakeSelectStructure($oQueryFilter, array(), $aArgs, $aAttToLoad, null, 0, 0, false, $aGroupByExpr);
  2339. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2340. try
  2341. {
  2342. $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
  2343. $sRes = $oSelect->RenderGroupBy($aScalarArgs, $bBeautifulSQL);
  2344. }
  2345. catch (MissingQueryArgument $e)
  2346. {
  2347. // Add some information...
  2348. $e->addInfo('OQL', $oFilter->ToOQL());
  2349. throw $e;
  2350. }
  2351. self::AddQueryTraceGroupBy($oFilter, $aArgs, $aGroupByExpr, $sRes);
  2352. return $sRes;
  2353. }
  2354. /**
  2355. * @param hash $aOrderBy Array of '[<classalias>.]attcode' => bAscending
  2356. */
  2357. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $aAttToLoad = null, $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false)
  2358. {
  2359. // Check the order by specification, and prefix with the class alias
  2360. // and make sure that the ordering columns are going to be selected
  2361. //
  2362. $sClass = $oFilter->GetClass();
  2363. $sClassAlias = $oFilter->GetClassAlias();
  2364. $aOrderSpec = array();
  2365. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  2366. {
  2367. if (!is_bool($bAscending))
  2368. {
  2369. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  2370. }
  2371. $iDotPos = strpos($sFieldAlias, '.');
  2372. if ($iDotPos === false)
  2373. {
  2374. $sAttClass = $sClass;
  2375. $sAttClassAlias = $sClassAlias;
  2376. $sAttCode = $sFieldAlias;
  2377. }
  2378. else
  2379. {
  2380. $sAttClassAlias = substr($sFieldAlias, 0, $iDotPos);
  2381. $sAttClass = $oFilter->GetClassName($sAttClassAlias);
  2382. $sAttCode = substr($sFieldAlias, $iDotPos + 1);
  2383. }
  2384. if ($sAttCode != 'id')
  2385. {
  2386. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sAttCode, self::GetAttributesList($sAttClass));
  2387. $oAttDef = self::GetAttributeDef($sAttClass, $sAttCode);
  2388. foreach($oAttDef->GetOrderBySQLExpressions($sAttClassAlias) as $sSQLExpression)
  2389. {
  2390. $aOrderSpec[$sSQLExpression] = $bAscending;
  2391. }
  2392. }
  2393. else
  2394. {
  2395. $aOrderSpec['`'.$sAttClassAlias.$sAttCode.'`'] = $bAscending;
  2396. }
  2397. // Make sure that the columns used for sorting are present in the loaded columns
  2398. if (!is_null($aAttToLoad) && !isset($aAttToLoad[$sAttClassAlias][$sAttCode]))
  2399. {
  2400. $aAttToLoad[$sAttClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sAttClass, $sAttCode);
  2401. }
  2402. }
  2403. $oSelect = self::MakeSelectStructure($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount);
  2404. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2405. try
  2406. {
  2407. $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
  2408. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount, $bBeautifulSQL);
  2409. if ($sClassAlias == '_itop_')
  2410. {
  2411. echo $sRes."<br/>\n";
  2412. }
  2413. }
  2414. catch (MissingQueryArgument $e)
  2415. {
  2416. // Add some information...
  2417. $e->addInfo('OQL', $oFilter->ToOQL());
  2418. throw $e;
  2419. }
  2420. self::AddQueryTraceSelect($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sRes);
  2421. return $sRes;
  2422. }
  2423. protected static function MakeSelectStructure(DBObjectSearch $oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $aGroupByExpr = null)
  2424. {
  2425. // Hide objects that are not visible to the current user
  2426. //
  2427. if (!$oFilter->IsAllDataAllowed() && !$oFilter->IsDataFiltered())
  2428. {
  2429. $oVisibleObjects = UserRights::GetSelectFilter($oFilter->GetClass(), $oFilter->GetModifierProperties('UserRightsGetSelectFilter'));
  2430. if ($oVisibleObjects === false)
  2431. {
  2432. // Make sure this is a valid search object, saying NO for all
  2433. $oVisibleObjects = DBObjectSearch::FromEmptySet($oFilter->GetClass());
  2434. }
  2435. if (is_object($oVisibleObjects))
  2436. {
  2437. $oFilter->MergeWith($oVisibleObjects);
  2438. $oFilter->SetDataFiltered();
  2439. }
  2440. else
  2441. {
  2442. // should be true at this point, meaning that no additional filtering
  2443. // is required
  2444. }
  2445. }
  2446. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2447. //
  2448. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2449. // Create a unique cache id
  2450. //
  2451. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  2452. {
  2453. // Need to identify the query
  2454. $sOqlQuery = $oFilter->ToOql();
  2455. if (count($aModifierProperties))
  2456. {
  2457. array_multisort($aModifierProperties);
  2458. $sModifierProperties = json_encode($aModifierProperties);
  2459. }
  2460. else
  2461. {
  2462. $sModifierProperties = '';
  2463. }
  2464. $sRawId = $sOqlQuery.$sModifierProperties;
  2465. if (!is_null($aAttToLoad))
  2466. {
  2467. $sRawId .= json_encode($aAttToLoad);
  2468. }
  2469. if (!is_null($aGroupByExpr))
  2470. {
  2471. foreach($aGroupByExpr as $sAlias => $oExpr)
  2472. {
  2473. $sRawId .= 'g:'.$sAlias.'!'.$oExpr->Render();
  2474. }
  2475. }
  2476. $sRawId .= $bGetCount;
  2477. $sOqlId = md5($sRawId);
  2478. }
  2479. else
  2480. {
  2481. $sOqlQuery = "SELECTING... ".$oFilter->GetClass();
  2482. $sOqlId = "query id ? n/a";
  2483. }
  2484. // Query caching
  2485. //
  2486. if (self::$m_bQueryCacheEnabled)
  2487. {
  2488. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  2489. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  2490. // to use a hash (like md5) of the string as the key !
  2491. //
  2492. // Example of two queries that were found as similar by the hash array:
  2493. // 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
  2494. // and
  2495. // 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
  2496. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  2497. //
  2498. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  2499. {
  2500. // hit!
  2501. $oSelect = unserialize(serialize(self::$m_aQueryStructCache[$sOqlId]));
  2502. // Note: cloning is not enough because the subtree is made of objects
  2503. }
  2504. elseif (self::$m_bUseAPCCache)
  2505. {
  2506. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  2507. //
  2508. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-query-cache-'.$sOqlId;
  2509. $oKPI = new ExecutionKPI();
  2510. $result = apc_fetch($sOqlAPCCacheId);
  2511. $oKPI->ComputeStats('Query APC (fetch)', $sOqlQuery);
  2512. if (is_object($result))
  2513. {
  2514. $oSelect = $result;
  2515. self::$m_aQueryStructCache[$sOqlId] = $oSelect;
  2516. }
  2517. }
  2518. }
  2519. if (!isset($oSelect))
  2520. {
  2521. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties, $aGroupByExpr);
  2522. $oKPI = new ExecutionKPI();
  2523. $oSelect = self::MakeQuery($oBuild, $oFilter, $aAttToLoad, array(), true /* main query */);
  2524. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2525. $oSelect->SetSourceOQL($sOqlQuery);
  2526. if ($aGroupByExpr)
  2527. {
  2528. $aCols = $oBuild->m_oQBExpressions->GetGroupBy();
  2529. $oSelect->SetGroupBy($aCols);
  2530. $oSelect->SetSelect($aCols);
  2531. }
  2532. else
  2533. {
  2534. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2535. }
  2536. if (self::$m_bOptimizeQueries)
  2537. {
  2538. if ($bGetCount)
  2539. {
  2540. // Simplify the query if just getting the count
  2541. $oSelect->SetSelect(array());
  2542. }
  2543. $oBuild->m_oQBExpressions->GetMandatoryTables($aMandatoryTables);
  2544. $oSelect->OptimizeJoins($aMandatoryTables);
  2545. }
  2546. $oKPI->ComputeStats('MakeQuery (select)', $sOqlQuery);
  2547. if (self::$m_bQueryCacheEnabled)
  2548. {
  2549. if (self::$m_bUseAPCCache)
  2550. {
  2551. $oKPI = new ExecutionKPI();
  2552. apc_store($sOqlAPCCacheId, $oSelect, self::$m_iQueryCacheTTL);
  2553. $oKPI->ComputeStats('Query APC (store)', $sOqlQuery);
  2554. }
  2555. self::$m_aQueryStructCache[$sOqlId] = $oSelect->DeepClone();
  2556. }
  2557. }
  2558. // Join to an additional table, if required...
  2559. //
  2560. if ($aExtendedDataSpec != null)
  2561. {
  2562. $sTableAlias = '_extended_data_';
  2563. $aExtendedFields = array();
  2564. foreach($aExtendedDataSpec['fields'] as $sColumn)
  2565. {
  2566. $sColRef = $oFilter->GetClassAlias().'_extdata_'.$sColumn;
  2567. $aExtendedFields[$sColRef] = new FieldExpressionResolved($sColumn, $sTableAlias);
  2568. }
  2569. $oSelectExt = new SQLQuery($aExtendedDataSpec['table'], $sTableAlias, $aExtendedFields);
  2570. $oSelect->AddInnerJoin($oSelectExt, 'id', $aExtendedDataSpec['join_key'] /*, $sTableAlias*/);
  2571. }
  2572. return $oSelect;
  2573. }
  2574. protected static function AddQueryTraceSelect($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sSql)
  2575. {
  2576. if (self::$m_bTraceQueries)
  2577. {
  2578. $aQueryData = array(
  2579. 'type' => 'select',
  2580. 'filter' => $oFilter,
  2581. 'order_by' => $aOrderBy,
  2582. 'args' => $aArgs,
  2583. 'att_to_load' => $aAttToLoad,
  2584. 'extended_data_spec' => $aExtendedDataSpec,
  2585. 'limit_count' => $iLimitCount,
  2586. 'limit_start' => $iLimitStart,
  2587. 'is_count' => $bGetCount
  2588. );
  2589. $sOql = $oFilter->ToOQL(true, $aArgs);
  2590. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  2591. }
  2592. }
  2593. protected static function AddQueryTraceGroupBy($oFilter, $aArgs, $aGroupByExpr, $sSql)
  2594. {
  2595. if (self::$m_bTraceQueries)
  2596. {
  2597. $aQueryData = array(
  2598. 'type' => 'group_by',
  2599. 'filter' => $oFilter,
  2600. 'args' => $aArgs,
  2601. 'group_by_expr' => $aGroupByExpr
  2602. );
  2603. $sOql = $oFilter->ToOQL(true, $aArgs);
  2604. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  2605. }
  2606. }
  2607. protected static function AddQueryTrace($aQueryData, $sOql, $sSql)
  2608. {
  2609. if (self::$m_bTraceQueries)
  2610. {
  2611. $sQueryId = md5(serialize($aQueryData));
  2612. $sMySQLQueryId = md5($sSql);
  2613. if(!isset(self::$m_aQueriesLog[$sQueryId]))
  2614. {
  2615. self::$m_aQueriesLog[$sQueryId]['data'] = serialize($aQueryData);
  2616. self::$m_aQueriesLog[$sQueryId]['oql'] = $sOql;
  2617. self::$m_aQueriesLog[$sQueryId]['hits'] = 1;
  2618. }
  2619. else
  2620. {
  2621. self::$m_aQueriesLog[$sQueryId]['hits']++;
  2622. }
  2623. if(!isset(self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]))
  2624. {
  2625. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['sql'] = $sSql;
  2626. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count'] = 1;
  2627. $iTableCount = count(CMDBSource::ExplainQuery($sSql));
  2628. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['table_count'] = $iTableCount;
  2629. }
  2630. else
  2631. {
  2632. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count']++;
  2633. }
  2634. }
  2635. }
  2636. public static function RecordQueryTrace()
  2637. {
  2638. if (!self::$m_bTraceQueries) return;
  2639. $iOqlCount = count(self::$m_aQueriesLog);
  2640. $iSqlCount = 0;
  2641. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2642. {
  2643. $iSqlCount += $aOqlData['hits'];
  2644. }
  2645. $sHtml = "<h2>Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount</h2>\n";
  2646. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2647. {
  2648. $sOql = $aOqlData['oql'];
  2649. $sHits = $aOqlData['hits'];
  2650. $sHtml .= "<p><b>$sHits</b> hits for OQL query: $sOql</p>\n";
  2651. $sHtml .= "<ul id=\"ClassesRelationships\" class=\"treeview\">\n";
  2652. foreach($aOqlData['queries'] as $aSqlData)
  2653. {
  2654. $sQuery = $aSqlData['sql'];
  2655. $sSqlHits = $aSqlData['count'];
  2656. $iTableCount = $aSqlData['table_count'];
  2657. $sHtml .= "<li><b>$sSqlHits</b> hits for SQL ($iTableCount tables): <pre style=\"font-size:60%\">$sQuery</pre></li>\n";
  2658. }
  2659. $sHtml .= "</ul>\n";
  2660. }
  2661. $sLogFile = 'queries.latest';
  2662. file_put_contents(APPROOT.'data/'.$sLogFile.'.html', $sHtml);
  2663. $sLog = "<?php\n\$aQueriesLog = ".var_export(self::$m_aQueriesLog, true).";";
  2664. file_put_contents(APPROOT.'data/'.$sLogFile.'.log', $sLog);
  2665. // Cumulate the queries
  2666. $sAllQueries = APPROOT.'data/queries.log';
  2667. if (file_exists($sAllQueries))
  2668. {
  2669. // Merge the new queries into the existing log
  2670. include($sAllQueries);
  2671. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2672. {
  2673. if (!array_key_exists($sQueryId, $aQueriesLog))
  2674. {
  2675. $aQueriesLog[$sQueryId] = $aOqlData;
  2676. }
  2677. }
  2678. }
  2679. else
  2680. {
  2681. $aQueriesLog = self::$m_aQueriesLog;
  2682. }
  2683. $sLog = "<?php\n\$aQueriesLog = ".var_export($aQueriesLog, true).";";
  2684. file_put_contents($sAllQueries, $sLog);
  2685. }
  2686. protected static function MakeModifierProperties($oFilter)
  2687. {
  2688. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2689. //
  2690. $aModifierProperties = array();
  2691. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  2692. {
  2693. // Lowest precedence: the application context
  2694. $aPluginProps = ApplicationContext::GetPluginProperties($sPluginClass);
  2695. // Highest precedence: programmatically specified (or OQL)
  2696. foreach($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value)
  2697. {
  2698. $aPluginProps[$sProp] = $value;
  2699. }
  2700. if (count($aPluginProps) > 0)
  2701. {
  2702. $aModifierProperties[$sPluginClass] = $aPluginProps;
  2703. }
  2704. }
  2705. return $aModifierProperties;
  2706. }
  2707. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  2708. {
  2709. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2710. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties);
  2711. $oSelect = self::MakeQuery($oBuild, $oFilter, null, array(), true /* main query */);
  2712. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2713. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2714. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2715. return $oSelect->RenderDelete($aScalarArgs);
  2716. }
  2717. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  2718. {
  2719. // $aValues is an array of $sAttCode => $value
  2720. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2721. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties);
  2722. $oSelect = self::MakeQuery($oBuild, $oFilter, null, $aValues, true /* main query */);
  2723. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2724. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2725. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2726. return $oSelect->RenderUpdate($aScalarArgs);
  2727. }
  2728. private static function MakeQuery(&$oBuild, DBObjectSearch $oFilter, $aAttToLoad = null, $aValues = array(), $bIsMainQueryUNUSED = false)
  2729. {
  2730. // Note: query class might be different than the class of the filter
  2731. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  2732. $sClass = $oFilter->GetFirstJoinedClass();
  2733. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  2734. $bIsOnQueriedClass = array_key_exists($sClassAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  2735. self::DbgTrace("Entering: ".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  2736. $sRootClass = self::GetRootClass($sClass);
  2737. $sKeyField = self::DBGetKey($sClass);
  2738. if ($bIsOnQueriedClass)
  2739. {
  2740. // default to the whole list of attributes + the very std id/finalclass
  2741. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.'id', new FieldExpression('id', $sClassAlias));
  2742. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  2743. {
  2744. $aAttList = self::ListAttributeDefs($sClass);
  2745. }
  2746. else
  2747. {
  2748. $aAttList = $aAttToLoad[$sClassAlias];
  2749. }
  2750. foreach ($aAttList as $sAttCode => $oAttDef)
  2751. {
  2752. if (!$oAttDef->IsScalar()) continue;
  2753. // keep because it can be used for sorting - if (!$oAttDef->LoadInObject()) continue;
  2754. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  2755. {
  2756. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.$sAttCode.$sColId, new FieldExpression($sAttCode.$sColId, $sClassAlias));
  2757. }
  2758. }
  2759. // Transform the full text condition into additional condition expression
  2760. $aFullText = $oFilter->GetCriteria_FullText();
  2761. if (count($aFullText) > 0)
  2762. {
  2763. $aFullTextFields = array();
  2764. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2765. {
  2766. if (!$oAttDef->IsScalar()) continue;
  2767. if ($oAttDef->IsExternalKey()) continue;
  2768. $aFullTextFields[] = new FieldExpression($sAttCode, $sClassAlias);
  2769. }
  2770. $oTextFields = new CharConcatWSExpression(' ', $aFullTextFields);
  2771. foreach($aFullText as $sFTNeedle)
  2772. {
  2773. $oNewCond = new BinaryExpression($oTextFields, 'LIKE', new ScalarExpression("%$sFTNeedle%"));
  2774. $oBuild->m_oQBExpressions->AddCondition($oNewCond);
  2775. }
  2776. }
  2777. }
  2778. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  2779. $aExpectedAtts = array(); // array of (attcode => fieldexpression)
  2780. //echo "<p>".__LINE__.": GetUnresolvedFields($sClassAlias, ...)</p>\n";
  2781. $oBuild->m_oQBExpressions->GetUnresolvedFields($sClassAlias, $aExpectedAtts);
  2782. // Compute a clear view of required joins (from the current class)
  2783. // Build the list of external keys:
  2784. // -> ext keys required by an explicit join
  2785. // -> ext keys mentionned in a 'pointing to' condition
  2786. // -> ext keys required for an external field
  2787. // -> ext keys required for a friendly name
  2788. //
  2789. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  2790. //
  2791. // Optimization: could be partially computed once for all (cached) ?
  2792. //
  2793. if ($bIsOnQueriedClass)
  2794. {
  2795. // Get all Ext keys for the queried class (??)
  2796. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  2797. {
  2798. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2799. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  2800. }
  2801. }
  2802. // Get all Ext keys used by the filter
  2803. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $aPointingTo)
  2804. {
  2805. if (array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  2806. {
  2807. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2808. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  2809. }
  2810. }
  2811. $aFNJoinAlias = array(); // array of (subclass => alias)
  2812. if (array_key_exists('friendlyname', $aExpectedAtts))
  2813. {
  2814. // To optimize: detect a restriction on child classes in the condition expression
  2815. // e.g. SELECT FunctionalCI WHERE finalclass IN ('Server', 'VirtualMachine')
  2816. $oNameExpression = self::GetExtendedNameExpression($sClass);
  2817. $aNameFields = array();
  2818. $oNameExpression->GetUnresolvedFields('', $aNameFields);
  2819. $aTranslateNameFields = array();
  2820. foreach($aNameFields as $sSubClass => $aFields)
  2821. {
  2822. foreach($aFields as $sAttCode => $oField)
  2823. {
  2824. $oAttDef = self::GetAttributeDef($sSubClass, $sAttCode);
  2825. if ($oAttDef->IsExternalKey())
  2826. {
  2827. $sClassOfAttribute = self::$m_aAttribOrigins[$sSubClass][$sAttCode];
  2828. $aExtKeys[$sClassOfAttribute][$sAttCode] = array();
  2829. }
  2830. elseif ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  2831. {
  2832. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2833. $sClassOfAttribute = self::$m_aAttribOrigins[$sSubClass][$sKeyAttCode];
  2834. $aExtKeys[$sClassOfAttribute][$sKeyAttCode][$sAttCode] = $oAttDef;
  2835. }
  2836. else
  2837. {
  2838. $sClassOfAttribute = self::GetAttributeOrigin($sSubClass, $sAttCode);
  2839. }
  2840. if (self::IsParentClass($sClassOfAttribute, $sClass))
  2841. {
  2842. // The attribute is part of the standard query
  2843. //
  2844. $sAliasForAttribute = $sClassAlias;
  2845. }
  2846. else
  2847. {
  2848. // The attribute will be available from an additional outer join
  2849. // For each subclass (table) one single join is enough
  2850. //
  2851. if (!array_key_exists($sClassOfAttribute, $aFNJoinAlias))
  2852. {
  2853. $sAliasForAttribute = $oBuild->GenerateClassAlias($sClassAlias.'_fn_'.$sClassOfAttribute, $sClassOfAttribute);
  2854. $aFNJoinAlias[$sClassOfAttribute] = $sAliasForAttribute;
  2855. }
  2856. else
  2857. {
  2858. $sAliasForAttribute = $aFNJoinAlias[$sClassOfAttribute];
  2859. }
  2860. }
  2861. $aTranslateNameFields[$sSubClass][$sAttCode] = new FieldExpression($sAttCode, $sAliasForAttribute);
  2862. }
  2863. }
  2864. $oNameExpression = $oNameExpression->Translate($aTranslateNameFields, false);
  2865. $aTranslateNow = array();
  2866. $aTranslateNow[$sClassAlias]['friendlyname'] = $oNameExpression;
  2867. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  2868. }
  2869. // Add the ext fields used in the select (eventually adds an external key)
  2870. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2871. {
  2872. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  2873. {
  2874. if (array_key_exists($sAttCode, $aExpectedAtts))
  2875. {
  2876. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2877. if ($sKeyAttCode != 'id')
  2878. {
  2879. // Add the external attribute
  2880. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2881. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  2882. }
  2883. }
  2884. }
  2885. }
  2886. // First query built upon on the leaf (ie current) class
  2887. //
  2888. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  2889. if (self::HasTable($sClass))
  2890. {
  2891. $oSelectBase = self::MakeQuerySingleTable($oBuild, $oFilter, $sClass, $aExtKeys, $aValues);
  2892. }
  2893. else
  2894. {
  2895. $oSelectBase = null;
  2896. // As the join will not filter on the expected classes, we have to specify it explicitely
  2897. $sExpectedClasses = implode("', '", self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  2898. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  2899. $oBuild->m_oQBExpressions->AddCondition($oFinalClassRestriction);
  2900. }
  2901. // Then we join the queries of the eventual parent classes (compound model)
  2902. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  2903. {
  2904. if (!self::HasTable($sParentClass)) continue;
  2905. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  2906. $oSelectParentTable = self::MakeQuerySingleTable($oBuild, $oFilter, $sParentClass, $aExtKeys, $aValues);
  2907. if (is_null($oSelectBase))
  2908. {
  2909. $oSelectBase = $oSelectParentTable;
  2910. }
  2911. else
  2912. {
  2913. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  2914. }
  2915. }
  2916. // Filter on objects referencing me
  2917. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  2918. {
  2919. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  2920. {
  2921. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  2922. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  2923. //self::DbgTrace($oForeignFilter);
  2924. //self::DbgTrace($oForeignFilter->ToOQL());
  2925. //self::DbgTrace($oSelectForeign);
  2926. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  2927. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  2928. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sForeignKeyAttCode, $sForeignClassAlias));
  2929. if ($oForeignKeyAttDef instanceof AttributeObjectKey)
  2930. {
  2931. $sClassAttCode = $oForeignKeyAttDef->Get('class_attcode');
  2932. // Add the condition: `$sForeignClassAlias`.$sClassAttCode IN (subclasses of $sClass')
  2933. $oClassListExpr = ListExpression::FromScalars(self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  2934. $oClassExpr = new FieldExpression($sClassAttCode, $sForeignClassAlias);
  2935. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  2936. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  2937. }
  2938. $oSelectForeign = self::MakeQuery($oBuild, $oForeignFilter, $aAttToLoad);
  2939. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  2940. $sForeignKeyTable = $oJoinExpr->GetParent();
  2941. $sForeignKeyColumn = $oJoinExpr->GetName();
  2942. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  2943. }
  2944. }
  2945. // Filter on related objects
  2946. //
  2947. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  2948. {
  2949. $oSubFilter = $aCritInfo['flt'];
  2950. $sRelCode = $aCritInfo['relcode'];
  2951. $iMaxDepth = $aCritInfo['maxdepth'];
  2952. // Get the starting point objects
  2953. $oStartSet = new CMDBObjectSet($oSubFilter);
  2954. // Get the objects related to those objects... recursively...
  2955. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  2956. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  2957. // #@# todo - related objects and expressions...
  2958. // Create condition
  2959. if (count($aRestriction) > 0)
  2960. {
  2961. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  2962. }
  2963. else
  2964. {
  2965. // Quick N'dirty -> generate an empty set
  2966. $oSelectBase->AddCondition('false');
  2967. }
  2968. }
  2969. // Additional JOINS for Friendly names
  2970. //
  2971. foreach ($aFNJoinAlias as $sSubClass => $sSubClassAlias)
  2972. {
  2973. $oSubClassFilter = new DBObjectSearch($sSubClass, $sSubClassAlias);
  2974. $oSelectFN = self::MakeQuerySingleTable($oBuild, $oSubClassFilter, $sSubClass, $aExtKeys, array());
  2975. $oSelectBase->AddLeftJoin($oSelectFN, $sKeyField, self::DBGetKey($sSubClass));
  2976. }
  2977. // That's all... cross fingers and we'll get some working query
  2978. //MyHelpers::var_dump_html($oSelectBase, true);
  2979. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  2980. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  2981. return $oSelectBase;
  2982. }
  2983. protected static function MakeQuerySingleTable(&$oBuild, $oFilter, $sTableClass, $aExtKeys, $aValues)
  2984. {
  2985. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  2986. //echo "MAKEQUERY($sTableClass)-liste des clefs externes($sTableClass): <pre>".print_r($aExtKeys, true)."</pre><br/>\n";
  2987. // Prepare the query for a single table (compound objects)
  2988. // Ignores the items (attributes/filters) that are not on the target table
  2989. // Perform an (inner or left) join for every external key (and specify the expected fields)
  2990. //
  2991. // Returns an SQLQuery
  2992. //
  2993. $sTargetClass = $oFilter->GetFirstJoinedClass();
  2994. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  2995. $sTable = self::DBGetTable($sTableClass);
  2996. $sTableAlias = $oBuild->GenerateTableAlias($sTargetAlias.'_'.$sTable, $sTable);
  2997. $aTranslation = array();
  2998. $aExpectedAtts = array();
  2999. $oBuild->m_oQBExpressions->GetUnresolvedFields($sTargetAlias, $aExpectedAtts);
  3000. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  3001. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  3002. // 1 - SELECT and UPDATE
  3003. //
  3004. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  3005. //
  3006. $aUpdateValues = array();
  3007. // 1/a - Get the key and friendly name
  3008. //
  3009. // We need one pkey to be the key, let's take the first one available
  3010. $oSelectedIdField = null;
  3011. $oIdField = new FieldExpressionResolved(self::DBGetKey($sTableClass), $sTableAlias);
  3012. $aTranslation[$sTargetAlias]['id'] = $oIdField;
  3013. if ($bIsOnQueriedClass)
  3014. {
  3015. // Add this field to the list of queried fields (required for the COUNT to work fine)
  3016. $oSelectedIdField = $oIdField;
  3017. }
  3018. // 1/b - Get the other attributes
  3019. //
  3020. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  3021. {
  3022. // Skip this attribute if not defined in this table
  3023. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  3024. // Skip this attribute if not made of SQL columns
  3025. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  3026. // Update...
  3027. //
  3028. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  3029. {
  3030. assert ($oAttDef->IsDirectField());
  3031. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  3032. {
  3033. $aUpdateValues[$sColumn] = $sValue;
  3034. }
  3035. }
  3036. }
  3037. // 2 - The SQL query, for this table only
  3038. //
  3039. $oSelectBase = new SQLQuery($sTable, $sTableAlias, array(), $bIsOnQueriedClass, $aUpdateValues, $oSelectedIdField);
  3040. // 3 - Resolve expected expressions (translation table: alias.attcode => table.column)
  3041. //
  3042. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  3043. {
  3044. // Skip this attribute if not defined in this table
  3045. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  3046. // Select...
  3047. //
  3048. if ($oAttDef->IsExternalField())
  3049. {
  3050. // skip, this will be handled in the joined tables (done hereabove)
  3051. }
  3052. else
  3053. {
  3054. //echo "<p>MakeQuerySingleTable: Field $sAttCode is part of the table $sTable (named: $sTableAlias)</p>";
  3055. // standard field, or external key
  3056. // add it to the output
  3057. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  3058. {
  3059. if (array_key_exists($sAttCode.$sColId, $aExpectedAtts))
  3060. {
  3061. $oFieldSQLExp = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  3062. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  3063. {
  3064. $oFieldSQLExp = $oQueryModifier->GetFieldExpression($oBuild, $sTargetClass, $sAttCode, $sColId, $oFieldSQLExp, $oSelectBase);
  3065. }
  3066. $aTranslation[$sTargetAlias][$sAttCode.$sColId] = $oFieldSQLExp;
  3067. }
  3068. }
  3069. }
  3070. }
  3071. //echo "MAKEQUERY- Classe $sTableClass<br/>\n";
  3072. // 4 - The external keys -> joins...
  3073. //
  3074. $aAllPointingTo = $oFilter->GetCriteria_PointingTo();
  3075. if (array_key_exists($sTableClass, $aExtKeys))
  3076. {
  3077. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  3078. {
  3079. $oKeyAttDef = self::GetAttributeDef($sTableClass, $sKeyAttCode);
  3080. $aPointingTo = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  3081. //echo "MAKEQUERY-Cle '$sKeyAttCode'<br/>\n";
  3082. if (!array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  3083. {
  3084. //echo "MAKEQUERY-Ajoutons l'operateur TREE_OPERATOR_EQUALS pour $sKeyAttCode<br/>\n";
  3085. // The join was not explicitely defined in the filter,
  3086. // we need to do it now
  3087. $sKeyClass = $oKeyAttDef->GetTargetClass();
  3088. $sKeyClassAlias = $oBuild->GenerateClassAlias($sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  3089. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  3090. $aAllPointingTo[$sKeyAttCode][TREE_OPERATOR_EQUALS][$sKeyClassAlias] = $oExtFilter;
  3091. }
  3092. }
  3093. }
  3094. //echo "MAKEQUERY-liste des clefs de jointure: <pre>".print_r(array_keys($aAllPointingTo), true)."</pre><br/>\n";
  3095. foreach ($aAllPointingTo as $sKeyAttCode => $aPointingTo)
  3096. {
  3097. foreach($aPointingTo as $iOperatorCode => $aFilter)
  3098. {
  3099. foreach($aFilter as $oExtFilter)
  3100. {
  3101. if (!MetaModel::IsValidAttCode($sTableClass, $sKeyAttCode)) continue; // Not defined in the class, skip it
  3102. // The aliases should not conflict because normalization occured while building the filter
  3103. $oKeyAttDef = self::GetAttributeDef($sTableClass, $sKeyAttCode);
  3104. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  3105. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  3106. //echo "MAKEQUERY-$sTableClass::$sKeyAttCode Foreach PointingTo($iOperatorCode) <span style=\"color:red\">$sKeyClass (alias:$sKeyClassAlias)</span><br/>\n";
  3107. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  3108. //echo "MAKEQUERY-array_key_exists($sTableClass, \$aExtKeys)<br/>\n";
  3109. if ($iOperatorCode == TREE_OPERATOR_EQUALS)
  3110. {
  3111. if (array_key_exists($sTableClass, $aExtKeys) && array_key_exists($sKeyAttCode, $aExtKeys[$sTableClass]))
  3112. {
  3113. // Specify expected attributes for the target class query
  3114. // ... and use the current alias !
  3115. $aTranslateNow = array(); // Translation for external fields - must be performed before the join is done (recursion...)
  3116. foreach($aExtKeys[$sTableClass][$sKeyAttCode] as $sAttCode => $oAtt)
  3117. {
  3118. //echo "MAKEQUERY aExtKeys[$sTableClass][$sKeyAttCode] => $sAttCode-oAtt: <pre>".print_r($oAtt, true)."</pre><br/>\n";
  3119. if ($oAtt instanceof AttributeFriendlyName)
  3120. {
  3121. // Note: for a given ext key, there is one single attribute "friendly name"
  3122. $aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);
  3123. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);</b></p>\n";
  3124. }
  3125. else
  3126. {
  3127. $sExtAttCode = $oAtt->GetExtAttCode();
  3128. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  3129. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  3130. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  3131. {
  3132. $aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);
  3133. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);</b></p>\n";
  3134. }
  3135. //echo "<p><b>ExtAttr2: $sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</b></p>\n";
  3136. }
  3137. }
  3138. if ($oKeyAttDef instanceof AttributeObjectKey)
  3139. {
  3140. // Add the condition: `$sTargetAlias`.$sClassAttCode IN (subclasses of $sKeyClass')
  3141. $sClassAttCode = $oKeyAttDef->Get('class_attcode');
  3142. $oClassAttDef = self::GetAttributeDef($sTargetClass, $sClassAttCode);
  3143. foreach ($oClassAttDef->GetSQLExpressions() as $sColID => $sSQLExpr)
  3144. {
  3145. $aTranslateNow[$sTargetAlias][$sClassAttCode.$sColId] = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  3146. }
  3147. $oClassListExpr = ListExpression::FromScalars(self::EnumChildClasses($sKeyClass, ENUM_CHILD_CLASSES_ALL));
  3148. $oClassExpr = new FieldExpression($sClassAttCode, $sTargetAlias);
  3149. $oClassRestriction = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  3150. $oBuild->m_oQBExpressions->AddCondition($oClassRestriction);
  3151. }
  3152. // Translate prior to recursing
  3153. //
  3154. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."\n".print_r($aTranslateNow, true)."</pre></p>\n";
  3155. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  3156. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  3157. //echo "<p>External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()/p>\n";
  3158. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  3159. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression('id', $sKeyClassAlias));
  3160. //echo "<p>Recursive MakeQuery ".__LINE__.": <pre>\n".print_r($oBuild->GetRootFilter()->GetSelectedClasses(), true)."</pre></p>\n";
  3161. $oSelectExtKey = self::MakeQuery($oBuild, $oExtFilter);
  3162. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  3163. $sExternalKeyTable = $oJoinExpr->GetParent();
  3164. $sExternalKeyField = $oJoinExpr->GetName();
  3165. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3166. $sLocalKeyField = current($aCols); // get the first column for an external key
  3167. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  3168. if ($oKeyAttDef->IsNullAllowed())
  3169. {
  3170. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  3171. }
  3172. else
  3173. {
  3174. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  3175. }
  3176. }
  3177. }
  3178. elseif(self::$m_aAttribOrigins[$sKeyClass][$sKeyAttCode] == $sTableClass)
  3179. {
  3180. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sKeyAttCode, $sKeyClassAlias));
  3181. $oSelectExtKey = self::MakeQuery($oBuild, $oExtFilter);
  3182. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  3183. //echo "MAKEQUERY-PopJoinField pour $sKeyAttCode, $sKeyClassAlias: <pre>".print_r($oJoinExpr, true)."</pre><br/>\n";
  3184. $sExternalKeyTable = $oJoinExpr->GetParent();
  3185. $sExternalKeyField = $oJoinExpr->GetName();
  3186. $sLeftIndex = $sExternalKeyField.'_left'; // TODO use GetSQLLeft()
  3187. $sRightIndex = $sExternalKeyField.'_right'; // TODO use GetSQLRight()
  3188. $LocalKeyLeft = $oKeyAttDef->GetSQLLeft();
  3189. $LocalKeyRight = $oKeyAttDef->GetSQLRight();
  3190. //echo "MAKEQUERY-LocalKeyLeft pour $sKeyAttCode => $LocalKeyLeft<br/>\n";
  3191. $oSelectBase->AddInnerJoinTree($oSelectExtKey, $LocalKeyLeft, $LocalKeyRight, $sLeftIndex, $sRightIndex, $sExternalKeyTable, $iOperatorCode);
  3192. }
  3193. }
  3194. }
  3195. }
  3196. // Translate the selected columns
  3197. //
  3198. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  3199. $oBuild->m_oQBExpressions->Translate($aTranslation, false);
  3200. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  3201. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  3202. return $oSelectBase;
  3203. }
  3204. /**
  3205. * Special processing for the hierarchical keys stored as nested sets
  3206. * @param $iId integer The identifier of the parent
  3207. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  3208. * @param $stable string The name of the database table containing the hierarchical key
  3209. */
  3210. public static function HKInsertChildUnder($iId, $oAttDef, $sTable)
  3211. {
  3212. // Get the parent id.right value
  3213. if ($iId == 0)
  3214. {
  3215. // No parent, insert completely at the right of the tree
  3216. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  3217. $aRes = CMDBSource::QueryToArray($sSQL);
  3218. if (count($aRes) == 0)
  3219. {
  3220. $iMyRight = 1;
  3221. }
  3222. else
  3223. {
  3224. $iMyRight = $aRes[0]['max']+1;
  3225. }
  3226. }
  3227. else
  3228. {
  3229. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".$iId;
  3230. $iMyRight = CMDBSource::QueryToScalar($sSQL);
  3231. $sSQLUpdateRight = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + 2 WHERE `".$oAttDef->GetSQLRight()."` >= $iMyRight";
  3232. CMDBSource::Query($sSQLUpdateRight);
  3233. $sSQLUpdateLeft = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + 2 WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  3234. CMDBSource::Query($sSQLUpdateLeft);
  3235. }
  3236. return array($oAttDef->GetSQLRight() => $iMyRight+1, $oAttDef->GetSQLLeft() => $iMyRight);
  3237. }
  3238. /**
  3239. * Special processing for the hierarchical keys stored as nested sets: temporary remove the branch
  3240. * @param $iId integer The identifier of the parent
  3241. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  3242. * @param $sTable string The name of the database table containing the hierarchical key
  3243. */
  3244. public static function HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable)
  3245. {
  3246. $iDelta = $iMyRight - $iMyLeft + 1;
  3247. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iMyLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iMyLeft - `".$oAttDef->GetSQLLeft();
  3248. $sSQL .= "` WHERE `".$oAttDef->GetSQLLeft()."`> $iMyLeft AND `".$oAttDef->GetSQLRight()."`< $iMyRight";
  3249. CMDBSource::Query($sSQL);
  3250. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` - $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  3251. CMDBSource::Query($sSQL);
  3252. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` - $iDelta WHERE `".$oAttDef->GetSQLRight()."` > $iMyRight";
  3253. CMDBSource::Query($sSQL);
  3254. }
  3255. /**
  3256. * Special processing for the hierarchical keys stored as nested sets: replug the temporary removed branch
  3257. * @param $iId integer The identifier of the parent
  3258. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  3259. * @param $sTable string The name of the database table containing the hierarchical key
  3260. */
  3261. public static function HKReplugBranch($iNewLeft, $iNewRight, $oAttDef, $sTable)
  3262. {
  3263. $iDelta = $iNewRight - $iNewLeft + 1;
  3264. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iNewLeft";
  3265. CMDBSource::Query($sSQL);
  3266. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + $iDelta WHERE `".$oAttDef->GetSQLRight()."` >= $iNewLeft";
  3267. CMDBSource::Query($sSQL);
  3268. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iNewLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iNewLeft - `".$oAttDef->GetSQLLeft()."` WHERE `".$oAttDef->GetSQLRight()."`< 0";
  3269. CMDBSource::Query($sSQL);
  3270. }
  3271. /**
  3272. * Check (and updates if needed) the hierarchical keys
  3273. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  3274. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  3275. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  3276. */
  3277. public static function CheckHKeys($bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  3278. {
  3279. $bChangeNeeded = false;
  3280. foreach (self::GetClasses() as $sClass)
  3281. {
  3282. if (!self::HasTable($sClass)) continue;
  3283. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3284. {
  3285. // Check (once) all the attributes that are hierarchical keys
  3286. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey())
  3287. {
  3288. if ($bVerbose)
  3289. {
  3290. echo "The attribute $sAttCode from $sClass is a hierarchical key.\n";
  3291. }
  3292. $bResult = self::HKInit($sClass, $sAttCode, $bDiagnosticsOnly, $bVerbose, $bForceComputation);
  3293. $bChangeNeeded |= $bResult;
  3294. if ($bVerbose && !$bResult)
  3295. {
  3296. echo "Ok, the attribute $sAttCode from class $sClass seems up to date.\n";
  3297. }
  3298. }
  3299. }
  3300. }
  3301. return $bChangeNeeded;
  3302. }
  3303. /**
  3304. * Initializes (i.e converts) a hierarchy stored using a 'parent_id' external key
  3305. * into a hierarchy stored with a HierarchicalKey, by initializing the _left and _right values
  3306. * to correspond to the existing hierarchy in the database
  3307. * @param $sClass string Name of the class to process
  3308. * @param $sAttCode string Code of the attribute to process
  3309. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  3310. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  3311. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  3312. * @return true if an update is needed (diagnostics only) / was performed
  3313. */
  3314. public static function HKInit($sClass, $sAttCode, $bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  3315. {
  3316. $idx = 1;
  3317. $bUpdateNeeded = $bForceComputation;
  3318. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  3319. $sTable = self::DBGetTable($sClass, $sAttCode);
  3320. if ($oAttDef->IsHierarchicalKey())
  3321. {
  3322. // Check if some values already exist in the table for the _right value, if so, do nothing
  3323. $sRight = $oAttDef->GetSQLRight();
  3324. $sSQL = "SELECT MAX(`$sRight`) AS MaxRight FROM `$sTable`";
  3325. $iMaxRight = CMDBSource::QueryToScalar($sSQL);
  3326. $sSQL = "SELECT COUNT(*) AS Count FROM `$sTable`"; // Note: COUNT(field) returns zero if the given field contains only NULLs
  3327. $iCount = CMDBSource::QueryToScalar($sSQL);
  3328. if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0))
  3329. {
  3330. $bUpdateNeeded = true;
  3331. if ($bVerbose)
  3332. {
  3333. echo "The table '$sTable' must be updated to compute the fields $sRight and ".$oAttDef->GetSQLLeft()."\n";
  3334. }
  3335. }
  3336. if ($bForceComputation && !$bDiagnosticsOnly)
  3337. {
  3338. echo "Rebuilding the fields $sRight and ".$oAttDef->GetSQLLeft()." from table '$sTable'...\n";
  3339. }
  3340. if ($bUpdateNeeded && !$bDiagnosticsOnly)
  3341. {
  3342. try
  3343. {
  3344. CMDBSource::Query('START TRANSACTION');
  3345. self::HKInitChildren($sTable, $sAttCode, $oAttDef, 0, $idx);
  3346. CMDBSource::Query('COMMIT');
  3347. if ($bVerbose)
  3348. {
  3349. echo "Ok, table '$sTable' successfully updated.\n";
  3350. }
  3351. }
  3352. catch(Exception $e)
  3353. {
  3354. CMDBSource::Query('ROLLBACK');
  3355. throw new Exception("An error occured (".$e->getMessage().") while initializing the hierarchy for ($sClass, $sAttCode). The database was not modified.");
  3356. }
  3357. }
  3358. }
  3359. return $bUpdateNeeded;
  3360. }
  3361. /**
  3362. * Recursive helper function called by HKInit
  3363. */
  3364. protected static function HKInitChildren($sTable, $sAttCode, $oAttDef, $iId, &$iCurrIndex)
  3365. {
  3366. $sSQL = "SELECT id FROM `$sTable` WHERE `$sAttCode` = $iId";
  3367. $aRes = CMDBSource::QueryToArray($sSQL);
  3368. $aTree = array();
  3369. $sLeft = $oAttDef->GetSQLLeft();
  3370. $sRight = $oAttDef->GetSQLRight();
  3371. foreach($aRes as $aValues)
  3372. {
  3373. $iChildId = $aValues['id'];
  3374. $iLeft = $iCurrIndex++;
  3375. $aChildren = self::HKInitChildren($sTable, $sAttCode, $oAttDef, $iChildId, $iCurrIndex);
  3376. $iRight = $iCurrIndex++;
  3377. $sSQL = "UPDATE `$sTable` SET `$sLeft` = $iLeft, `$sRight` = $iRight WHERE id= $iChildId";
  3378. CMDBSource::Query($sSQL);
  3379. }
  3380. }
  3381. public static function CheckDataSources($bDiagnostics, $bVerbose)
  3382. {
  3383. $sOQL = 'SELECT SynchroDataSource';
  3384. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  3385. $bFixNeeded = false;
  3386. if ($bVerbose && $oSet->Count() == 0)
  3387. {
  3388. echo "There are no Data Sources in the database.\n";
  3389. }
  3390. while($oSource = $oSet->Fetch())
  3391. {
  3392. if ($bVerbose)
  3393. {
  3394. echo "Checking Data Source '".$oSource->GetName()."'...\n";
  3395. $bFixNeeded = $bFixNeeded | $oSource->CheckDBConsistency($bDiagnostics, $bVerbose);
  3396. }
  3397. }
  3398. if (!$bFixNeeded && $bVerbose)
  3399. {
  3400. echo "Ok.\n";
  3401. }
  3402. return $bFixNeeded;
  3403. }
  3404. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  3405. {
  3406. if (!array_key_exists($sNewName, $aAliases))
  3407. {
  3408. $aAliases[$sNewName] = $sRealName;
  3409. return $sNewName;
  3410. }
  3411. for ($i = 1 ; $i < 100 ; $i++)
  3412. {
  3413. $sAnAlias = $sNewName.$i;
  3414. if (!array_key_exists($sAnAlias, $aAliases))
  3415. {
  3416. // Create that new alias
  3417. $aAliases[$sAnAlias] = $sRealName;
  3418. return $sAnAlias;
  3419. }
  3420. }
  3421. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  3422. }
  3423. public static function CheckDefinitions($bExitOnError = true)
  3424. {
  3425. if (count(self::GetClasses()) == 0)
  3426. {
  3427. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  3428. }
  3429. $aErrors = array();
  3430. $aSugFix = array();
  3431. foreach (self::GetClasses() as $sClass)
  3432. {
  3433. $sTable = self::DBGetTable($sClass);
  3434. $sTableLowercase = strtolower($sTable);
  3435. if ($sTableLowercase != $sTable)
  3436. {
  3437. $aErrors[$sClass][] = "Table name '".$sTable."' has upper case characters. You might encounter issues when moving your installation between Linux and Windows.";
  3438. $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.";
  3439. }
  3440. $aNameSpec = self::GetNameSpec($sClass);
  3441. foreach($aNameSpec[1] as $i => $sAttCode)
  3442. {
  3443. if(!self::IsValidAttCode($sClass, $sAttCode))
  3444. {
  3445. $aErrors[$sClass][] = "Unknown attribute code '".$sAttCode."' for the name definition";
  3446. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  3447. }
  3448. }
  3449. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  3450. {
  3451. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  3452. {
  3453. $aErrors[$sClass][] = "Unknown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  3454. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  3455. }
  3456. }
  3457. $bHasWritableAttribute = false;
  3458. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3459. {
  3460. // It makes no sense to check the attributes again and again in the subclasses
  3461. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3462. if ($oAttDef->IsExternalKey())
  3463. {
  3464. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  3465. {
  3466. $aErrors[$sClass][] = "Unknown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  3467. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  3468. }
  3469. }
  3470. elseif ($oAttDef->IsExternalField())
  3471. {
  3472. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  3473. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  3474. {
  3475. $aErrors[$sClass][] = "Unknown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  3476. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  3477. }
  3478. else
  3479. {
  3480. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  3481. $sTargetClass = $oKeyAttDef->GetTargetClass();
  3482. $sExtAttCode = $oAttDef->GetExtAttCode();
  3483. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  3484. {
  3485. $aErrors[$sClass][] = "Unknown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  3486. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  3487. }
  3488. }
  3489. }
  3490. else if ($oAttDef->IsLinkSet())
  3491. {
  3492. // Do nothing...
  3493. }
  3494. else if ($oAttDef instanceof AttributeStopWatch)
  3495. {
  3496. $aThresholds = $oAttDef->ListThresholds();
  3497. if (is_array($aThresholds))
  3498. {
  3499. foreach($aThresholds as $iPercent => $aDef)
  3500. {
  3501. if (array_key_exists('highlight', $aDef))
  3502. {
  3503. if(!array_key_exists('code', $aDef['highlight']))
  3504. {
  3505. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of the $iPercent% threshold in the attribute: '$sAttCode'.";
  3506. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this threshold.";
  3507. }
  3508. else
  3509. {
  3510. $aScale = self::GetHighlightScale($sClass);
  3511. if (!array_key_exists($aDef['highlight']['code'], $aScale))
  3512. {
  3513. $aErrors[$sClass][] = "'{$aDef['highlight']['code']}' is not a valid value for the 'code' element of the $iPercent% threshold in the attribute: '$sAttCode'.";
  3514. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  3515. }
  3516. }
  3517. }
  3518. }
  3519. }
  3520. }
  3521. else // standard attributes
  3522. {
  3523. // Check that the default values definition is a valid object!
  3524. $oValSetDef = $oAttDef->GetValuesDef();
  3525. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  3526. {
  3527. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  3528. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  3529. }
  3530. else
  3531. {
  3532. // Default value must be listed in the allowed values (if defined)
  3533. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  3534. if (!is_null($aAllowedValues))
  3535. {
  3536. $sDefaultValue = $oAttDef->GetDefaultValue();
  3537. if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues))
  3538. {
  3539. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  3540. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  3541. }
  3542. }
  3543. }
  3544. }
  3545. // Check dependencies
  3546. if ($oAttDef->IsWritable())
  3547. {
  3548. $bHasWritableAttribute = true;
  3549. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  3550. {
  3551. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  3552. {
  3553. $aErrors[$sClass][] = "Unknown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  3554. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  3555. }
  3556. }
  3557. }
  3558. }
  3559. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  3560. {
  3561. if (method_exists($oFilterDef, '__GetRefAttribute'))
  3562. {
  3563. $oAttDef = $oFilterDef->__GetRefAttribute();
  3564. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  3565. {
  3566. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  3567. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3568. }
  3569. }
  3570. }
  3571. // Lifecycle
  3572. //
  3573. $sStateAttCode = self::GetStateAttributeCode($sClass);
  3574. if (strlen($sStateAttCode) > 0)
  3575. {
  3576. // Lifecycle - check that the state attribute does exist as an attribute
  3577. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  3578. {
  3579. $aErrors[$sClass][] = "Unknown attribute code '".$sStateAttCode."' for the state definition";
  3580. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3581. }
  3582. else
  3583. {
  3584. // Lifecycle - check that there is a value set constraint on the state attribute
  3585. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  3586. $aStates = array_keys(self::EnumStates($sClass));
  3587. if (is_null($aAllowedValuesRaw))
  3588. {
  3589. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  3590. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  3591. }
  3592. else
  3593. {
  3594. $aAllowedValues = array_keys($aAllowedValuesRaw);
  3595. // Lifecycle - check the the state attribute allowed values are defined states
  3596. foreach($aAllowedValues as $sValue)
  3597. {
  3598. if (!in_array($sValue, $aStates))
  3599. {
  3600. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  3601. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  3602. }
  3603. }
  3604. // Lifecycle - check that defined states are allowed values
  3605. foreach($aStates as $sStateValue)
  3606. {
  3607. if (!in_array($sStateValue, $aAllowedValues))
  3608. {
  3609. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  3610. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  3611. }
  3612. }
  3613. }
  3614. // Lifecycle - check that the action handlers are defined
  3615. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  3616. {
  3617. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  3618. {
  3619. foreach ($aTransitionDef['actions'] as $actionHandler)
  3620. {
  3621. if (is_string($actionHandler))
  3622. {
  3623. if (!method_exists($sClass, $actionHandler))
  3624. {
  3625. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  3626. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  3627. }
  3628. }
  3629. else // if(is_array($actionHandler))
  3630. {
  3631. $sActionHandler = $actionHandler['verb'];
  3632. if (!method_exists($sClass, $sActionHandler))
  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(...){return true;}]";
  3636. }
  3637. }
  3638. }
  3639. }
  3640. if (array_key_exists('highlight', $aStateDef))
  3641. {
  3642. if(!array_key_exists('code', $aStateDef['highlight']))
  3643. {
  3644. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of state: '$sStateCode'.";
  3645. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this state.";
  3646. }
  3647. else
  3648. {
  3649. $aScale = self::GetHighlightScale($sClass);
  3650. if (!array_key_exists($aStateDef['highlight']['code'], $aScale))
  3651. {
  3652. $aErrors[$sClass][] = "'{$aStateDef['highlight']['code']}' is not a valid value for the 'code' element in the 'highlight' property of state: '$sStateCode'.";
  3653. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  3654. }
  3655. }
  3656. }
  3657. }
  3658. }
  3659. }
  3660. if ($bHasWritableAttribute)
  3661. {
  3662. if (!self::HasTable($sClass))
  3663. {
  3664. $aErrors[$sClass][] = "No table has been defined for this class";
  3665. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  3666. }
  3667. }
  3668. // ZList
  3669. //
  3670. foreach(self::EnumZLists() as $sListCode)
  3671. {
  3672. foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode)
  3673. {
  3674. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  3675. {
  3676. $aErrors[$sClass][] = "Unknown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  3677. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3678. }
  3679. }
  3680. }
  3681. // Check unicity of the SQL columns
  3682. //
  3683. if (self::HasTable($sClass))
  3684. {
  3685. $aTableColumns = array(); // array of column => attcode (the column is used by this attribute)
  3686. $aTableColumns[self::DBGetKey($sClass)] = 'id';
  3687. // Check that SQL columns are declared only once
  3688. //
  3689. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3690. {
  3691. // Skip this attribute if not originaly defined in this class
  3692. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3693. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  3694. {
  3695. if (array_key_exists($sField, $aTableColumns))
  3696. {
  3697. $aErrors[$sClass][] = "Column '$sField' declared for attribute $sAttCode, but already used for attribute ".$aTableColumns[$sField];
  3698. $aSugFix[$sClass][] = "Please find another name for the SQL column";
  3699. }
  3700. else
  3701. {
  3702. $aTableColumns[$sField] = $sAttCode;
  3703. }
  3704. }
  3705. }
  3706. }
  3707. } // foreach class
  3708. if (count($aErrors) > 0)
  3709. {
  3710. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3711. echo "<h3>Business model inconsistencies have been found</h3>\n";
  3712. // #@# later -> this is the responsibility of the caller to format the output
  3713. foreach ($aErrors as $sClass => $aMessages)
  3714. {
  3715. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  3716. echo "<ul class=\"treeview\">\n";
  3717. $i = 0;
  3718. foreach ($aMessages as $sMsg)
  3719. {
  3720. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  3721. $i++;
  3722. }
  3723. echo "</ul>\n";
  3724. }
  3725. if ($bExitOnError) echo "<p>Aborting...</p>\n";
  3726. echo "</div>\n";
  3727. if ($bExitOnError) exit;
  3728. }
  3729. }
  3730. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  3731. {
  3732. if (empty($sRepairUrl)) return;
  3733. // By design, some queries might be blank, we have to ignore them
  3734. $aCleanFixes = array();
  3735. foreach($aSQLFixes as $sSQLFix)
  3736. {
  3737. if (!empty($sSQLFix))
  3738. {
  3739. $aCleanFixes[] = $sSQLFix;
  3740. }
  3741. }
  3742. if (count($aCleanFixes) == 0) return;
  3743. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  3744. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes), ENT_QUOTES, 'UTF-8')."\">\n";
  3745. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  3746. echo "</form>\n";
  3747. }
  3748. public static function DBExists($bMustBeComplete = true)
  3749. {
  3750. // returns true if at least one table exists
  3751. //
  3752. if (!CMDBSource::IsDB(self::$m_sDBName))
  3753. {
  3754. return false;
  3755. }
  3756. CMDBSource::SelectDB(self::$m_sDBName);
  3757. $aFound = array();
  3758. $aMissing = array();
  3759. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3760. {
  3761. if (CMDBSource::IsTable($sTable))
  3762. {
  3763. $aFound[] = $sTable;
  3764. }
  3765. else
  3766. {
  3767. $aMissing[] = $sTable;
  3768. }
  3769. }
  3770. if (count($aFound) == 0)
  3771. {
  3772. // no expected table has been found
  3773. return false;
  3774. }
  3775. else
  3776. {
  3777. if (count($aMissing) == 0)
  3778. {
  3779. // the database is complete (still, could be some fields missing!)
  3780. return true;
  3781. }
  3782. else
  3783. {
  3784. // not all the tables, could be an older version
  3785. if ($bMustBeComplete)
  3786. {
  3787. return false;
  3788. }
  3789. else
  3790. {
  3791. return true;
  3792. }
  3793. }
  3794. }
  3795. }
  3796. public static function DBDrop()
  3797. {
  3798. $bDropEntireDB = true;
  3799. if (!empty(self::$m_sTablePrefix))
  3800. {
  3801. // Do drop only tables corresponding to the sub-database (table prefix)
  3802. // then possibly drop the DB itself (if no table remain)
  3803. foreach (CMDBSource::EnumTables() as $sTable)
  3804. {
  3805. // perform a case insensitive test because on Windows the table names become lowercase :-(
  3806. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  3807. {
  3808. CMDBSource::DropTable($sTable);
  3809. }
  3810. else
  3811. {
  3812. // There is at least one table which is out of the scope of the current application
  3813. $bDropEntireDB = false;
  3814. }
  3815. }
  3816. }
  3817. if ($bDropEntireDB)
  3818. {
  3819. CMDBSource::DropDB(self::$m_sDBName);
  3820. }
  3821. }
  3822. public static function DBCreate($aCallback = null)
  3823. {
  3824. // Note: we have to check if the DB does exist, because we may share the DB
  3825. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  3826. if (!CMDBSource::IsDB(self::$m_sDBName))
  3827. {
  3828. CMDBSource::CreateDB(self::$m_sDBName);
  3829. }
  3830. self::DBCreateTables($aCallback);
  3831. self::DBCreateViews();
  3832. }
  3833. protected static function DBCreateTables($aCallback = null)
  3834. {
  3835. list($aErrors, $aSugFix, $aCondensedQueries) = self::DBCheckFormat();
  3836. //$sSQL = implode('; ', $aCondensedQueries); Does not work - multiple queries not allowed
  3837. foreach($aCondensedQueries as $sQuery)
  3838. {
  3839. $fStart = microtime(true);
  3840. CMDBSource::CreateTable($sQuery);
  3841. $fDuration = microtime(true) - $fStart;
  3842. if ($aCallback != null)
  3843. {
  3844. call_user_func($aCallback, $sQuery, $fDuration);
  3845. }
  3846. }
  3847. }
  3848. protected static function DBCreateViews()
  3849. {
  3850. list($aErrors, $aSugFix) = self::DBCheckViews();
  3851. $aSQL = array();
  3852. foreach ($aSugFix as $sClass => $aTarget)
  3853. {
  3854. foreach ($aTarget as $aQueries)
  3855. {
  3856. foreach ($aQueries as $sQuery)
  3857. {
  3858. if (!empty($sQuery))
  3859. {
  3860. //$aSQL[] = $sQuery;
  3861. // forces a refresh of cached information
  3862. CMDBSource::CreateTable($sQuery);
  3863. }
  3864. }
  3865. }
  3866. }
  3867. }
  3868. public static function DBDump()
  3869. {
  3870. $aDataDump = array();
  3871. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3872. {
  3873. $aRows = CMDBSource::DumpTable($sTable);
  3874. $aDataDump[$sTable] = $aRows;
  3875. }
  3876. return $aDataDump;
  3877. }
  3878. /*
  3879. * Determines wether the target DB is frozen or not
  3880. */
  3881. public static function DBIsReadOnly()
  3882. {
  3883. // Improvement: check the mySQL variable -> Read-only
  3884. if (UserRights::IsAdministrator())
  3885. {
  3886. return (!self::DBHasAccess(ACCESS_ADMIN_WRITE));
  3887. }
  3888. else
  3889. {
  3890. return (!self::DBHasAccess(ACCESS_USER_WRITE));
  3891. }
  3892. }
  3893. public static function DBHasAccess($iRequested = ACCESS_FULL)
  3894. {
  3895. $iMode = self::$m_oConfig->Get('access_mode');
  3896. if (($iMode & $iRequested) == 0) return false;
  3897. return true;
  3898. }
  3899. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  3900. {
  3901. $sValue = Dict::S($sKey, 'x-no-nothing');
  3902. if ($sValue == 'x-no-nothing')
  3903. {
  3904. $bNotInDico = true;
  3905. $sValue = $sValueFromOldSystem;
  3906. if (strlen($sValue) == 0)
  3907. {
  3908. $sValue = $sDefaultValue;
  3909. }
  3910. }
  3911. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  3912. }
  3913. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  3914. {
  3915. $sRes = '';
  3916. $sRes .= "// Dictionnay conventions\n";
  3917. $sRes .= htmlentities("// Class:<class_name>\n", ENT_QUOTES, 'UTF-8');
  3918. $sRes .= htmlentities("// Class:<class_name>+\n", ENT_QUOTES, 'UTF-8');
  3919. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n", ENT_QUOTES, 'UTF-8');
  3920. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n", ENT_QUOTES, 'UTF-8');
  3921. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n", ENT_QUOTES, 'UTF-8');
  3922. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n", ENT_QUOTES, 'UTF-8');
  3923. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n", ENT_QUOTES, 'UTF-8');
  3924. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n", ENT_QUOTES, 'UTF-8');
  3925. $sRes .= "\n";
  3926. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  3927. // Need to invent the "module", to characterize the origins of a class
  3928. if (strlen($sModules) == 0)
  3929. {
  3930. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  3931. }
  3932. else
  3933. {
  3934. $aModules = explode(', ', $sModules);
  3935. }
  3936. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3937. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  3938. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3939. foreach ($aModules as $sCategory)
  3940. {
  3941. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3942. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  3943. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3944. $sRes .= "//\n";
  3945. $sRes .= "\n";
  3946. foreach (self::GetClasses($sCategory) as $sClass)
  3947. {
  3948. if (!self::HasTable($sClass)) continue;
  3949. $bNotInDico = false;
  3950. $sClassRes = "//\n";
  3951. $sClassRes .= "// Class: $sClass\n";
  3952. $sClassRes .= "//\n";
  3953. $sClassRes .= "\n";
  3954. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  3955. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  3956. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  3957. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  3958. {
  3959. // Skip this attribute if not originaly defined in this class
  3960. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3961. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  3962. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  3963. if ($oAttDef instanceof AttributeEnum)
  3964. {
  3965. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  3966. {
  3967. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  3968. {
  3969. if (array_key_exists('label', $aStateData))
  3970. {
  3971. $sValue = $aStateData['label'];
  3972. }
  3973. else
  3974. {
  3975. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  3976. }
  3977. if (array_key_exists('description', $aStateData))
  3978. {
  3979. $sValuePlus = $aStateData['description'];
  3980. }
  3981. else
  3982. {
  3983. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  3984. }
  3985. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  3986. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  3987. }
  3988. }
  3989. else
  3990. {
  3991. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  3992. {
  3993. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  3994. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  3995. }
  3996. }
  3997. }
  3998. }
  3999. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  4000. {
  4001. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  4002. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  4003. }
  4004. $sClassRes .= "));\n";
  4005. $sClassRes .= "\n";
  4006. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  4007. {
  4008. $sRes .= $sClassRes;
  4009. }
  4010. }
  4011. }
  4012. return $sRes;
  4013. }
  4014. public static function DBCheckFormat()
  4015. {
  4016. $aErrors = array();
  4017. $aSugFix = array();
  4018. // A new way of representing things to be done - quicker to execute !
  4019. $aCreateTable = array(); // array of <table> => <table options>
  4020. $aCreateTableItems = array(); // array of <table> => array of <create definition>
  4021. $aAlterTableItems = array(); // array of <table> => <alter specification>
  4022. foreach (self::GetClasses() as $sClass)
  4023. {
  4024. if (!self::HasTable($sClass)) continue;
  4025. // Check that the table exists
  4026. //
  4027. $sTable = self::DBGetTable($sClass);
  4028. $sKeyField = self::DBGetKey($sClass);
  4029. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  4030. $sKeyFieldDefinition = "`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  4031. if (!CMDBSource::IsTable($sTable))
  4032. {
  4033. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  4034. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` ($sKeyFieldDefinition) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  4035. $aCreateTable[$sTable] = "ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  4036. $aCreateTableItems[$sTable][$sKeyField] = $sKeyFieldDefinition;
  4037. }
  4038. // Check that the key field exists
  4039. //
  4040. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  4041. {
  4042. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  4043. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD $sKeyFieldDefinition";
  4044. if (!array_key_exists($sTable, $aCreateTable))
  4045. {
  4046. $aAlterTableItems[$sTable][$sKeyField] = "ADD $sKeyFieldDefinition";
  4047. }
  4048. }
  4049. else
  4050. {
  4051. // Check the key field properties
  4052. //
  4053. if (!CMDBSource::IsKey($sTable, $sKeyField))
  4054. {
  4055. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  4056. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  4057. if (!array_key_exists($sTable, $aCreateTable))
  4058. {
  4059. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  4060. }
  4061. }
  4062. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  4063. {
  4064. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  4065. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` $sKeyFieldDefinition";
  4066. if (!array_key_exists($sTable, $aCreateTable))
  4067. {
  4068. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  4069. }
  4070. }
  4071. }
  4072. // Check that any defined field exists
  4073. //
  4074. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  4075. $aTableInfo['Fields'][$sKeyField]['used'] = true;
  4076. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  4077. {
  4078. // Skip this attribute if not originaly defined in this class
  4079. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  4080. foreach($oAttDef->GetSQLColumns(true) as $sField => $sDBFieldSpec)
  4081. {
  4082. // Keep track of columns used by iTop
  4083. $aTableInfo['Fields'][$sField]['used'] = true;
  4084. $bIndexNeeded = $oAttDef->RequiresIndex();
  4085. $sFieldDefinition = "`$sField` $sDBFieldSpec";
  4086. if (!CMDBSource::IsField($sTable, $sField))
  4087. {
  4088. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  4089. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD $sFieldDefinition";
  4090. if ($bIndexNeeded)
  4091. {
  4092. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  4093. }
  4094. if (array_key_exists($sTable, $aCreateTable))
  4095. {
  4096. $aCreateTableItems[$sTable][$sField] = $sFieldDefinition;
  4097. if ($bIndexNeeded)
  4098. {
  4099. $aCreateTableItems[$sTable][] = "INDEX (`$sField`)";
  4100. }
  4101. }
  4102. else
  4103. {
  4104. $aAlterTableItems[$sTable][$sField] = "ADD $sFieldDefinition";
  4105. if ($bIndexNeeded)
  4106. {
  4107. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  4108. }
  4109. }
  4110. }
  4111. else
  4112. {
  4113. // The field already exists, does it have the relevant properties?
  4114. //
  4115. $bToBeChanged = false;
  4116. $sActualFieldSpec = CMDBSource::GetFieldSpec($sTable, $sField);
  4117. if (strcasecmp($sDBFieldSpec, $sActualFieldSpec) != 0)
  4118. {
  4119. $bToBeChanged = true;
  4120. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldSpec' while expecting '$sDBFieldSpec'";
  4121. }
  4122. if ($bToBeChanged)
  4123. {
  4124. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  4125. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  4126. }
  4127. // Create indexes (external keys only... so far)
  4128. //
  4129. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField, array($sField)))
  4130. {
  4131. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  4132. if (CMDBSource::HasIndex($sTable, $sField))
  4133. {
  4134. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` DROP INDEX `$sField`, ADD INDEX (`$sField`)";
  4135. $aAlterTableItems[$sTable][] = "DROP INDEX `$sField`";
  4136. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  4137. }
  4138. else
  4139. {
  4140. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  4141. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  4142. }
  4143. }
  4144. }
  4145. }
  4146. }
  4147. // Check indexes
  4148. foreach (self::DBGetIndexes($sClass) as $aColumns)
  4149. {
  4150. $sIndexId = implode('_', $aColumns);
  4151. if(!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns))
  4152. {
  4153. $sColumns = "`".implode("`, `", $aColumns)."`";
  4154. if (CMDBSource::HasIndex($sTable, $sIndexId))
  4155. {
  4156. $aErrors[$sClass]['*'][] = "Wrong index '$sIndexId' ($sColumns) in table '$sTable'";
  4157. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`, ADD INDEX `$sIndexId` ($sColumns)";
  4158. }
  4159. else
  4160. {
  4161. $aErrors[$sClass]['*'][] = "Missing index '$sIndexId' ($sColumns) in table '$sTable'";
  4162. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)";
  4163. }
  4164. if (array_key_exists($sTable, $aCreateTable))
  4165. {
  4166. $aCreateTableItems[$sTable][] = "INDEX `$sIndexId` ($sColumns)";
  4167. }
  4168. else
  4169. {
  4170. if (CMDBSource::HasIndex($sTable, $sIndexId))
  4171. {
  4172. $aAlterTableItems[$sTable][] = "DROP INDEX `$sIndexId`";
  4173. }
  4174. $aAlterTableItems[$sTable][] = "ADD INDEX `$sIndexId` ($sColumns)";
  4175. }
  4176. }
  4177. }
  4178. // Find out unused columns
  4179. //
  4180. foreach($aTableInfo['Fields'] as $sField => $aFieldData)
  4181. {
  4182. if (!isset($aFieldData['used']) || !$aFieldData['used'])
  4183. {
  4184. $aErrors[$sClass]['*'][] = "Column '$sField' in table '$sTable' is not used";
  4185. if (!CMDBSource::IsNullAllowed($sTable, $sField))
  4186. {
  4187. // Allow null values so that new record can be inserted
  4188. // without specifying the value of this unknown column
  4189. $sFieldDefinition = "`$sField` ".CMDBSource::GetFieldType($sTable, $sField).' NULL';
  4190. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  4191. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  4192. }
  4193. }
  4194. }
  4195. }
  4196. $aCondensedQueries = array();
  4197. foreach($aCreateTable as $sTable => $sTableOptions)
  4198. {
  4199. $sTableItems = implode(', ', $aCreateTableItems[$sTable]);
  4200. $aCondensedQueries[] = "CREATE TABLE `$sTable` ($sTableItems) $sTableOptions";
  4201. }
  4202. foreach($aAlterTableItems as $sTable => $aChangeList)
  4203. {
  4204. $sChangeList = implode(', ', $aChangeList);
  4205. $aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList";
  4206. }
  4207. return array($aErrors, $aSugFix, $aCondensedQueries);
  4208. }
  4209. public static function DBCheckViews()
  4210. {
  4211. $aErrors = array();
  4212. $aSugFix = array();
  4213. // Reporting views (must be created after any other table)
  4214. //
  4215. foreach (self::GetClasses('bizmodel') as $sClass)
  4216. {
  4217. $sView = self::DBGetView($sClass);
  4218. if (CMDBSource::IsTable($sView))
  4219. {
  4220. // Check that the view is complete
  4221. //
  4222. // Note: checking the list of attributes is not enough because the columns can be stable while the SELECT is not stable
  4223. // Example: new way to compute the friendly name
  4224. // The correct comparison algorithm is to compare the queries,
  4225. // by using "SHOW CREATE VIEW" (MySQL 5.0.1 required) or to look into INFORMATION_SCHEMA/views
  4226. // both requiring some privileges
  4227. // Decision: to simplify, let's consider the views as being wrong anytime
  4228. if (true)
  4229. {
  4230. // Rework the view
  4231. //
  4232. $oFilter = new DBObjectSearch($sClass, '');
  4233. $oFilter->AllowAllData();
  4234. $sSQL = self::MakeSelectQuery($oFilter);
  4235. $aErrors[$sClass]['*'][] = "Redeclare view '$sView' (systematic - to support an eventual change in the friendly name computation)";
  4236. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  4237. }
  4238. }
  4239. else
  4240. {
  4241. // Create the view
  4242. //
  4243. $oFilter = new DBObjectSearch($sClass, '');
  4244. $oFilter->AllowAllData();
  4245. $sSQL = self::MakeSelectQuery($oFilter);
  4246. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  4247. $aSugFix[$sClass]['*'][] = "DROP VIEW IF EXISTS `$sView`";
  4248. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  4249. }
  4250. }
  4251. return array($aErrors, $aSugFix);
  4252. }
  4253. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  4254. {
  4255. $sRootClass = self::GetRootClass($sClass);
  4256. $sTable = self::DBGetTable($sClass);
  4257. $sKeyField = self::DBGetKey($sClass);
  4258. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  4259. {
  4260. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  4261. }
  4262. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  4263. if (count($aWrongRecords) == 0) return;
  4264. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  4265. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  4266. foreach ($aWrongRecords as $iRecordId)
  4267. {
  4268. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  4269. {
  4270. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  4271. {
  4272. case 'Delete':
  4273. // Already planned for a deletion
  4274. // Let's concatenate the errors description together
  4275. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  4276. break;
  4277. case 'Update':
  4278. // Let's plan a deletion
  4279. break;
  4280. }
  4281. }
  4282. else
  4283. {
  4284. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  4285. }
  4286. if (!$bProcessingFriends)
  4287. {
  4288. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  4289. {
  4290. // Something new to be deleted...
  4291. $iNewDelCount++;
  4292. }
  4293. }
  4294. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  4295. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  4296. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  4297. $aPlannedDel[$sTable][] = $iRecordId;
  4298. }
  4299. // Now make sure that we would delete the records of the other tables for that class
  4300. //
  4301. if (!$bProcessingFriends)
  4302. {
  4303. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  4304. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  4305. {
  4306. $sFriendTable = self::DBGetTable($sFriendClass);
  4307. $sFriendKey = self::DBGetKey($sFriendClass);
  4308. // skip the current table
  4309. if ($sFriendTable == $sTable) continue;
  4310. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  4311. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  4312. }
  4313. }
  4314. }
  4315. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  4316. {
  4317. $sRootClass = self::GetRootClass($sClass);
  4318. $sTable = self::DBGetTable($sClass);
  4319. $sKeyField = self::DBGetKey($sClass);
  4320. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  4321. {
  4322. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  4323. }
  4324. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  4325. if (count($aWrongRecords) == 0) return;
  4326. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  4327. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  4328. foreach ($aWrongRecords as $iRecordId)
  4329. {
  4330. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  4331. {
  4332. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  4333. {
  4334. case 'Delete':
  4335. // No need to update, the record will be deleted!
  4336. break;
  4337. case 'Update':
  4338. // Already planned for an update
  4339. // Add this new update spec to the list
  4340. $bFoundSameSpec = false;
  4341. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  4342. {
  4343. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  4344. {
  4345. $bFoundSameSpec = true;
  4346. }
  4347. }
  4348. if (!$bFoundSameSpec)
  4349. {
  4350. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  4351. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  4352. }
  4353. break;
  4354. }
  4355. }
  4356. else
  4357. {
  4358. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  4359. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  4360. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  4361. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  4362. }
  4363. }
  4364. }
  4365. // returns the count of records found for deletion
  4366. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  4367. {
  4368. foreach (self::GetClasses() as $sClass)
  4369. {
  4370. if (!self::HasTable($sClass)) continue;
  4371. $sRootClass = self::GetRootClass($sClass);
  4372. $sTable = self::DBGetTable($sClass);
  4373. $sKeyField = self::DBGetKey($sClass);
  4374. if (!self::IsStandaloneClass($sClass))
  4375. {
  4376. if (self::IsRootClass($sClass))
  4377. {
  4378. // Check that the final class field contains the name of a class which inherited from the current class
  4379. //
  4380. $sFinalClassField = self::DBGetClassField($sClass);
  4381. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  4382. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  4383. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  4384. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4385. }
  4386. else
  4387. {
  4388. $sRootTable = self::DBGetTable($sRootClass);
  4389. $sRootKey = self::DBGetKey($sRootClass);
  4390. $sFinalClassField = self::DBGetClassField($sRootClass);
  4391. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  4392. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  4393. // Check that any record found here has its counterpart in the root table
  4394. // and which refers to a child class
  4395. //
  4396. $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";
  4397. 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);
  4398. // Check that any record found in the root table and referring to a child class
  4399. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  4400. //
  4401. $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)";
  4402. 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);
  4403. }
  4404. }
  4405. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  4406. {
  4407. // Skip this attribute if not defined in this table
  4408. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  4409. if ($oAttDef->IsExternalKey())
  4410. {
  4411. // Check that any external field is pointing to an existing object
  4412. //
  4413. $sRemoteClass = $oAttDef->GetTargetClass();
  4414. $sRemoteTable = self::DBGetTable($sRemoteClass);
  4415. $sRemoteKey = self::DBGetKey($sRemoteClass);
  4416. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  4417. $sExtKeyField = current($aCols); // get the first column for an external key
  4418. // Note: a class/table may have an external key on itself
  4419. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  4420. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  4421. if ($oAttDef->IsNullAllowed())
  4422. {
  4423. // Exclude the records pointing to 0/null from the errors
  4424. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  4425. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  4426. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4427. }
  4428. else
  4429. {
  4430. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4431. }
  4432. // Do almost the same, taking into account the records planned for deletion
  4433. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  4434. {
  4435. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  4436. // but in that case you won't be able to track the root cause (cascading)
  4437. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  4438. if ($oAttDef->IsNullAllowed())
  4439. {
  4440. // Exclude the records pointing to 0/null from the errors
  4441. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  4442. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  4443. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4444. }
  4445. else
  4446. {
  4447. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4448. }
  4449. }
  4450. }
  4451. else if ($oAttDef->IsDirectField())
  4452. {
  4453. // Check that the values fit the allowed values
  4454. //
  4455. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  4456. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  4457. {
  4458. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  4459. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  4460. $sMyAttributeField = current($aCols); // get the first column for the moment
  4461. $sDefaultValue = $oAttDef->GetDefaultValue();
  4462. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  4463. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4464. }
  4465. }
  4466. }
  4467. }
  4468. }
  4469. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  4470. {
  4471. // Records in error, and action to be taken: delete or update
  4472. // by RootClass/Table/Record
  4473. $aErrorsAndFixes = array();
  4474. // Records to be ignored in the current/next pass
  4475. // by Table = array of RecordId
  4476. $aPlannedDel = array();
  4477. // Count of errors in the next pass: no error means that we can leave...
  4478. $iErrorCount = 0;
  4479. // Limit in case of a bug in the algorythm
  4480. $iLoopCount = 0;
  4481. $iNewDelCount = 1; // startup...
  4482. while ($iNewDelCount > 0)
  4483. {
  4484. $iNewDelCount = 0;
  4485. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4486. $iErrorCount += $iNewDelCount;
  4487. // Safety net #1 - limit the planned deletions
  4488. //
  4489. $iMaxDel = 1000;
  4490. $iPlannedDel = 0;
  4491. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  4492. {
  4493. $iPlannedDel += count($aPlannedDelOnTable);
  4494. }
  4495. if ($iPlannedDel > $iMaxDel)
  4496. {
  4497. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  4498. break;
  4499. }
  4500. // Safety net #2 - limit the iterations
  4501. //
  4502. $iLoopCount++;
  4503. $iMaxLoops = 10;
  4504. if ($iLoopCount > $iMaxLoops)
  4505. {
  4506. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  4507. break;
  4508. }
  4509. }
  4510. // Display the results
  4511. //
  4512. $iIssueCount = 0;
  4513. $aFixesDelete = array();
  4514. $aFixesUpdate = array();
  4515. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  4516. {
  4517. foreach ($aTables as $sTable => $aRecords)
  4518. {
  4519. foreach ($aRecords as $iRecord => $aError)
  4520. {
  4521. $sAction = $aError['Action'];
  4522. $sReason = $aError['Reason'];
  4523. $iPass = $aError['Pass'];
  4524. switch ($sAction)
  4525. {
  4526. case 'Delete':
  4527. $sActionDetails = "";
  4528. $aFixesDelete[$sTable][] = $iRecord;
  4529. break;
  4530. case 'Update':
  4531. $aUpdateDesc = array();
  4532. foreach($aError['Action_Details'] as $aUpdateSpec)
  4533. {
  4534. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  4535. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  4536. }
  4537. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  4538. break;
  4539. default:
  4540. $sActionDetails = "bug: unknown action '$sAction'";
  4541. }
  4542. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  4543. $iIssueCount++;
  4544. }
  4545. }
  4546. }
  4547. if ($iIssueCount > 0)
  4548. {
  4549. // Build the queries to fix in the database
  4550. //
  4551. // First step, be able to get class data out of the table name
  4552. // Could be optimized, because we've made the job earlier... but few benefits, so...
  4553. $aTable2ClassProp = array();
  4554. foreach (self::GetClasses() as $sClass)
  4555. {
  4556. if (!self::HasTable($sClass)) continue;
  4557. $sRootClass = self::GetRootClass($sClass);
  4558. $sTable = self::DBGetTable($sClass);
  4559. $sKeyField = self::DBGetKey($sClass);
  4560. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  4561. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  4562. }
  4563. // Second step, build a flat list of SQL queries
  4564. $aSQLFixes = array();
  4565. $iPlannedUpdate = 0;
  4566. foreach ($aFixesUpdate as $sTable => $aColumns)
  4567. {
  4568. foreach ($aColumns as $sColumn => $aNewValues)
  4569. {
  4570. foreach ($aNewValues as $sNewValue => $aRecords)
  4571. {
  4572. $iPlannedUpdate += count($aRecords);
  4573. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  4574. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  4575. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  4576. }
  4577. }
  4578. }
  4579. $iPlannedDel = 0;
  4580. foreach ($aFixesDelete as $sTable => $aRecords)
  4581. {
  4582. $iPlannedDel += count($aRecords);
  4583. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  4584. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  4585. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  4586. }
  4587. // Report the results
  4588. //
  4589. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  4590. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  4591. // #@# later -> this is the responsibility of the caller to format the output
  4592. echo "<ul class=\"treeview\">\n";
  4593. foreach ($aIssues as $sIssueDesc)
  4594. {
  4595. echo "<li>$sIssueDesc</li>\n";
  4596. }
  4597. echo "</ul>\n";
  4598. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  4599. echo "<p>Aborting...</p>\n";
  4600. echo "</div>\n";
  4601. exit;
  4602. }
  4603. }
  4604. public static function Startup($config, $bModelOnly = false, $bAllowCache = true, $bTraceSourceFiles = false)
  4605. {
  4606. if (!defined('MODULESROOT'))
  4607. {
  4608. define('MODULESROOT', APPROOT.'env-'.utils::GetCurrentEnvironment().'/');
  4609. self::$m_bTraceSourceFiles = $bTraceSourceFiles;
  4610. // $config can be either a filename, or a Configuration object (volatile!)
  4611. if ($config instanceof Config)
  4612. {
  4613. self::LoadConfig($config, $bAllowCache);
  4614. }
  4615. else
  4616. {
  4617. self::LoadConfig(new Config($config), $bAllowCache);
  4618. }
  4619. if ($bModelOnly) return;
  4620. }
  4621. CMDBSource::SelectDB(self::$m_sDBName);
  4622. foreach(get_declared_classes() as $sPHPClass)
  4623. {
  4624. if (is_subclass_of($sPHPClass, 'ModuleHandlerAPI'))
  4625. {
  4626. $aCallSpec = array($sPHPClass, 'OnMetaModelStarted');
  4627. call_user_func_array($aCallSpec, array());
  4628. }
  4629. }
  4630. if (false)
  4631. {
  4632. echo "Debug<br/>\n";
  4633. self::static_var_dump();
  4634. }
  4635. }
  4636. public static function LoadConfig($oConfiguration, $bAllowCache = false)
  4637. {
  4638. self::$m_oConfig = $oConfiguration;
  4639. // Set log ASAP
  4640. if (self::$m_oConfig->GetLogGlobal())
  4641. {
  4642. if (self::$m_oConfig->GetLogIssue())
  4643. {
  4644. self::$m_bLogIssue = true;
  4645. IssueLog::Enable(APPROOT.'log/error.log');
  4646. }
  4647. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  4648. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  4649. ToolsLog::Enable(APPROOT.'log/tools.log');
  4650. }
  4651. else
  4652. {
  4653. self::$m_bLogIssue = false;
  4654. self::$m_bLogNotification = false;
  4655. self::$m_bLogWebService = false;
  4656. }
  4657. ExecutionKPI::EnableDuration(self::$m_oConfig->Get('log_kpi_duration'));
  4658. ExecutionKPI::EnableMemory(self::$m_oConfig->Get('log_kpi_memory'));
  4659. ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id'));
  4660. self::$m_bTraceQueries = self::$m_oConfig->GetLogQueries();
  4661. self::$m_bIndentQueries = self::$m_oConfig->Get('query_indentation_enabled');
  4662. self::$m_bQueryCacheEnabled = self::$m_oConfig->GetQueryCacheEnabled();
  4663. self::$m_bOptimizeQueries = self::$m_oConfig->Get('query_optimization_enabled');
  4664. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  4665. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  4666. self::$m_bUseAPCCache = $bAllowCache
  4667. && self::$m_oConfig->Get('apc_cache.enabled')
  4668. && function_exists('apc_fetch')
  4669. && function_exists('apc_store');
  4670. self::$m_iQueryCacheTTL = self::$m_oConfig->Get('apc_cache.query_ttl');
  4671. // PHP timezone first...
  4672. //
  4673. $sPHPTimezone = self::$m_oConfig->Get('timezone');
  4674. if ($sPHPTimezone == '')
  4675. {
  4676. // Leave as is... up to the admin to set a value somewhere...
  4677. //$sPHPTimezone = date_default_timezone_get();
  4678. }
  4679. else
  4680. {
  4681. date_default_timezone_set($sPHPTimezone);
  4682. }
  4683. // Note: load the dictionary as soon as possible, because it might be
  4684. // needed when some error occur
  4685. $sAppIdentity = 'itop-'.MetaModel::GetEnvironmentId();
  4686. $bDictInitializedFromData = false;
  4687. if (!self::$m_bUseAPCCache || !Dict::InCache($sAppIdentity))
  4688. {
  4689. $bDictInitializedFromData = true;
  4690. foreach (self::$m_oConfig->GetDictionaries() as $sModule => $sToInclude)
  4691. {
  4692. self::IncludeModule('dictionaries', $sToInclude);
  4693. }
  4694. }
  4695. // Set the language... after the dictionaries have been loaded!
  4696. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  4697. // Romain: this is the only way I've found to cope with the fact that
  4698. // classes have to be derived from cmdbabstract (to be editable in the UI)
  4699. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  4700. foreach (self::$m_oConfig->GetAppModules() as $sModule => $sToInclude)
  4701. {
  4702. self::IncludeModule('application', $sToInclude);
  4703. }
  4704. foreach (self::$m_oConfig->GetDataModels() as $sModule => $sToInclude)
  4705. {
  4706. self::IncludeModule('business', $sToInclude);
  4707. }
  4708. foreach (self::$m_oConfig->GetWebServiceCategories() as $sModule => $sToInclude)
  4709. {
  4710. self::IncludeModule('webservice', $sToInclude);
  4711. }
  4712. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  4713. {
  4714. self::IncludeModule('addons', $sToInclude);
  4715. }
  4716. $sServer = self::$m_oConfig->GetDBHost();
  4717. $sUser = self::$m_oConfig->GetDBUser();
  4718. $sPwd = self::$m_oConfig->GetDBPwd();
  4719. $sSource = self::$m_oConfig->GetDBName();
  4720. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  4721. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  4722. $sCollation = self::$m_oConfig->GetDBCollation();
  4723. if (self::$m_bUseAPCCache)
  4724. {
  4725. $oKPI = new ExecutionKPI();
  4726. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  4727. //
  4728. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-metamodel';
  4729. $result = apc_fetch($sOqlAPCCacheId);
  4730. if (is_array($result))
  4731. {
  4732. // todo - verifier que toutes les classes mentionnees ici sont chargees dans InitClasses()
  4733. self::$m_aExtensionClasses = $result['m_aExtensionClasses'];
  4734. self::$m_Category2Class = $result['m_Category2Class'];
  4735. self::$m_aRootClasses = $result['m_aRootClasses'];
  4736. self::$m_aParentClasses = $result['m_aParentClasses'];
  4737. self::$m_aChildClasses = $result['m_aChildClasses'];
  4738. self::$m_aClassParams = $result['m_aClassParams'];
  4739. self::$m_aAttribDefs = $result['m_aAttribDefs'];
  4740. self::$m_aAttribOrigins = $result['m_aAttribOrigins'];
  4741. self::$m_aExtKeyFriends = $result['m_aExtKeyFriends'];
  4742. self::$m_aIgnoredAttributes = $result['m_aIgnoredAttributes'];
  4743. self::$m_aFilterDefs = $result['m_aFilterDefs'];
  4744. self::$m_aFilterOrigins = $result['m_aFilterOrigins'];
  4745. self::$m_aListInfos = $result['m_aListInfos'];
  4746. self::$m_aListData = $result['m_aListData'];
  4747. self::$m_aRelationInfos = $result['m_aRelationInfos'];
  4748. self::$m_aStates = $result['m_aStates'];
  4749. self::$m_aStimuli = $result['m_aStimuli'];
  4750. self::$m_aTransitions = $result['m_aTransitions'];
  4751. self::$m_aHighlightScales = $result['m_aHighlightScales'];
  4752. }
  4753. $oKPI->ComputeAndReport('Metamodel APC (fetch + read)');
  4754. }
  4755. if (count(self::$m_aAttribDefs) == 0)
  4756. {
  4757. // The includes have been included, let's browse the existing classes and
  4758. // develop some data based on the proposed model
  4759. $oKPI = new ExecutionKPI();
  4760. self::InitClasses($sTablePrefix);
  4761. $oKPI->ComputeAndReport('Initialization of Data model structures');
  4762. if (self::$m_bUseAPCCache)
  4763. {
  4764. $oKPI = new ExecutionKPI();
  4765. $aCache = array();
  4766. $aCache['m_aExtensionClasses'] = self::$m_aExtensionClasses;
  4767. $aCache['m_Category2Class'] = self::$m_Category2Class;
  4768. $aCache['m_aRootClasses'] = self::$m_aRootClasses; // array of "classname" => "rootclass"
  4769. $aCache['m_aParentClasses'] = self::$m_aParentClasses; // array of ("classname" => array of "parentclass")
  4770. $aCache['m_aChildClasses'] = self::$m_aChildClasses; // array of ("classname" => array of "childclass")
  4771. $aCache['m_aClassParams'] = self::$m_aClassParams; // array of ("classname" => array of class information)
  4772. $aCache['m_aAttribDefs'] = self::$m_aAttribDefs; // array of ("classname" => array of attributes)
  4773. $aCache['m_aAttribOrigins'] = self::$m_aAttribOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4774. $aCache['m_aExtKeyFriends'] = self::$m_aExtKeyFriends; // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  4775. $aCache['m_aIgnoredAttributes'] = self::$m_aIgnoredAttributes; //array of ("classname" => array of ("attcode")
  4776. $aCache['m_aFilterDefs'] = self::$m_aFilterDefs; // array of ("classname" => array filterdef)
  4777. $aCache['m_aFilterOrigins'] = self::$m_aFilterOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4778. $aCache['m_aListInfos'] = self::$m_aListInfos; // array of ("listcode" => various info on the list, common to every classes)
  4779. $aCache['m_aListData'] = self::$m_aListData; // array of ("classname" => array of "listcode" => list)
  4780. $aCache['m_aRelationInfos'] = self::$m_aRelationInfos; // array of ("relcode" => various info on the list, common to every classes)
  4781. $aCache['m_aStates'] = self::$m_aStates; // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  4782. $aCache['m_aStimuli'] = self::$m_aStimuli; // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  4783. $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)))
  4784. $aCache['m_aHighlightScales'] = self::$m_aHighlightScales; // array of ("classname" => array of higlightcodes)))
  4785. apc_store($sOqlAPCCacheId, $aCache);
  4786. $oKPI->ComputeAndReport('Metamodel APC (store)');
  4787. }
  4788. }
  4789. if (self::$m_bUseAPCCache && $bDictInitializedFromData)
  4790. {
  4791. Dict::InitCache($sAppIdentity);
  4792. }
  4793. self::$m_sDBName = $sSource;
  4794. self::$m_sTablePrefix = $sTablePrefix;
  4795. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  4796. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  4797. // Later when timezone implementation is correctly done: CMDBSource::SetTimezone($sDBTimezone);
  4798. }
  4799. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  4800. {
  4801. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  4802. }
  4803. public static function GetModuleParameter($sModule, $sProperty, $defaultvalue = null)
  4804. {
  4805. $value = $defaultvalue;
  4806. if (!array_key_exists($sModule, self::$m_aModulesParameters))
  4807. {
  4808. }
  4809. if (!self::$m_aModulesParameters[$sModule] == null)
  4810. {
  4811. $value = self::$m_aModulesParameters[$sModule]->Get($sProperty, $defaultvalue);
  4812. }
  4813. return $value;
  4814. }
  4815. public static function GetConfig()
  4816. {
  4817. return self::$m_oConfig;
  4818. }
  4819. public static function GetEnvironmentId()
  4820. {
  4821. return md5(APPROOT).'-'.utils::GetCurrentEnvironment();
  4822. }
  4823. protected static $m_aExtensionClasses = array();
  4824. protected static function IncludeModule($sModuleType, $sToInclude)
  4825. {
  4826. $sFirstChar = substr($sToInclude, 0, 1);
  4827. $sSecondChar = substr($sToInclude, 1, 1);
  4828. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  4829. {
  4830. // It is a relative path, prepend APPROOT
  4831. if (substr($sToInclude, 0, 3) == '../')
  4832. {
  4833. // Preserve compatibility with config files written before 1.0.1
  4834. // Replace '../' by '<root>/'
  4835. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  4836. }
  4837. else
  4838. {
  4839. $sFile = APPROOT.'/'.$sToInclude;
  4840. }
  4841. }
  4842. else
  4843. {
  4844. // Leave as is - should be an absolute path
  4845. $sFile = $sToInclude;
  4846. }
  4847. if (!file_exists($sFile))
  4848. {
  4849. $sConfigFile = self::$m_oConfig->GetLoadedFile();
  4850. if (strlen($sConfigFile) > 0)
  4851. {
  4852. throw new CoreException('Include: wrong file name in configuration file', array('config file' => $sConfigFile, 'section' => $sModuleType, 'filename' => $sFile));
  4853. }
  4854. else
  4855. {
  4856. // The configuration is in memory only
  4857. throw new CoreException('Include: wrong file name in configuration file (in memory)', array('section' => $sModuleType, 'filename' => $sFile));
  4858. }
  4859. }
  4860. // Note: We do not expect the modules to output characters while loading them.
  4861. // Therefore, and because unexpected characters can corrupt the output,
  4862. // they must be trashed here.
  4863. // Additionnaly, pages aiming at delivering data in their output can call WebPage::TrashUnexpectedOutput()
  4864. // to get rid of chars that could be generated during the execution of the code
  4865. ob_start();
  4866. require_once($sFile);
  4867. $sPreviousContent = ob_get_clean();
  4868. if (self::$m_oConfig->Get('debug_report_spurious_chars'))
  4869. {
  4870. if ($sPreviousContent != '')
  4871. {
  4872. IssueLog::Error("Spurious characters injected by $sModuleType/$sToInclude");
  4873. }
  4874. }
  4875. }
  4876. // Building an object
  4877. //
  4878. //
  4879. private static $aQueryCacheGetObject = array();
  4880. private static $aQueryCacheGetObjectHits = array();
  4881. public static function GetQueryCacheStatus()
  4882. {
  4883. $aRes = array();
  4884. $iTotalHits = 0;
  4885. foreach(self::$aQueryCacheGetObjectHits as $sClassSign => $iHits)
  4886. {
  4887. $aRes[] = "$sClassSign: $iHits";
  4888. $iTotalHits += $iHits;
  4889. }
  4890. return $iTotalHits.' ('.implode(', ', $aRes).')';
  4891. }
  4892. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4893. {
  4894. // Build the query cache signature
  4895. //
  4896. $sQuerySign = $sClass;
  4897. if($bAllowAllData)
  4898. {
  4899. $sQuerySign .= '_all_';
  4900. }
  4901. if (count($aModifierProperties))
  4902. {
  4903. array_multisort($aModifierProperties);
  4904. $sModifierProperties = json_encode($aModifierProperties);
  4905. $sQuerySign .= '_all_'.md5($sModifierProperties);
  4906. }
  4907. if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject))
  4908. {
  4909. // NOTE: Quick and VERY dirty caching mechanism which relies on
  4910. // the fact that the string '987654321' will never appear in the
  4911. // standard query
  4912. // This could be simplified a little, relying solely on the query cache,
  4913. // but this would slow down -by how much time?- the application
  4914. $oFilter = new DBObjectSearch($sClass);
  4915. $oFilter->AddCondition('id', 987654321, '=');
  4916. if ($aModifierProperties)
  4917. {
  4918. foreach ($aModifierProperties as $sPluginClass => $aProperties)
  4919. {
  4920. foreach ($aProperties as $sProperty => $value)
  4921. {
  4922. $oFilter->SetModifierProperty($sPluginClass, $sProperty, $value);
  4923. }
  4924. }
  4925. }
  4926. if ($bAllowAllData)
  4927. {
  4928. $oFilter->AllowAllData();
  4929. }
  4930. $sSQL = self::MakeSelectQuery($oFilter);
  4931. self::$aQueryCacheGetObject[$sQuerySign] = $sSQL;
  4932. self::$aQueryCacheGetObjectHits[$sQuerySign] = 0;
  4933. }
  4934. else
  4935. {
  4936. $sSQL = self::$aQueryCacheGetObject[$sQuerySign];
  4937. self::$aQueryCacheGetObjectHits[$sQuerySign] += 1;
  4938. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sQuerySign]."<br/>\n";
  4939. }
  4940. $sSQL = str_replace(CMDBSource::Quote(987654321), CMDBSource::Quote($iKey), $sSQL);
  4941. $res = CMDBSource::Query($sSQL);
  4942. $aRow = CMDBSource::FetchArray($res);
  4943. CMDBSource::FreeResult($res);
  4944. if ($bMustBeFound && empty($aRow))
  4945. {
  4946. throw new CoreException("No result for the single row query: '$sSQL'");
  4947. }
  4948. return $aRow;
  4949. }
  4950. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  4951. {
  4952. self::_check_subclass($sClass);
  4953. if (strlen($sClassAlias) == 0)
  4954. {
  4955. $sClassAlias = $sClass;
  4956. }
  4957. // Compound objects: if available, get the final object class
  4958. //
  4959. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  4960. {
  4961. // Either this is a bug (forgot to specify a root class with a finalclass field
  4962. // Or this is the expected behavior, because the object is not made of several tables
  4963. }
  4964. elseif (empty($aRow[$sClassAlias."finalclass"]))
  4965. {
  4966. // The data is missing in the DB
  4967. // @#@ possible improvement: check that the class is valid !
  4968. $sRootClass = self::GetRootClass($sClass);
  4969. $sFinalClassField = self::DBGetClassField($sRootClass);
  4970. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  4971. }
  4972. else
  4973. {
  4974. // do the job for the real target class
  4975. $sClass = $aRow[$sClassAlias."finalclass"];
  4976. }
  4977. return new $sClass($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  4978. }
  4979. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4980. {
  4981. self::_check_subclass($sClass);
  4982. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
  4983. if (empty($aRow))
  4984. {
  4985. return null;
  4986. }
  4987. return self::GetObjectByRow($sClass, $aRow);
  4988. }
  4989. public static function GetObjectByName($sClass, $sName, $bMustBeFound = true)
  4990. {
  4991. self::_check_subclass($sClass);
  4992. $oObjSearch = new DBObjectSearch($sClass);
  4993. $oObjSearch->AddNameCondition($sName);
  4994. $oSet = new DBObjectSet($oObjSearch);
  4995. if ($oSet->Count() != 1)
  4996. {
  4997. if ($bMustBeFound) throw new CoreException('Failed to get an object by its name', array('class'=>$sClass, 'name'=>$sName));
  4998. return null;
  4999. }
  5000. $oObj = $oSet->fetch();
  5001. return $oObj;
  5002. }
  5003. static protected $m_aCacheObjectByColumn = array();
  5004. public static function GetObjectByColumn($sClass, $sAttCode, $value, $bMustBeFoundUnique = true)
  5005. {
  5006. if (!isset(self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value]))
  5007. {
  5008. self::_check_subclass($sClass);
  5009. $oObjSearch = new DBObjectSearch($sClass);
  5010. $oObjSearch->AddCondition($sAttCode, $value, '=');
  5011. $oSet = new DBObjectSet($oObjSearch);
  5012. if ($oSet->Count() == 1)
  5013. {
  5014. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch();
  5015. }
  5016. else
  5017. {
  5018. if ($bMustBeFoundUnique) throw new CoreException('Failed to get an object by column', array('class'=>$sClass, 'attcode'=>$sAttCode, 'value'=>$value, 'matches' => $oSet->Count()));
  5019. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null;
  5020. }
  5021. }
  5022. return self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value];
  5023. }
  5024. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  5025. {
  5026. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  5027. if ($bAllowAllData)
  5028. {
  5029. $oFilter->AllowAllData();
  5030. }
  5031. $oSet = new DBObjectSet($oFilter);
  5032. $oObject = $oSet->Fetch();
  5033. return $oObject;
  5034. }
  5035. public static function GetHyperLink($sTargetClass, $iKey)
  5036. {
  5037. if ($iKey < 0)
  5038. {
  5039. return "$sTargetClass: $iKey (invalid value)";
  5040. }
  5041. $oObj = self::GetObject($sTargetClass, $iKey, false);
  5042. if (is_null($oObj))
  5043. {
  5044. // Whatever we are looking for, the root class is the key to search for
  5045. $sRootClass = self::GetRootClass($sTargetClass);
  5046. $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', array('objclass' => $sRootClass, 'objkey' => $iKey));
  5047. $oSet = new DBObjectSet($oSearch);
  5048. $oRecord = $oSet->Fetch();
  5049. // An empty fname is obtained with iTop < 2.0
  5050. if (is_null($oRecord) || (strlen(trim($oRecord->Get('fname'))) == 0))
  5051. {
  5052. $sName = Dict::Format('Core:UnknownObjectLabel', $sTargetClass, $iKey);
  5053. $sTitle = Dict::S('Core:UnknownObjectTip');
  5054. }
  5055. else
  5056. {
  5057. $sName = $oRecord->Get('fname');
  5058. $sTitle = Dict::Format('Core:DeletedObjectTip', $oRecord->Get('date'), $oRecord->Get('userinfo'));
  5059. }
  5060. return '<span class="itop-deleted-object" title="'.htmlentities($sTitle, ENT_QUOTES, 'UTF-8').'">'.htmlentities($sName, ENT_QUOTES, 'UTF-8').'</span>';
  5061. }
  5062. return $oObj->GetHyperLink();
  5063. }
  5064. public static function NewObject($sClass)
  5065. {
  5066. self::_check_subclass($sClass);
  5067. return new $sClass();
  5068. }
  5069. public static function GetNextKey($sClass)
  5070. {
  5071. $sRootClass = MetaModel::GetRootClass($sClass);
  5072. $sRootTable = MetaModel::DBGetTable($sRootClass);
  5073. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  5074. return $iNextKey;
  5075. }
  5076. /**
  5077. * Deletion of records, bypassing DBObject::DBDelete !!!
  5078. * It is NOT recommended to use this shortcut
  5079. * In particular, it will not work
  5080. * - if the class is not a final class
  5081. * - if the class has a hierarchical key (need to rebuild the indexes)
  5082. * - if the class overload DBDelete !
  5083. * Todo: protect it against forbidden usages (in such a case, delete objects one by one)
  5084. */
  5085. public static function BulkDelete(DBObjectSearch $oFilter)
  5086. {
  5087. $sSQL = self::MakeDeleteQuery($oFilter);
  5088. if (!self::DBIsReadOnly())
  5089. {
  5090. CMDBSource::Query($sSQL);
  5091. }
  5092. }
  5093. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  5094. {
  5095. // $aValues is an array of $sAttCode => $value
  5096. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  5097. if (!self::DBIsReadOnly())
  5098. {
  5099. CMDBSource::Query($sSQL);
  5100. }
  5101. }
  5102. /**
  5103. * Helper to remove selected objects without calling any handler
  5104. * Surpasses BulkDelete as it can handle abstract classes, but has the other limitation as it bypasses standard objects handlers
  5105. *
  5106. * @param string $oFilter Scope of objects to wipe out
  5107. * @return The count of deleted objects
  5108. */
  5109. public static function PurgeData($oFilter)
  5110. {
  5111. $sTargetClass = $oFilter->GetClass();
  5112. $oSet = new DBObjectSet($oFilter);
  5113. $oSet->OptimizeColumnLoad(array($sTargetClass => array('finalclass')));
  5114. $aIdToClass = $oSet->GetColumnAsArray('finalclass', true);
  5115. $aIds = array_keys($aIdToClass);
  5116. if (count($aIds) > 0)
  5117. {
  5118. $aQuotedIds = CMDBSource::Quote($aIds);
  5119. $sIdList = implode(',', $aQuotedIds);
  5120. $aTargetClasses = array_merge(
  5121. self::EnumChildClasses($sTargetClass, ENUM_CHILD_CLASSES_ALL),
  5122. self::EnumParentClasses($sTargetClass, ENUM_PARENT_CLASSES_EXCLUDELEAF)
  5123. );
  5124. foreach ($aTargetClasses as $sSomeClass)
  5125. {
  5126. $sTable = MetaModel::DBGetTable($sSomeClass);
  5127. $sPKField = MetaModel::DBGetKey($sSomeClass);
  5128. $sDeleteSQL = "DELETE FROM `$sTable` WHERE `$sPKField` IN ($sIdList)";
  5129. CMDBSource::DeleteFrom($sDeleteSQL);
  5130. }
  5131. }
  5132. return count($aIds);
  5133. }
  5134. // Links
  5135. //
  5136. //
  5137. public static function EnumReferencedClasses($sClass)
  5138. {
  5139. self::_check_subclass($sClass);
  5140. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  5141. $aResult = array();
  5142. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  5143. {
  5144. if ($oAttDef->IsExternalKey())
  5145. {
  5146. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  5147. }
  5148. }
  5149. return $aResult;
  5150. }
  5151. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  5152. {
  5153. self::_check_subclass($sClass);
  5154. if ($bSkipLinkingClasses)
  5155. {
  5156. $aLinksClasses = self::EnumLinksClasses();
  5157. }
  5158. // 1-N links (referencing my class), array of sClass => array of sAttcode
  5159. $aResult = array();
  5160. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  5161. {
  5162. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  5163. $aExtKeys = array();
  5164. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  5165. {
  5166. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  5167. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  5168. {
  5169. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  5170. // Ok, I want this one
  5171. $aExtKeys[$sAttCode] = $oAttDef;
  5172. }
  5173. }
  5174. if (count($aExtKeys) != 0)
  5175. {
  5176. $aResult[$sSomeClass] = $aExtKeys;
  5177. }
  5178. }
  5179. return $aResult;
  5180. }
  5181. /**
  5182. * It is not recommended to use this function: call GetLinkClasses instead
  5183. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  5184. * The only difference with EnumLinkingClasses is the output format
  5185. */
  5186. public static function EnumLinksClasses()
  5187. {
  5188. // Returns a flat array of classes having at least two external keys
  5189. $aResult = array();
  5190. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  5191. {
  5192. $iExtKeyCount = 0;
  5193. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  5194. {
  5195. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  5196. if ($oAttDef->IsExternalKey())
  5197. {
  5198. $iExtKeyCount++;
  5199. }
  5200. }
  5201. if ($iExtKeyCount >= 2)
  5202. {
  5203. $aResult[] = $sSomeClass;
  5204. }
  5205. }
  5206. return $aResult;
  5207. }
  5208. /**
  5209. * It is not recommended to use this function: call GetLinkClasses instead
  5210. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  5211. * The only difference with EnumLinksClasses is the output format
  5212. */
  5213. public static function EnumLinkingClasses($sClass = "")
  5214. {
  5215. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  5216. $aResult = array();
  5217. foreach (self::EnumLinksClasses() as $sSomeClass)
  5218. {
  5219. $aTargets = array();
  5220. $bFoundClass = false;
  5221. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  5222. {
  5223. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  5224. if ($oAttDef->IsExternalKey())
  5225. {
  5226. $sRemoteClass = $oAttDef->GetTargetClass();
  5227. if (empty($sClass))
  5228. {
  5229. $aTargets[$sAttCode] = $sRemoteClass;
  5230. }
  5231. elseif ($sClass == $sRemoteClass)
  5232. {
  5233. $bFoundClass = true;
  5234. }
  5235. else
  5236. {
  5237. $aTargets[$sAttCode] = $sRemoteClass;
  5238. }
  5239. }
  5240. }
  5241. if (empty($sClass) || $bFoundClass)
  5242. {
  5243. $aResult[$sSomeClass] = $aTargets;
  5244. }
  5245. }
  5246. return $aResult;
  5247. }
  5248. /**
  5249. * This function has two siblings that will be soon deprecated:
  5250. * EnumLinkingClasses and EnumLinkClasses
  5251. *
  5252. * Using GetLinkClasses is the recommended way to determine if a class is
  5253. * actually an N-N relation because it is based on the decision made by the
  5254. * designer the data model
  5255. */
  5256. public static function GetLinkClasses()
  5257. {
  5258. $aRet = array();
  5259. foreach(self::GetClasses() as $sClass)
  5260. {
  5261. if (isset(self::$m_aClassParams[$sClass]["is_link"]))
  5262. {
  5263. if (self::$m_aClassParams[$sClass]["is_link"])
  5264. {
  5265. $aExtKeys = array();
  5266. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  5267. {
  5268. if ($oAttDef->IsExternalKey())
  5269. {
  5270. $aExtKeys[$sAttCode] = $oAttDef->GetTargetClass();
  5271. }
  5272. }
  5273. $aRet[$sClass] = $aExtKeys;
  5274. }
  5275. }
  5276. }
  5277. return $aRet;
  5278. }
  5279. public static function GetLinkLabel($sLinkClass, $sAttCode)
  5280. {
  5281. self::_check_subclass($sLinkClass);
  5282. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  5283. return self::GetLabel($sLinkClass, $sAttCode);
  5284. }
  5285. /**
  5286. * Replaces all the parameters by the values passed in the hash array
  5287. */
  5288. static public function ApplyParams($sInput, $aParams)
  5289. {
  5290. // Declare magic parameters
  5291. $aParams['APP_URL'] = utils::GetAbsoluteUrlAppRoot();
  5292. $aParams['MODULES_URL'] = utils::GetAbsoluteUrlModulesRoot();
  5293. $aSearches = array();
  5294. $aReplacements = array();
  5295. foreach($aParams as $sSearch => $replace)
  5296. {
  5297. // Some environment parameters are objects, we just need scalars
  5298. if (is_object($replace))
  5299. {
  5300. $iPos = strpos($sSearch, '->object()');
  5301. if ($iPos !== false)
  5302. {
  5303. // Expand the parameters for the object
  5304. $sName = substr($sSearch, 0, $iPos);
  5305. if (preg_match_all('/\\$'.$sName.'->([^\\$]+)\\$/', $sInput, $aMatches))
  5306. {
  5307. foreach($aMatches[1] as $sPlaceholderAttCode)
  5308. {
  5309. try
  5310. {
  5311. $sReplacement = $replace->GetForTemplate($sPlaceholderAttCode);
  5312. if ($sReplacement !== null)
  5313. {
  5314. $aReplacements[] = $sReplacement;
  5315. $aSearches[] = '$'.$sName.'->'.$sPlaceholderAttCode.'$';
  5316. }
  5317. }
  5318. catch(Exception $e)
  5319. {
  5320. // No replacement will occur
  5321. }
  5322. }
  5323. }
  5324. }
  5325. else
  5326. {
  5327. continue; // Ignore this non-scalar value
  5328. }
  5329. }
  5330. $aSearches[] = '$'.$sSearch.'$';
  5331. $aReplacements[] = (string) $replace;
  5332. }
  5333. return str_replace($aSearches, $aReplacements, $sInput);
  5334. }
  5335. /**
  5336. * Returns an array of classes=>instance implementing the given interface
  5337. */
  5338. public static function EnumPlugins($sInterface)
  5339. {
  5340. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  5341. {
  5342. return self::$m_aExtensionClasses[$sInterface];
  5343. }
  5344. else
  5345. {
  5346. return array();
  5347. }
  5348. }
  5349. /**
  5350. * Returns the instance of the specified plug-ins for the given interface
  5351. */
  5352. public static function GetPlugins($sInterface, $sClassName)
  5353. {
  5354. $oInstance = null;
  5355. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  5356. {
  5357. if (array_key_exists($sClassName, self::$m_aExtensionClasses[$sInterface]))
  5358. {
  5359. return self::$m_aExtensionClasses[$sInterface][$sClassName];
  5360. }
  5361. }
  5362. return $oInstance;
  5363. }
  5364. public static function GetCacheEntries($sEnvironment = null)
  5365. {
  5366. if (!function_exists('apc_cache_info')) return array();
  5367. if (is_null($sEnvironment))
  5368. {
  5369. $sEnvironment = MetaModel::GetEnvironmentId();
  5370. }
  5371. $aEntries = array();
  5372. if (extension_loaded('apcu'))
  5373. {
  5374. // Beware: APCu behaves slightly differently from APC !!
  5375. $aCacheUserData = @apc_cache_info();
  5376. }
  5377. else
  5378. {
  5379. $aCacheUserData = @apc_cache_info('user');
  5380. }
  5381. if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list']))
  5382. {
  5383. $sPrefix = 'itop-'.$sEnvironment.'-';
  5384. foreach($aCacheUserData['cache_list'] as $i => $aEntry)
  5385. {
  5386. $sEntryKey = array_key_exists('info', $aEntry) ? $aEntry['info'] : $aEntry['key'];
  5387. if (strpos($sEntryKey, $sPrefix) === 0)
  5388. {
  5389. $sCleanKey = substr($sEntryKey, strlen($sPrefix));
  5390. $aEntries[$sCleanKey] = $aEntry;
  5391. $aEntries[$sCleanKey]['info'] = $sEntryKey;
  5392. }
  5393. }
  5394. }
  5395. return $aEntries;
  5396. }
  5397. public static function ResetCache($sEnvironmentId = null)
  5398. {
  5399. if (!function_exists('apc_delete')) return;
  5400. if (is_null($sEnvironmentId))
  5401. {
  5402. $sEnvironmentId = MetaModel::GetEnvironmentId();
  5403. }
  5404. $sAppIdentity = 'itop-'.$sEnvironmentId;
  5405. Dict::ResetCache($sAppIdentity);
  5406. foreach(self::GetCacheEntries($sEnvironmentId) as $sKey => $aAPCInfo)
  5407. {
  5408. $sAPCKey = $aAPCInfo['info'];
  5409. apc_delete($sAPCKey);
  5410. }
  5411. }
  5412. } // class MetaModel
  5413. // Standard attribute lists
  5414. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  5415. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  5416. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  5417. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  5418. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  5419. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));