metamodel.class.php 200 KB

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