metamodel.class.php 186 KB

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