metamodel.class.php 198 KB

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