metamodel.class.php 185 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505
  1. <?php
  2. // Copyright (C) 2010-2013 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. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $aAttToLoad = null, $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false)
  2036. {
  2037. // Check the order by specification, and prefix with the class alias
  2038. // and make sure that the ordering columns are going to be selected
  2039. //
  2040. $sClass = $oFilter->GetClass();
  2041. $sClassAlias = $oFilter->GetClassAlias();
  2042. $aOrderSpec = array();
  2043. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  2044. {
  2045. if ($sFieldAlias != 'id')
  2046. {
  2047. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sFieldAlias, self::GetAttributesList($sClass));
  2048. }
  2049. if (!is_bool($bAscending))
  2050. {
  2051. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  2052. }
  2053. if (self::IsValidAttCode($sClass, $sFieldAlias))
  2054. {
  2055. $oAttDef = self::GetAttributeDef($sClass, $sFieldAlias);
  2056. foreach($oAttDef->GetOrderBySQLExpressions($sClassAlias) as $sSQLExpression)
  2057. {
  2058. $aOrderSpec[$sSQLExpression] = $bAscending;
  2059. }
  2060. }
  2061. else
  2062. {
  2063. $aOrderSpec['`'.$sClassAlias.$sFieldAlias.'`'] = $bAscending;
  2064. }
  2065. // Make sure that the columns used for sorting are present in the loaded columns
  2066. if (!is_null($aAttToLoad) && !isset($aAttToLoad[$sClassAlias][$sFieldAlias]))
  2067. {
  2068. $aAttToLoad[$sClassAlias][$sFieldAlias] = MetaModel::GetAttributeDef($sClass, $sFieldAlias);
  2069. }
  2070. }
  2071. $oSelect = self::MakeSelectStructure($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount);
  2072. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2073. try
  2074. {
  2075. $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
  2076. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount, $bBeautifulSQL);
  2077. if ($sClassAlias == '_itop_')
  2078. {
  2079. echo $sRes."<br/>\n";
  2080. }
  2081. }
  2082. catch (MissingQueryArgument $e)
  2083. {
  2084. // Add some information...
  2085. $e->addInfo('OQL', $oFilter->ToOQL());
  2086. throw $e;
  2087. }
  2088. self::AddQueryTraceSelect($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sRes);
  2089. return $sRes;
  2090. }
  2091. protected static function MakeSelectStructure(DBObjectSearch $oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $aGroupByExpr = null)
  2092. {
  2093. // Hide objects that are not visible to the current user
  2094. //
  2095. if (!$oFilter->IsAllDataAllowed() && !$oFilter->IsDataFiltered())
  2096. {
  2097. $oVisibleObjects = UserRights::GetSelectFilter($oFilter->GetClass(), $oFilter->GetModifierProperties('UserRightsGetSelectFilter'));
  2098. if ($oVisibleObjects === false)
  2099. {
  2100. // Make sure this is a valid search object, saying NO for all
  2101. $oVisibleObjects = DBObjectSearch::FromEmptySet($oFilter->GetClass());
  2102. }
  2103. if (is_object($oVisibleObjects))
  2104. {
  2105. $oFilter->MergeWith($oVisibleObjects);
  2106. $oFilter->SetDataFiltered();
  2107. }
  2108. else
  2109. {
  2110. // should be true at this point, meaning that no additional filtering
  2111. // is required
  2112. }
  2113. }
  2114. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2115. //
  2116. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2117. // Create a unique cache id
  2118. //
  2119. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  2120. {
  2121. // Need to identify the query
  2122. $sOqlQuery = $oFilter->ToOql();
  2123. if (count($aModifierProperties))
  2124. {
  2125. array_multisort($aModifierProperties);
  2126. $sModifierProperties = json_encode($aModifierProperties);
  2127. }
  2128. else
  2129. {
  2130. $sModifierProperties = '';
  2131. }
  2132. $sRawId = $sOqlQuery.$sModifierProperties;
  2133. if (!is_null($aAttToLoad))
  2134. {
  2135. $sRawId .= json_encode($aAttToLoad);
  2136. }
  2137. if (!is_null($aGroupByExpr))
  2138. {
  2139. foreach($aGroupByExpr as $sAlias => $oExpr)
  2140. {
  2141. $sRawId .= 'g:'.$sAlias.'!'.$oExpr->Render();
  2142. }
  2143. }
  2144. $sRawId .= $bGetCount;
  2145. $sOqlId = md5($sRawId);
  2146. }
  2147. else
  2148. {
  2149. $sOqlQuery = "SELECTING... ".$oFilter->GetClass();
  2150. $sOqlId = "query id ? n/a";
  2151. }
  2152. // Query caching
  2153. //
  2154. if (self::$m_bQueryCacheEnabled)
  2155. {
  2156. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  2157. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  2158. // to use a hash (like md5) of the string as the key !
  2159. //
  2160. // Example of two queries that were found as similar by the hash array:
  2161. // 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
  2162. // and
  2163. // 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
  2164. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  2165. //
  2166. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  2167. {
  2168. // hit!
  2169. $oSelect = unserialize(serialize(self::$m_aQueryStructCache[$sOqlId]));
  2170. // Note: cloning is not enough because the subtree is made of objects
  2171. }
  2172. elseif (self::$m_bUseAPCCache)
  2173. {
  2174. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  2175. //
  2176. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-query-cache-'.$sOqlId;
  2177. $oKPI = new ExecutionKPI();
  2178. $result = apc_fetch($sOqlAPCCacheId);
  2179. $oKPI->ComputeStats('Query APC (fetch)', $sOqlQuery);
  2180. if (is_object($result))
  2181. {
  2182. $oSelect = $result;
  2183. self::$m_aQueryStructCache[$sOqlId] = $oSelect;
  2184. }
  2185. }
  2186. }
  2187. if (!isset($oSelect))
  2188. {
  2189. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties, $aGroupByExpr);
  2190. $oKPI = new ExecutionKPI();
  2191. $oSelect = self::MakeQuery($oBuild, $oFilter, $aAttToLoad, array(), true /* main query */);
  2192. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2193. $oSelect->SetSourceOQL($sOqlQuery);
  2194. if ($aGroupByExpr)
  2195. {
  2196. $aCols = $oBuild->m_oQBExpressions->GetGroupBy();
  2197. $oSelect->SetGroupBy($aCols);
  2198. $oSelect->SetSelect($aCols);
  2199. }
  2200. else
  2201. {
  2202. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2203. }
  2204. if (self::$m_bOptimizeQueries)
  2205. {
  2206. if ($bGetCount)
  2207. {
  2208. // Simplify the query if just getting the count
  2209. $oSelect->SetSelect(array());
  2210. }
  2211. $oBuild->m_oQBExpressions->GetMandatoryTables($aMandatoryTables);
  2212. $oSelect->OptimizeJoins($aMandatoryTables);
  2213. }
  2214. $oKPI->ComputeStats('MakeQuery (select)', $sOqlQuery);
  2215. if (self::$m_bQueryCacheEnabled)
  2216. {
  2217. if (self::$m_bUseAPCCache)
  2218. {
  2219. $oKPI = new ExecutionKPI();
  2220. apc_store($sOqlAPCCacheId, $oSelect, self::$m_iQueryCacheTTL);
  2221. $oKPI->ComputeStats('Query APC (store)', $sOqlQuery);
  2222. }
  2223. self::$m_aQueryStructCache[$sOqlId] = $oSelect->DeepClone();
  2224. }
  2225. }
  2226. // Join to an additional table, if required...
  2227. //
  2228. if ($aExtendedDataSpec != null)
  2229. {
  2230. $sTableAlias = '_extended_data_';
  2231. $aExtendedFields = array();
  2232. foreach($aExtendedDataSpec['fields'] as $sColumn)
  2233. {
  2234. $sColRef = $oFilter->GetClassAlias().'_extdata_'.$sColumn;
  2235. $aExtendedFields[$sColRef] = new FieldExpressionResolved($sColumn, $sTableAlias);
  2236. }
  2237. $oSelectExt = new SQLQuery($aExtendedDataSpec['table'], $sTableAlias, $aExtendedFields);
  2238. $oSelect->AddInnerJoin($oSelectExt, 'id', $aExtendedDataSpec['join_key'] /*, $sTableAlias*/);
  2239. }
  2240. return $oSelect;
  2241. }
  2242. protected static function AddQueryTraceSelect($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sSql)
  2243. {
  2244. if (self::$m_bTraceQueries)
  2245. {
  2246. $aQueryData = array(
  2247. 'type' => 'select',
  2248. 'filter' => $oFilter,
  2249. 'order_by' => $aOrderBy,
  2250. 'args' => $aArgs,
  2251. 'att_to_load' => $aAttToLoad,
  2252. 'extended_data_spec' => $aExtendedDataSpec,
  2253. 'limit_count' => $iLimitCount,
  2254. 'limit_start' => $iLimitStart,
  2255. 'is_count' => $bGetCount
  2256. );
  2257. $sOql = $oFilter->ToOQL(true, $aArgs);
  2258. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  2259. }
  2260. }
  2261. protected static function AddQueryTraceGroupBy($oFilter, $aArgs, $aGroupByExpr, $sSql)
  2262. {
  2263. if (self::$m_bTraceQueries)
  2264. {
  2265. $aQueryData = array(
  2266. 'type' => 'group_by',
  2267. 'filter' => $oFilter,
  2268. 'args' => $aArgs,
  2269. 'group_by_expr' => $aGroupByExpr
  2270. );
  2271. $sOql = $oFilter->ToOQL(true, $aArgs);
  2272. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  2273. }
  2274. }
  2275. protected static function AddQueryTrace($aQueryData, $sOql, $sSql)
  2276. {
  2277. if (self::$m_bTraceQueries)
  2278. {
  2279. $sQueryId = md5(serialize($aQueryData));
  2280. $sMySQLQueryId = md5($sSql);
  2281. if(!isset(self::$m_aQueriesLog[$sQueryId]))
  2282. {
  2283. self::$m_aQueriesLog[$sQueryId]['data'] = serialize($aQueryData);
  2284. self::$m_aQueriesLog[$sQueryId]['oql'] = $sOql;
  2285. self::$m_aQueriesLog[$sQueryId]['hits'] = 1;
  2286. }
  2287. else
  2288. {
  2289. self::$m_aQueriesLog[$sQueryId]['hits']++;
  2290. }
  2291. if(!isset(self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]))
  2292. {
  2293. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['sql'] = $sSql;
  2294. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count'] = 1;
  2295. $iTableCount = count(CMDBSource::ExplainQuery($sSql));
  2296. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['table_count'] = $iTableCount;
  2297. }
  2298. else
  2299. {
  2300. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count']++;
  2301. }
  2302. }
  2303. }
  2304. public static function RecordQueryTrace()
  2305. {
  2306. if (!self::$m_bTraceQueries) return;
  2307. $iOqlCount = count(self::$m_aQueriesLog);
  2308. $iSqlCount = 0;
  2309. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2310. {
  2311. $iSqlCount += $aOqlData['hits'];
  2312. }
  2313. $sHtml = "<h2>Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount</h2>\n";
  2314. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2315. {
  2316. $sOql = $aOqlData['oql'];
  2317. $sHits = $aOqlData['hits'];
  2318. $sHtml .= "<p><b>$sHits</b> hits for OQL query: $sOql</p>\n";
  2319. $sHtml .= "<ul id=\"ClassesRelationships\" class=\"treeview\">\n";
  2320. foreach($aOqlData['queries'] as $aSqlData)
  2321. {
  2322. $sQuery = $aSqlData['sql'];
  2323. $sSqlHits = $aSqlData['count'];
  2324. $iTableCount = $aSqlData['table_count'];
  2325. $sHtml .= "<li><b>$sSqlHits</b> hits for SQL ($iTableCount tables): <pre style=\"font-size:60%\">$sQuery</pre></li>\n";
  2326. }
  2327. $sHtml .= "</ul>\n";
  2328. }
  2329. $sLogFile = 'queries.latest';
  2330. file_put_contents(APPROOT.'data/'.$sLogFile.'.html', $sHtml);
  2331. $sLog = "<?php\n\$aQueriesLog = ".var_export(self::$m_aQueriesLog, true).";";
  2332. file_put_contents(APPROOT.'data/'.$sLogFile.'.log', $sLog);
  2333. // Cumulate the queries
  2334. $sAllQueries = APPROOT.'data/queries.log';
  2335. if (file_exists($sAllQueries))
  2336. {
  2337. // Merge the new queries into the existing log
  2338. include($sAllQueries);
  2339. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2340. {
  2341. if (!array_key_exists($sQueryId, $aQueriesLog))
  2342. {
  2343. $aQueriesLog[$sQueryId] = $aOqlData;
  2344. }
  2345. }
  2346. }
  2347. else
  2348. {
  2349. $aQueriesLog = self::$m_aQueriesLog;
  2350. }
  2351. $sLog = "<?php\n\$aQueriesLog = ".var_export($aQueriesLog, true).";";
  2352. file_put_contents($sAllQueries, $sLog);
  2353. }
  2354. protected static function MakeModifierProperties($oFilter)
  2355. {
  2356. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2357. //
  2358. $aModifierProperties = array();
  2359. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  2360. {
  2361. // Lowest precedence: the application context
  2362. $aPluginProps = ApplicationContext::GetPluginProperties($sPluginClass);
  2363. // Highest precedence: programmatically specified (or OQL)
  2364. foreach($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value)
  2365. {
  2366. $aPluginProps[$sProp] = $value;
  2367. }
  2368. if (count($aPluginProps) > 0)
  2369. {
  2370. $aModifierProperties[$sPluginClass] = $aPluginProps;
  2371. }
  2372. }
  2373. return $aModifierProperties;
  2374. }
  2375. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  2376. {
  2377. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2378. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties);
  2379. $oSelect = self::MakeQuery($oBuild, $oFilter, null, array(), true /* main query */);
  2380. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2381. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2382. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2383. return $oSelect->RenderDelete($aScalarArgs);
  2384. }
  2385. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  2386. {
  2387. // $aValues is an array of $sAttCode => $value
  2388. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2389. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties);
  2390. $oSelect = self::MakeQuery($oBuild, $oFilter, null, $aValues, true /* main query */);
  2391. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2392. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2393. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2394. return $oSelect->RenderUpdate($aScalarArgs);
  2395. }
  2396. private static function MakeQuery(&$oBuild, DBObjectSearch $oFilter, $aAttToLoad = null, $aValues = array(), $bIsMainQueryUNUSED = false)
  2397. {
  2398. // Note: query class might be different than the class of the filter
  2399. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  2400. $sClass = $oFilter->GetFirstJoinedClass();
  2401. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  2402. $bIsOnQueriedClass = array_key_exists($sClassAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  2403. self::DbgTrace("Entering: ".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  2404. $sRootClass = self::GetRootClass($sClass);
  2405. $sKeyField = self::DBGetKey($sClass);
  2406. if ($bIsOnQueriedClass)
  2407. {
  2408. // default to the whole list of attributes + the very std id/finalclass
  2409. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.'id', new FieldExpression('id', $sClassAlias));
  2410. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  2411. {
  2412. $aAttList = self::ListAttributeDefs($sClass);
  2413. }
  2414. else
  2415. {
  2416. $aAttList = $aAttToLoad[$sClassAlias];
  2417. }
  2418. foreach ($aAttList as $sAttCode => $oAttDef)
  2419. {
  2420. if (!$oAttDef->IsScalar()) continue;
  2421. // keep because it can be used for sorting - if (!$oAttDef->LoadInObject()) continue;
  2422. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  2423. {
  2424. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.$sAttCode.$sColId, new FieldExpression($sAttCode.$sColId, $sClassAlias));
  2425. }
  2426. }
  2427. // Transform the full text condition into additional condition expression
  2428. $aFullText = $oFilter->GetCriteria_FullText();
  2429. if (count($aFullText) > 0)
  2430. {
  2431. $aFullTextFields = array();
  2432. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2433. {
  2434. if (!$oAttDef->IsScalar()) continue;
  2435. if ($oAttDef->IsExternalKey()) continue;
  2436. $aFullTextFields[] = new FieldExpression($sAttCode, $sClassAlias);
  2437. }
  2438. $oTextFields = new CharConcatWSExpression(' ', $aFullTextFields);
  2439. foreach($aFullText as $sFTNeedle)
  2440. {
  2441. $oNewCond = new BinaryExpression($oTextFields, 'LIKE', new ScalarExpression("%$sFTNeedle%"));
  2442. $oBuild->m_oQBExpressions->AddCondition($oNewCond);
  2443. }
  2444. }
  2445. }
  2446. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  2447. $aExpectedAtts = array(); // array of (attcode => fieldexpression)
  2448. //echo "<p>".__LINE__.": GetUnresolvedFields($sClassAlias, ...)</p>\n";
  2449. $oBuild->m_oQBExpressions->GetUnresolvedFields($sClassAlias, $aExpectedAtts);
  2450. // Compute a clear view of required joins (from the current class)
  2451. // Build the list of external keys:
  2452. // -> ext keys required by an explicit join
  2453. // -> ext keys mentionned in a 'pointing to' condition
  2454. // -> ext keys required for an external field
  2455. // -> ext keys required for a friendly name
  2456. //
  2457. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  2458. //
  2459. // Optimization: could be partially computed once for all (cached) ?
  2460. //
  2461. if ($bIsOnQueriedClass)
  2462. {
  2463. // Get all Ext keys for the queried class (??)
  2464. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  2465. {
  2466. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2467. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  2468. }
  2469. }
  2470. // Get all Ext keys used by the filter
  2471. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $aPointingTo)
  2472. {
  2473. if (array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  2474. {
  2475. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2476. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  2477. }
  2478. }
  2479. $aFNJoinAlias = array(); // array of (subclass => alias)
  2480. if (array_key_exists('friendlyname', $aExpectedAtts))
  2481. {
  2482. // To optimize: detect a restriction on child classes in the condition expression
  2483. // e.g. SELECT FunctionalCI WHERE finalclass IN ('Server', 'VirtualMachine')
  2484. $oNameExpression = self::GetExtendedNameExpression($sClass);
  2485. $aNameFields = array();
  2486. $oNameExpression->GetUnresolvedFields('', $aNameFields);
  2487. $aTranslateNameFields = array();
  2488. foreach($aNameFields as $sSubClass => $aFields)
  2489. {
  2490. foreach($aFields as $sAttCode => $oField)
  2491. {
  2492. $oAttDef = self::GetAttributeDef($sSubClass, $sAttCode);
  2493. if ($oAttDef->IsExternalKey())
  2494. {
  2495. $sClassOfAttribute = self::$m_aAttribOrigins[$sSubClass][$sAttCode];
  2496. $aExtKeys[$sClassOfAttribute][$sAttCode] = array();
  2497. }
  2498. elseif ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  2499. {
  2500. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2501. $sClassOfAttribute = self::$m_aAttribOrigins[$sSubClass][$sKeyAttCode];
  2502. $aExtKeys[$sClassOfAttribute][$sKeyAttCode][$sAttCode] = $oAttDef;
  2503. }
  2504. else
  2505. {
  2506. $sClassOfAttribute = self::GetAttributeOrigin($sSubClass, $sAttCode);
  2507. }
  2508. if (self::IsParentClass($sClassOfAttribute, $sClass))
  2509. {
  2510. // The attribute is part of the standard query
  2511. //
  2512. $sAliasForAttribute = $sClassAlias;
  2513. }
  2514. else
  2515. {
  2516. // The attribute will be available from an additional outer join
  2517. // For each subclass (table) one single join is enough
  2518. //
  2519. if (!array_key_exists($sClassOfAttribute, $aFNJoinAlias))
  2520. {
  2521. $sAliasForAttribute = $oBuild->GenerateClassAlias($sClassAlias.'_fn_'.$sClassOfAttribute, $sClassOfAttribute);
  2522. $aFNJoinAlias[$sClassOfAttribute] = $sAliasForAttribute;
  2523. }
  2524. else
  2525. {
  2526. $sAliasForAttribute = $aFNJoinAlias[$sClassOfAttribute];
  2527. }
  2528. }
  2529. $aTranslateNameFields[$sSubClass][$sAttCode] = new FieldExpression($sAttCode, $sAliasForAttribute);
  2530. }
  2531. }
  2532. $oNameExpression = $oNameExpression->Translate($aTranslateNameFields, false);
  2533. $aTranslateNow = array();
  2534. $aTranslateNow[$sClassAlias]['friendlyname'] = $oNameExpression;
  2535. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  2536. }
  2537. // Add the ext fields used in the select (eventually adds an external key)
  2538. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2539. {
  2540. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  2541. {
  2542. if (array_key_exists($sAttCode, $aExpectedAtts))
  2543. {
  2544. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2545. if ($sKeyAttCode != 'id')
  2546. {
  2547. // Add the external attribute
  2548. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2549. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  2550. }
  2551. }
  2552. }
  2553. }
  2554. // First query built upon on the leaf (ie current) class
  2555. //
  2556. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  2557. if (self::HasTable($sClass))
  2558. {
  2559. $oSelectBase = self::MakeQuerySingleTable($oBuild, $oFilter, $sClass, $aExtKeys, $aValues);
  2560. }
  2561. else
  2562. {
  2563. $oSelectBase = null;
  2564. // As the join will not filter on the expected classes, we have to specify it explicitely
  2565. $sExpectedClasses = implode("', '", self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  2566. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  2567. $oBuild->m_oQBExpressions->AddCondition($oFinalClassRestriction);
  2568. }
  2569. // Then we join the queries of the eventual parent classes (compound model)
  2570. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  2571. {
  2572. if (!self::HasTable($sParentClass)) continue;
  2573. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  2574. $oSelectParentTable = self::MakeQuerySingleTable($oBuild, $oFilter, $sParentClass, $aExtKeys, $aValues);
  2575. if (is_null($oSelectBase))
  2576. {
  2577. $oSelectBase = $oSelectParentTable;
  2578. }
  2579. else
  2580. {
  2581. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  2582. }
  2583. }
  2584. // Filter on objects referencing me
  2585. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  2586. {
  2587. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  2588. {
  2589. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  2590. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  2591. //self::DbgTrace($oForeignFilter);
  2592. //self::DbgTrace($oForeignFilter->ToOQL());
  2593. //self::DbgTrace($oSelectForeign);
  2594. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  2595. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  2596. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sForeignKeyAttCode, $sForeignClassAlias));
  2597. $oSelectForeign = self::MakeQuery($oBuild, $oForeignFilter, $aAttToLoad);
  2598. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  2599. $sForeignKeyTable = $oJoinExpr->GetParent();
  2600. $sForeignKeyColumn = $oJoinExpr->GetName();
  2601. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  2602. }
  2603. }
  2604. // Filter on related objects
  2605. //
  2606. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  2607. {
  2608. $oSubFilter = $aCritInfo['flt'];
  2609. $sRelCode = $aCritInfo['relcode'];
  2610. $iMaxDepth = $aCritInfo['maxdepth'];
  2611. // Get the starting point objects
  2612. $oStartSet = new CMDBObjectSet($oSubFilter);
  2613. // Get the objects related to those objects... recursively...
  2614. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  2615. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  2616. // #@# todo - related objects and expressions...
  2617. // Create condition
  2618. if (count($aRestriction) > 0)
  2619. {
  2620. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  2621. }
  2622. else
  2623. {
  2624. // Quick N'dirty -> generate an empty set
  2625. $oSelectBase->AddCondition('false');
  2626. }
  2627. }
  2628. // Additional JOINS for Friendly names
  2629. //
  2630. foreach ($aFNJoinAlias as $sSubClass => $sSubClassAlias)
  2631. {
  2632. $oSubClassFilter = new DBObjectSearch($sSubClass, $sSubClassAlias);
  2633. $oSelectFN = self::MakeQuerySingleTable($oBuild, $oSubClassFilter, $sSubClass, $aExtKeys, array());
  2634. $oSelectBase->AddLeftJoin($oSelectFN, $sKeyField, self::DBGetKey($sSubClass));
  2635. }
  2636. // That's all... cross fingers and we'll get some working query
  2637. //MyHelpers::var_dump_html($oSelectBase, true);
  2638. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  2639. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  2640. return $oSelectBase;
  2641. }
  2642. protected static function MakeQuerySingleTable(&$oBuild, $oFilter, $sTableClass, $aExtKeys, $aValues)
  2643. {
  2644. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  2645. //echo "MAKEQUERY($sTableClass)-liste des clefs externes($sTableClass): <pre>".print_r($aExtKeys, true)."</pre><br/>\n";
  2646. // Prepare the query for a single table (compound objects)
  2647. // Ignores the items (attributes/filters) that are not on the target table
  2648. // Perform an (inner or left) join for every external key (and specify the expected fields)
  2649. //
  2650. // Returns an SQLQuery
  2651. //
  2652. $sTargetClass = $oFilter->GetFirstJoinedClass();
  2653. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  2654. $sTable = self::DBGetTable($sTableClass);
  2655. $sTableAlias = $oBuild->GenerateTableAlias($sTargetAlias.'_'.$sTable, $sTable);
  2656. $aTranslation = array();
  2657. $aExpectedAtts = array();
  2658. $oBuild->m_oQBExpressions->GetUnresolvedFields($sTargetAlias, $aExpectedAtts);
  2659. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  2660. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  2661. // 1 - SELECT and UPDATE
  2662. //
  2663. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  2664. //
  2665. $aUpdateValues = array();
  2666. // 1/a - Get the key and friendly name
  2667. //
  2668. // We need one pkey to be the key, let's take the first one available
  2669. $oSelectedIdField = null;
  2670. $oIdField = new FieldExpressionResolved(self::DBGetKey($sTableClass), $sTableAlias);
  2671. $aTranslation[$sTargetAlias]['id'] = $oIdField;
  2672. if ($bIsOnQueriedClass)
  2673. {
  2674. // Add this field to the list of queried fields (required for the COUNT to work fine)
  2675. $oSelectedIdField = $oIdField;
  2676. }
  2677. // 1/b - Get the other attributes
  2678. //
  2679. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  2680. {
  2681. // Skip this attribute if not defined in this table
  2682. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  2683. // Skip this attribute if not made of SQL columns
  2684. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  2685. // Update...
  2686. //
  2687. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  2688. {
  2689. assert ($oAttDef->IsDirectField());
  2690. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  2691. {
  2692. $aUpdateValues[$sColumn] = $sValue;
  2693. }
  2694. }
  2695. }
  2696. // 2 - The SQL query, for this table only
  2697. //
  2698. $oSelectBase = new SQLQuery($sTable, $sTableAlias, array(), $bIsOnQueriedClass, $aUpdateValues, $oSelectedIdField);
  2699. // 3 - Resolve expected expressions (translation table: alias.attcode => table.column)
  2700. //
  2701. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  2702. {
  2703. // Skip this attribute if not defined in this table
  2704. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  2705. // Select...
  2706. //
  2707. if ($oAttDef->IsExternalField())
  2708. {
  2709. // skip, this will be handled in the joined tables (done hereabove)
  2710. }
  2711. else
  2712. {
  2713. //echo "<p>MakeQuerySingleTable: Field $sAttCode is part of the table $sTable (named: $sTableAlias)</p>";
  2714. // standard field, or external key
  2715. // add it to the output
  2716. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  2717. {
  2718. if (array_key_exists($sAttCode.$sColId, $aExpectedAtts))
  2719. {
  2720. $oFieldSQLExp = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  2721. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  2722. {
  2723. $oFieldSQLExp = $oQueryModifier->GetFieldExpression($oBuild, $sTargetClass, $sAttCode, $sColId, $oFieldSQLExp, $oSelectBase);
  2724. }
  2725. $aTranslation[$sTargetAlias][$sAttCode.$sColId] = $oFieldSQLExp;
  2726. }
  2727. }
  2728. }
  2729. }
  2730. //echo "MAKEQUERY- Classe $sTableClass<br/>\n";
  2731. // 4 - The external keys -> joins...
  2732. //
  2733. $aAllPointingTo = $oFilter->GetCriteria_PointingTo();
  2734. if (array_key_exists($sTableClass, $aExtKeys))
  2735. {
  2736. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  2737. {
  2738. $oKeyAttDef = self::GetAttributeDef($sTableClass, $sKeyAttCode);
  2739. $aPointingTo = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  2740. //echo "MAKEQUERY-Cle '$sKeyAttCode'<br/>\n";
  2741. if (!array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  2742. {
  2743. //echo "MAKEQUERY-Ajoutons l'operateur TREE_OPERATOR_EQUALS pour $sKeyAttCode<br/>\n";
  2744. // The join was not explicitely defined in the filter,
  2745. // we need to do it now
  2746. $sKeyClass = $oKeyAttDef->GetTargetClass();
  2747. $sKeyClassAlias = $oBuild->GenerateClassAlias($sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  2748. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  2749. $aAllPointingTo[$sKeyAttCode][TREE_OPERATOR_EQUALS][$sKeyClassAlias] = $oExtFilter;
  2750. }
  2751. }
  2752. }
  2753. //echo "MAKEQUERY-liste des clefs de jointure: <pre>".print_r(array_keys($aAllPointingTo), true)."</pre><br/>\n";
  2754. foreach ($aAllPointingTo as $sKeyAttCode => $aPointingTo)
  2755. {
  2756. foreach($aPointingTo as $iOperatorCode => $aFilter)
  2757. {
  2758. foreach($aFilter as $oExtFilter)
  2759. {
  2760. if (!MetaModel::IsValidAttCode($sTableClass, $sKeyAttCode)) continue; // Not defined in the class, skip it
  2761. // The aliases should not conflict because normalization occured while building the filter
  2762. $oKeyAttDef = self::GetAttributeDef($sTableClass, $sKeyAttCode);
  2763. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  2764. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  2765. //echo "MAKEQUERY-$sTableClass::$sKeyAttCode Foreach PointingTo($iOperatorCode) <span style=\"color:red\">$sKeyClass (alias:$sKeyClassAlias)</span><br/>\n";
  2766. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  2767. //echo "MAKEQUERY-array_key_exists($sTableClass, \$aExtKeys)<br/>\n";
  2768. if ($iOperatorCode == TREE_OPERATOR_EQUALS)
  2769. {
  2770. if (array_key_exists($sTableClass, $aExtKeys) && array_key_exists($sKeyAttCode, $aExtKeys[$sTableClass]))
  2771. {
  2772. // Specify expected attributes for the target class query
  2773. // ... and use the current alias !
  2774. $aTranslateNow = array(); // Translation for external fields - must be performed before the join is done (recursion...)
  2775. foreach($aExtKeys[$sTableClass][$sKeyAttCode] as $sAttCode => $oAtt)
  2776. {
  2777. //echo "MAKEQUERY aExtKeys[$sTableClass][$sKeyAttCode] => $sAttCode-oAtt: <pre>".print_r($oAtt, true)."</pre><br/>\n";
  2778. if ($oAtt instanceof AttributeFriendlyName)
  2779. {
  2780. // Note: for a given ext key, there is one single attribute "friendly name"
  2781. $aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);
  2782. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);</b></p>\n";
  2783. }
  2784. else
  2785. {
  2786. $sExtAttCode = $oAtt->GetExtAttCode();
  2787. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  2788. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  2789. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  2790. {
  2791. $aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);
  2792. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);</b></p>\n";
  2793. }
  2794. //echo "<p><b>ExtAttr2: $sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</b></p>\n";
  2795. }
  2796. }
  2797. // Translate prior to recursing
  2798. //
  2799. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."\n".print_r($aTranslateNow, true)."</pre></p>\n";
  2800. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  2801. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  2802. //echo "<p>External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()/p>\n";
  2803. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  2804. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression('id', $sKeyClassAlias));
  2805. //echo "<p>Recursive MakeQuery ".__LINE__.": <pre>\n".print_r($oBuild->GetRootFilter()->GetSelectedClasses(), true)."</pre></p>\n";
  2806. $oSelectExtKey = self::MakeQuery($oBuild, $oExtFilter);
  2807. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  2808. $sExternalKeyTable = $oJoinExpr->GetParent();
  2809. $sExternalKeyField = $oJoinExpr->GetName();
  2810. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  2811. $sLocalKeyField = current($aCols); // get the first column for an external key
  2812. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  2813. if ($oKeyAttDef->IsNullAllowed())
  2814. {
  2815. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  2816. }
  2817. else
  2818. {
  2819. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  2820. }
  2821. }
  2822. }
  2823. elseif(self::$m_aAttribOrigins[$sKeyClass][$sKeyAttCode] == $sTableClass)
  2824. {
  2825. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sKeyAttCode, $sKeyClassAlias));
  2826. $oSelectExtKey = self::MakeQuery($oBuild, $oExtFilter);
  2827. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  2828. //echo "MAKEQUERY-PopJoinField pour $sKeyAttCode, $sKeyClassAlias: <pre>".print_r($oJoinExpr, true)."</pre><br/>\n";
  2829. $sExternalKeyTable = $oJoinExpr->GetParent();
  2830. $sExternalKeyField = $oJoinExpr->GetName();
  2831. $sLeftIndex = $sExternalKeyField.'_left'; // TODO use GetSQLLeft()
  2832. $sRightIndex = $sExternalKeyField.'_right'; // TODO use GetSQLRight()
  2833. $LocalKeyLeft = $oKeyAttDef->GetSQLLeft();
  2834. $LocalKeyRight = $oKeyAttDef->GetSQLRight();
  2835. //echo "MAKEQUERY-LocalKeyLeft pour $sKeyAttCode => $LocalKeyLeft<br/>\n";
  2836. $oSelectBase->AddInnerJoinTree($oSelectExtKey, $LocalKeyLeft, $LocalKeyRight, $sLeftIndex, $sRightIndex, $sExternalKeyTable, $iOperatorCode);
  2837. }
  2838. }
  2839. }
  2840. }
  2841. // Translate the selected columns
  2842. //
  2843. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  2844. $oBuild->m_oQBExpressions->Translate($aTranslation, false);
  2845. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  2846. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  2847. return $oSelectBase;
  2848. }
  2849. /**
  2850. * Special processing for the hierarchical keys stored as nested sets
  2851. * @param $iId integer The identifier of the parent
  2852. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2853. * @param $stable string The name of the database table containing the hierarchical key
  2854. */
  2855. public static function HKInsertChildUnder($iId, $oAttDef, $sTable)
  2856. {
  2857. // Get the parent id.right value
  2858. if ($iId == 0)
  2859. {
  2860. // No parent, insert completely at the right of the tree
  2861. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  2862. $aRes = CMDBSource::QueryToArray($sSQL);
  2863. if (count($aRes) == 0)
  2864. {
  2865. $iMyRight = 1;
  2866. }
  2867. else
  2868. {
  2869. $iMyRight = $aRes[0]['max']+1;
  2870. }
  2871. }
  2872. else
  2873. {
  2874. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".$iId;
  2875. $iMyRight = CMDBSource::QueryToScalar($sSQL);
  2876. $sSQLUpdateRight = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + 2 WHERE `".$oAttDef->GetSQLRight()."` >= $iMyRight";
  2877. CMDBSource::Query($sSQLUpdateRight);
  2878. $sSQLUpdateLeft = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + 2 WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2879. CMDBSource::Query($sSQLUpdateLeft);
  2880. }
  2881. return array($oAttDef->GetSQLRight() => $iMyRight+1, $oAttDef->GetSQLLeft() => $iMyRight);
  2882. }
  2883. /**
  2884. * Special processing for the hierarchical keys stored as nested sets: temporary remove the branch
  2885. * @param $iId integer The identifier of the parent
  2886. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2887. * @param $sTable string The name of the database table containing the hierarchical key
  2888. */
  2889. public static function HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable)
  2890. {
  2891. $iDelta = $iMyRight - $iMyLeft + 1;
  2892. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iMyLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iMyLeft - `".$oAttDef->GetSQLLeft();
  2893. $sSQL .= "` WHERE `".$oAttDef->GetSQLLeft()."`> $iMyLeft AND `".$oAttDef->GetSQLRight()."`< $iMyRight";
  2894. CMDBSource::Query($sSQL);
  2895. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` - $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2896. CMDBSource::Query($sSQL);
  2897. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` - $iDelta WHERE `".$oAttDef->GetSQLRight()."` > $iMyRight";
  2898. CMDBSource::Query($sSQL);
  2899. }
  2900. /**
  2901. * Special processing for the hierarchical keys stored as nested sets: replug the temporary removed branch
  2902. * @param $iId integer The identifier of the parent
  2903. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2904. * @param $sTable string The name of the database table containing the hierarchical key
  2905. */
  2906. public static function HKReplugBranch($iNewLeft, $iNewRight, $oAttDef, $sTable)
  2907. {
  2908. $iDelta = $iNewRight - $iNewLeft + 1;
  2909. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iNewLeft";
  2910. CMDBSource::Query($sSQL);
  2911. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + $iDelta WHERE `".$oAttDef->GetSQLRight()."` >= $iNewLeft";
  2912. CMDBSource::Query($sSQL);
  2913. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iNewLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iNewLeft - `".$oAttDef->GetSQLLeft()."` WHERE `".$oAttDef->GetSQLRight()."`< 0";
  2914. CMDBSource::Query($sSQL);
  2915. }
  2916. /**
  2917. * Check (and updates if needed) the hierarchical keys
  2918. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2919. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2920. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2921. */
  2922. public static function CheckHKeys($bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2923. {
  2924. $bChangeNeeded = false;
  2925. foreach (self::GetClasses() as $sClass)
  2926. {
  2927. if (!self::HasTable($sClass)) continue;
  2928. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2929. {
  2930. // Check (once) all the attributes that are hierarchical keys
  2931. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey())
  2932. {
  2933. if ($bVerbose)
  2934. {
  2935. echo "The attribute $sAttCode from $sClass is a hierarchical key.\n";
  2936. }
  2937. $bResult = self::HKInit($sClass, $sAttCode, $bDiagnosticsOnly, $bVerbose, $bForceComputation);
  2938. $bChangeNeeded |= $bResult;
  2939. if ($bVerbose && !$bResult)
  2940. {
  2941. echo "Ok, the attribute $sAttCode from class $sClass seems up to date.\n";
  2942. }
  2943. }
  2944. }
  2945. }
  2946. return $bChangeNeeded;
  2947. }
  2948. /**
  2949. * Initializes (i.e converts) a hierarchy stored using a 'parent_id' external key
  2950. * into a hierarchy stored with a HierarchicalKey, by initializing the _left and _right values
  2951. * to correspond to the existing hierarchy in the database
  2952. * @param $sClass string Name of the class to process
  2953. * @param $sAttCode string Code of the attribute to process
  2954. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2955. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2956. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2957. * @return true if an update is needed (diagnostics only) / was performed
  2958. */
  2959. public static function HKInit($sClass, $sAttCode, $bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2960. {
  2961. $idx = 1;
  2962. $bUpdateNeeded = $bForceComputation;
  2963. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  2964. $sTable = self::DBGetTable($sClass, $sAttCode);
  2965. if ($oAttDef->IsHierarchicalKey())
  2966. {
  2967. // Check if some values already exist in the table for the _right value, if so, do nothing
  2968. $sRight = $oAttDef->GetSQLRight();
  2969. $sSQL = "SELECT MAX(`$sRight`) AS MaxRight FROM `$sTable`";
  2970. $iMaxRight = CMDBSource::QueryToScalar($sSQL);
  2971. $sSQL = "SELECT COUNT(*) AS Count FROM `$sTable`"; // Note: COUNT(field) returns zero if the given field contains only NULLs
  2972. $iCount = CMDBSource::QueryToScalar($sSQL);
  2973. if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0))
  2974. {
  2975. $bUpdateNeeded = true;
  2976. if ($bVerbose)
  2977. {
  2978. echo "The table '$sTable' must be updated to compute the fields $sRight and ".$oAttDef->GetSQLLeft()."\n";
  2979. }
  2980. }
  2981. if ($bForceComputation && !$bDiagnosticsOnly)
  2982. {
  2983. echo "Rebuilding the fields $sRight and ".$oAttDef->GetSQLLeft()." from table '$sTable'...\n";
  2984. }
  2985. if ($bUpdateNeeded && !$bDiagnosticsOnly)
  2986. {
  2987. try
  2988. {
  2989. CMDBSource::Query('START TRANSACTION');
  2990. self::HKInitChildren($sTable, $sAttCode, $oAttDef, 0, $idx);
  2991. CMDBSource::Query('COMMIT');
  2992. if ($bVerbose)
  2993. {
  2994. echo "Ok, table '$sTable' successfully updated.\n";
  2995. }
  2996. }
  2997. catch(Exception $e)
  2998. {
  2999. CMDBSource::Query('ROLLBACK');
  3000. throw new Exception("An error occured (".$e->getMessage().") while initializing the hierarchy for ($sClass, $sAttCode). The database was not modified.");
  3001. }
  3002. }
  3003. }
  3004. return $bUpdateNeeded;
  3005. }
  3006. /**
  3007. * Recursive helper function called by HKInit
  3008. */
  3009. protected static function HKInitChildren($sTable, $sAttCode, $oAttDef, $iId, &$iCurrIndex)
  3010. {
  3011. $sSQL = "SELECT id FROM `$sTable` WHERE `$sAttCode` = $iId";
  3012. $aRes = CMDBSource::QueryToArray($sSQL);
  3013. $aTree = array();
  3014. $sLeft = $oAttDef->GetSQLLeft();
  3015. $sRight = $oAttDef->GetSQLRight();
  3016. foreach($aRes as $aValues)
  3017. {
  3018. $iChildId = $aValues['id'];
  3019. $iLeft = $iCurrIndex++;
  3020. $aChildren = self::HKInitChildren($sTable, $sAttCode, $oAttDef, $iChildId, $iCurrIndex);
  3021. $iRight = $iCurrIndex++;
  3022. $sSQL = "UPDATE `$sTable` SET `$sLeft` = $iLeft, `$sRight` = $iRight WHERE id= $iChildId";
  3023. CMDBSource::Query($sSQL);
  3024. }
  3025. }
  3026. public static function CheckDataSources($bDiagnostics, $bVerbose)
  3027. {
  3028. $sOQL = 'SELECT SynchroDataSource';
  3029. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  3030. $bFixNeeded = false;
  3031. if ($bVerbose && $oSet->Count() == 0)
  3032. {
  3033. echo "There are no Data Sources in the database.\n";
  3034. }
  3035. while($oSource = $oSet->Fetch())
  3036. {
  3037. if ($bVerbose)
  3038. {
  3039. echo "Checking Data Source '".$oSource->GetName()."'...\n";
  3040. $bFixNeeded = $bFixNeeded | $oSource->CheckDBConsistency($bDiagnostics, $bVerbose);
  3041. }
  3042. }
  3043. if (!$bFixNeeded && $bVerbose)
  3044. {
  3045. echo "Ok.\n";
  3046. }
  3047. return $bFixNeeded;
  3048. }
  3049. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  3050. {
  3051. if (!array_key_exists($sNewName, $aAliases))
  3052. {
  3053. $aAliases[$sNewName] = $sRealName;
  3054. return $sNewName;
  3055. }
  3056. for ($i = 1 ; $i < 100 ; $i++)
  3057. {
  3058. $sAnAlias = $sNewName.$i;
  3059. if (!array_key_exists($sAnAlias, $aAliases))
  3060. {
  3061. // Create that new alias
  3062. $aAliases[$sAnAlias] = $sRealName;
  3063. return $sAnAlias;
  3064. }
  3065. }
  3066. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  3067. }
  3068. public static function CheckDefinitions($bExitOnError = true)
  3069. {
  3070. if (count(self::GetClasses()) == 0)
  3071. {
  3072. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  3073. }
  3074. $aErrors = array();
  3075. $aSugFix = array();
  3076. foreach (self::GetClasses() as $sClass)
  3077. {
  3078. $sTable = self::DBGetTable($sClass);
  3079. $sTableLowercase = strtolower($sTable);
  3080. if ($sTableLowercase != $sTable)
  3081. {
  3082. $aErrors[$sClass][] = "Table name '".$sTable."' has upper case characters. You might encounter issues when moving your installation between Linux and Windows.";
  3083. $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.";
  3084. }
  3085. $aNameSpec = self::GetNameSpec($sClass);
  3086. foreach($aNameSpec[1] as $i => $sAttCode)
  3087. {
  3088. if(!self::IsValidAttCode($sClass, $sAttCode))
  3089. {
  3090. $aErrors[$sClass][] = "Unknown attribute code '".$sAttCode."' for the name definition";
  3091. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  3092. }
  3093. }
  3094. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  3095. {
  3096. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  3097. {
  3098. $aErrors[$sClass][] = "Unknown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  3099. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  3100. }
  3101. }
  3102. $bHasWritableAttribute = false;
  3103. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3104. {
  3105. // It makes no sense to check the attributes again and again in the subclasses
  3106. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3107. if ($oAttDef->IsExternalKey())
  3108. {
  3109. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  3110. {
  3111. $aErrors[$sClass][] = "Unknown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  3112. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  3113. }
  3114. }
  3115. elseif ($oAttDef->IsExternalField())
  3116. {
  3117. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  3118. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  3119. {
  3120. $aErrors[$sClass][] = "Unknown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  3121. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  3122. }
  3123. else
  3124. {
  3125. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  3126. $sTargetClass = $oKeyAttDef->GetTargetClass();
  3127. $sExtAttCode = $oAttDef->GetExtAttCode();
  3128. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  3129. {
  3130. $aErrors[$sClass][] = "Unknown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  3131. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  3132. }
  3133. }
  3134. }
  3135. else if ($oAttDef->IsLinkSet())
  3136. {
  3137. // Do nothing...
  3138. }
  3139. else if ($oAttDef instanceof AttributeStopWatch)
  3140. {
  3141. $aThresholds = $oAttDef->ListThresholds();
  3142. if (is_array($aThresholds))
  3143. {
  3144. foreach($aThresholds as $iPercent => $aDef)
  3145. {
  3146. if (array_key_exists('highlight', $aDef))
  3147. {
  3148. if(!array_key_exists('code', $aDef['highlight']))
  3149. {
  3150. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of the $iPercent% threshold in the attribute: '$sAttCode'.";
  3151. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this threshold.";
  3152. }
  3153. else
  3154. {
  3155. $aScale = self::GetHighlightScale($sClass);
  3156. if (!array_key_exists($aDef['highlight']['code'], $aScale))
  3157. {
  3158. $aErrors[$sClass][] = "'{$aDef['highlight']['code']}' is not a valid value for the 'code' element of the $iPercent% threshold in the attribute: '$sAttCode'.";
  3159. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  3160. }
  3161. }
  3162. }
  3163. }
  3164. }
  3165. }
  3166. else // standard attributes
  3167. {
  3168. // Check that the default values definition is a valid object!
  3169. $oValSetDef = $oAttDef->GetValuesDef();
  3170. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  3171. {
  3172. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  3173. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  3174. }
  3175. else
  3176. {
  3177. // Default value must be listed in the allowed values (if defined)
  3178. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  3179. if (!is_null($aAllowedValues))
  3180. {
  3181. $sDefaultValue = $oAttDef->GetDefaultValue();
  3182. if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues))
  3183. {
  3184. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  3185. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  3186. }
  3187. }
  3188. }
  3189. }
  3190. // Check dependencies
  3191. if ($oAttDef->IsWritable())
  3192. {
  3193. $bHasWritableAttribute = true;
  3194. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  3195. {
  3196. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  3197. {
  3198. $aErrors[$sClass][] = "Unknown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  3199. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  3200. }
  3201. }
  3202. }
  3203. }
  3204. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  3205. {
  3206. if (method_exists($oFilterDef, '__GetRefAttribute'))
  3207. {
  3208. $oAttDef = $oFilterDef->__GetRefAttribute();
  3209. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  3210. {
  3211. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  3212. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3213. }
  3214. }
  3215. }
  3216. // Lifecycle
  3217. //
  3218. $sStateAttCode = self::GetStateAttributeCode($sClass);
  3219. if (strlen($sStateAttCode) > 0)
  3220. {
  3221. // Lifecycle - check that the state attribute does exist as an attribute
  3222. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  3223. {
  3224. $aErrors[$sClass][] = "Unknown attribute code '".$sStateAttCode."' for the state definition";
  3225. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3226. }
  3227. else
  3228. {
  3229. // Lifecycle - check that there is a value set constraint on the state attribute
  3230. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  3231. $aStates = array_keys(self::EnumStates($sClass));
  3232. if (is_null($aAllowedValuesRaw))
  3233. {
  3234. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  3235. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  3236. }
  3237. else
  3238. {
  3239. $aAllowedValues = array_keys($aAllowedValuesRaw);
  3240. // Lifecycle - check the the state attribute allowed values are defined states
  3241. foreach($aAllowedValues as $sValue)
  3242. {
  3243. if (!in_array($sValue, $aStates))
  3244. {
  3245. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  3246. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  3247. }
  3248. }
  3249. // Lifecycle - check that defined states are allowed values
  3250. foreach($aStates as $sStateValue)
  3251. {
  3252. if (!in_array($sStateValue, $aAllowedValues))
  3253. {
  3254. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  3255. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  3256. }
  3257. }
  3258. }
  3259. // Lifecycle - check that the action handlers are defined
  3260. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  3261. {
  3262. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  3263. {
  3264. foreach ($aTransitionDef['actions'] as $actionHandler)
  3265. {
  3266. if (is_string($actionHandler))
  3267. {
  3268. if (!method_exists($sClass, $actionHandler))
  3269. {
  3270. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  3271. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  3272. }
  3273. }
  3274. else // if(is_array($actionHandler))
  3275. {
  3276. $sActionHandler = $actionHandler['verb'];
  3277. if (!method_exists($sClass, $sActionHandler))
  3278. {
  3279. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  3280. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(...){return true;}]";
  3281. }
  3282. }
  3283. }
  3284. }
  3285. if (array_key_exists('highlight', $aStateDef))
  3286. {
  3287. if(!array_key_exists('code', $aStateDef['highlight']))
  3288. {
  3289. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of state: '$sStateCode'.";
  3290. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this state.";
  3291. }
  3292. else
  3293. {
  3294. $aScale = self::GetHighlightScale($sClass);
  3295. if (!array_key_exists($aStateDef['highlight']['code'], $aScale))
  3296. {
  3297. $aErrors[$sClass][] = "'{$aStateDef['highlight']['code']}' is not a valid value for the 'code' element in the 'highlight' property of state: '$sStateCode'.";
  3298. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  3299. }
  3300. }
  3301. }
  3302. }
  3303. }
  3304. }
  3305. if ($bHasWritableAttribute)
  3306. {
  3307. if (!self::HasTable($sClass))
  3308. {
  3309. $aErrors[$sClass][] = "No table has been defined for this class";
  3310. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  3311. }
  3312. }
  3313. // ZList
  3314. //
  3315. foreach(self::EnumZLists() as $sListCode)
  3316. {
  3317. foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode)
  3318. {
  3319. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  3320. {
  3321. $aErrors[$sClass][] = "Unknown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  3322. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3323. }
  3324. }
  3325. }
  3326. // Check unicity of the SQL columns
  3327. //
  3328. if (self::HasTable($sClass))
  3329. {
  3330. $aTableColumns = array(); // array of column => attcode (the column is used by this attribute)
  3331. $aTableColumns[self::DBGetKey($sClass)] = 'id';
  3332. // Check that SQL columns are declared only once
  3333. //
  3334. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3335. {
  3336. // Skip this attribute if not originaly defined in this class
  3337. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3338. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  3339. {
  3340. if (array_key_exists($sField, $aTableColumns))
  3341. {
  3342. $aErrors[$sClass][] = "Column '$sField' declared for attribute $sAttCode, but already used for attribute ".$aTableColumns[$sField];
  3343. $aSugFix[$sClass][] = "Please find another name for the SQL column";
  3344. }
  3345. else
  3346. {
  3347. $aTableColumns[$sField] = $sAttCode;
  3348. }
  3349. }
  3350. }
  3351. }
  3352. } // foreach class
  3353. if (count($aErrors) > 0)
  3354. {
  3355. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3356. echo "<h3>Business model inconsistencies have been found</h3>\n";
  3357. // #@# later -> this is the responsibility of the caller to format the output
  3358. foreach ($aErrors as $sClass => $aMessages)
  3359. {
  3360. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  3361. echo "<ul class=\"treeview\">\n";
  3362. $i = 0;
  3363. foreach ($aMessages as $sMsg)
  3364. {
  3365. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  3366. $i++;
  3367. }
  3368. echo "</ul>\n";
  3369. }
  3370. if ($bExitOnError) echo "<p>Aborting...</p>\n";
  3371. echo "</div>\n";
  3372. if ($bExitOnError) exit;
  3373. }
  3374. }
  3375. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  3376. {
  3377. if (empty($sRepairUrl)) return;
  3378. // By design, some queries might be blank, we have to ignore them
  3379. $aCleanFixes = array();
  3380. foreach($aSQLFixes as $sSQLFix)
  3381. {
  3382. if (!empty($sSQLFix))
  3383. {
  3384. $aCleanFixes[] = $sSQLFix;
  3385. }
  3386. }
  3387. if (count($aCleanFixes) == 0) return;
  3388. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  3389. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes), ENT_QUOTES, 'UTF-8')."\">\n";
  3390. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  3391. echo "</form>\n";
  3392. }
  3393. public static function DBExists($bMustBeComplete = true)
  3394. {
  3395. // returns true if at least one table exists
  3396. //
  3397. if (!CMDBSource::IsDB(self::$m_sDBName))
  3398. {
  3399. return false;
  3400. }
  3401. CMDBSource::SelectDB(self::$m_sDBName);
  3402. $aFound = array();
  3403. $aMissing = array();
  3404. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3405. {
  3406. if (CMDBSource::IsTable($sTable))
  3407. {
  3408. $aFound[] = $sTable;
  3409. }
  3410. else
  3411. {
  3412. $aMissing[] = $sTable;
  3413. }
  3414. }
  3415. if (count($aFound) == 0)
  3416. {
  3417. // no expected table has been found
  3418. return false;
  3419. }
  3420. else
  3421. {
  3422. if (count($aMissing) == 0)
  3423. {
  3424. // the database is complete (still, could be some fields missing!)
  3425. return true;
  3426. }
  3427. else
  3428. {
  3429. // not all the tables, could be an older version
  3430. if ($bMustBeComplete)
  3431. {
  3432. return false;
  3433. }
  3434. else
  3435. {
  3436. return true;
  3437. }
  3438. }
  3439. }
  3440. }
  3441. public static function DBDrop()
  3442. {
  3443. $bDropEntireDB = true;
  3444. if (!empty(self::$m_sTablePrefix))
  3445. {
  3446. // Do drop only tables corresponding to the sub-database (table prefix)
  3447. // then possibly drop the DB itself (if no table remain)
  3448. foreach (CMDBSource::EnumTables() as $sTable)
  3449. {
  3450. // perform a case insensitive test because on Windows the table names become lowercase :-(
  3451. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  3452. {
  3453. CMDBSource::DropTable($sTable);
  3454. }
  3455. else
  3456. {
  3457. // There is at least one table which is out of the scope of the current application
  3458. $bDropEntireDB = false;
  3459. }
  3460. }
  3461. }
  3462. if ($bDropEntireDB)
  3463. {
  3464. CMDBSource::DropDB(self::$m_sDBName);
  3465. }
  3466. }
  3467. public static function DBCreate()
  3468. {
  3469. // Note: we have to check if the DB does exist, because we may share the DB
  3470. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  3471. if (!CMDBSource::IsDB(self::$m_sDBName))
  3472. {
  3473. CMDBSource::CreateDB(self::$m_sDBName);
  3474. }
  3475. self::DBCreateTables();
  3476. self::DBCreateViews();
  3477. }
  3478. protected static function DBCreateTables()
  3479. {
  3480. list($aErrors, $aSugFix, $aCondensedQueries) = self::DBCheckFormat();
  3481. //$sSQL = implode('; ', $aCondensedQueries); Does not work - multiple queries not allowed
  3482. foreach($aCondensedQueries as $sQuery)
  3483. {
  3484. CMDBSource::CreateTable($sQuery);
  3485. }
  3486. }
  3487. protected static function DBCreateViews()
  3488. {
  3489. list($aErrors, $aSugFix) = self::DBCheckViews();
  3490. $aSQL = array();
  3491. foreach ($aSugFix as $sClass => $aTarget)
  3492. {
  3493. foreach ($aTarget as $aQueries)
  3494. {
  3495. foreach ($aQueries as $sQuery)
  3496. {
  3497. if (!empty($sQuery))
  3498. {
  3499. //$aSQL[] = $sQuery;
  3500. // forces a refresh of cached information
  3501. CMDBSource::CreateTable($sQuery);
  3502. }
  3503. }
  3504. }
  3505. }
  3506. }
  3507. public static function DBDump()
  3508. {
  3509. $aDataDump = array();
  3510. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3511. {
  3512. $aRows = CMDBSource::DumpTable($sTable);
  3513. $aDataDump[$sTable] = $aRows;
  3514. }
  3515. return $aDataDump;
  3516. }
  3517. /*
  3518. * Determines wether the target DB is frozen or not
  3519. */
  3520. public static function DBIsReadOnly()
  3521. {
  3522. // Improvement: check the mySQL variable -> Read-only
  3523. if (UserRights::IsAdministrator())
  3524. {
  3525. return (!self::DBHasAccess(ACCESS_ADMIN_WRITE));
  3526. }
  3527. else
  3528. {
  3529. return (!self::DBHasAccess(ACCESS_USER_WRITE));
  3530. }
  3531. }
  3532. public static function DBHasAccess($iRequested = ACCESS_FULL)
  3533. {
  3534. $iMode = self::$m_oConfig->Get('access_mode');
  3535. if (($iMode & $iRequested) == 0) return false;
  3536. return true;
  3537. }
  3538. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  3539. {
  3540. $sValue = Dict::S($sKey, 'x-no-nothing');
  3541. if ($sValue == 'x-no-nothing')
  3542. {
  3543. $bNotInDico = true;
  3544. $sValue = $sValueFromOldSystem;
  3545. if (strlen($sValue) == 0)
  3546. {
  3547. $sValue = $sDefaultValue;
  3548. }
  3549. }
  3550. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  3551. }
  3552. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  3553. {
  3554. $sRes = '';
  3555. $sRes .= "// Dictionnay conventions\n";
  3556. $sRes .= htmlentities("// Class:<class_name>\n", ENT_QUOTES, 'UTF-8');
  3557. $sRes .= htmlentities("// Class:<class_name>+\n", ENT_QUOTES, 'UTF-8');
  3558. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n", ENT_QUOTES, 'UTF-8');
  3559. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n", ENT_QUOTES, 'UTF-8');
  3560. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n", ENT_QUOTES, 'UTF-8');
  3561. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n", ENT_QUOTES, 'UTF-8');
  3562. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n", ENT_QUOTES, 'UTF-8');
  3563. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n", ENT_QUOTES, 'UTF-8');
  3564. $sRes .= "\n";
  3565. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  3566. // Need to invent the "module", to characterize the origins of a class
  3567. if (strlen($sModules) == 0)
  3568. {
  3569. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  3570. }
  3571. else
  3572. {
  3573. $aModules = explode(', ', $sModules);
  3574. }
  3575. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3576. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  3577. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3578. foreach ($aModules as $sCategory)
  3579. {
  3580. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3581. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  3582. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3583. $sRes .= "//\n";
  3584. $sRes .= "\n";
  3585. foreach (self::GetClasses($sCategory) as $sClass)
  3586. {
  3587. if (!self::HasTable($sClass)) continue;
  3588. $bNotInDico = false;
  3589. $sClassRes = "//\n";
  3590. $sClassRes .= "// Class: $sClass\n";
  3591. $sClassRes .= "//\n";
  3592. $sClassRes .= "\n";
  3593. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  3594. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  3595. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  3596. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  3597. {
  3598. // Skip this attribute if not originaly defined in this class
  3599. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3600. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  3601. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  3602. if ($oAttDef instanceof AttributeEnum)
  3603. {
  3604. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  3605. {
  3606. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  3607. {
  3608. if (array_key_exists('label', $aStateData))
  3609. {
  3610. $sValue = $aStateData['label'];
  3611. }
  3612. else
  3613. {
  3614. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  3615. }
  3616. if (array_key_exists('description', $aStateData))
  3617. {
  3618. $sValuePlus = $aStateData['description'];
  3619. }
  3620. else
  3621. {
  3622. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  3623. }
  3624. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  3625. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  3626. }
  3627. }
  3628. else
  3629. {
  3630. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  3631. {
  3632. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  3633. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  3634. }
  3635. }
  3636. }
  3637. }
  3638. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  3639. {
  3640. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  3641. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  3642. }
  3643. $sClassRes .= "));\n";
  3644. $sClassRes .= "\n";
  3645. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  3646. {
  3647. $sRes .= $sClassRes;
  3648. }
  3649. }
  3650. }
  3651. return $sRes;
  3652. }
  3653. public static function DBCheckFormat()
  3654. {
  3655. $aErrors = array();
  3656. $aSugFix = array();
  3657. // A new way of representing things to be done - quicker to execute !
  3658. $aCreateTable = array(); // array of <table> => <table options>
  3659. $aCreateTableItems = array(); // array of <table> => array of <create definition>
  3660. $aAlterTableItems = array(); // array of <table> => <alter specification>
  3661. foreach (self::GetClasses() as $sClass)
  3662. {
  3663. if (!self::HasTable($sClass)) continue;
  3664. // Check that the table exists
  3665. //
  3666. $sTable = self::DBGetTable($sClass);
  3667. $sKeyField = self::DBGetKey($sClass);
  3668. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  3669. $sKeyFieldDefinition = "`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  3670. if (!CMDBSource::IsTable($sTable))
  3671. {
  3672. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  3673. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` ($sKeyFieldDefinition) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3674. $aCreateTable[$sTable] = "ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3675. $aCreateTableItems[$sTable][$sKeyField] = $sKeyFieldDefinition;
  3676. }
  3677. // Check that the key field exists
  3678. //
  3679. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  3680. {
  3681. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  3682. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD $sKeyFieldDefinition";
  3683. if (!array_key_exists($sTable, $aCreateTable))
  3684. {
  3685. $aAlterTableItems[$sTable][$sKeyField] = "ADD $sKeyFieldDefinition";
  3686. }
  3687. }
  3688. else
  3689. {
  3690. // Check the key field properties
  3691. //
  3692. if (!CMDBSource::IsKey($sTable, $sKeyField))
  3693. {
  3694. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  3695. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  3696. if (!array_key_exists($sTable, $aCreateTable))
  3697. {
  3698. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3699. }
  3700. }
  3701. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  3702. {
  3703. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  3704. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` $sKeyFieldDefinition";
  3705. if (!array_key_exists($sTable, $aCreateTable))
  3706. {
  3707. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3708. }
  3709. }
  3710. }
  3711. // Check that any defined field exists
  3712. //
  3713. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  3714. $aTableInfo['Fields'][$sKeyField]['used'] = true;
  3715. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3716. {
  3717. // Skip this attribute if not originaly defined in this class
  3718. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3719. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  3720. {
  3721. // Keep track of columns used by iTop
  3722. $aTableInfo['Fields'][$sField]['used'] = true;
  3723. $bIndexNeeded = $oAttDef->RequiresIndex();
  3724. $sFieldDefinition = "`$sField` ".($oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL");
  3725. if (!CMDBSource::IsField($sTable, $sField))
  3726. {
  3727. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  3728. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD $sFieldDefinition";
  3729. if ($bIndexNeeded)
  3730. {
  3731. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3732. }
  3733. if (array_key_exists($sTable, $aCreateTable))
  3734. {
  3735. $aCreateTableItems[$sTable][$sField] = $sFieldDefinition;
  3736. if ($bIndexNeeded)
  3737. {
  3738. $aCreateTableItems[$sTable][] = "INDEX (`$sField`)";
  3739. }
  3740. }
  3741. else
  3742. {
  3743. $aAlterTableItems[$sTable][$sField] = "ADD $sFieldDefinition";
  3744. if ($bIndexNeeded)
  3745. {
  3746. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3747. }
  3748. }
  3749. }
  3750. else
  3751. {
  3752. // The field already exists, does it have the relevant properties?
  3753. //
  3754. $bToBeChanged = false;
  3755. if ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  3756. {
  3757. $bToBeChanged = true;
  3758. if ($oAttDef->IsNullAllowed())
  3759. {
  3760. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could be NULL";
  3761. }
  3762. else
  3763. {
  3764. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could NOT be NULL";
  3765. }
  3766. }
  3767. $sActualFieldType = CMDBSource::GetFieldType($sTable, $sField);
  3768. if (strcasecmp($sDBFieldType, $sActualFieldType) != 0)
  3769. {
  3770. $bToBeChanged = true;
  3771. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldType' while expecting '$sDBFieldType'";
  3772. }
  3773. if ($bToBeChanged)
  3774. {
  3775. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3776. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3777. }
  3778. // Create indexes (external keys only... so far)
  3779. //
  3780. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField, array($sField)))
  3781. {
  3782. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  3783. if (CMDBSource::HasIndex($sTable, $sField))
  3784. {
  3785. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` DROP INDEX `$sField`, ADD INDEX (`$sField`)";
  3786. $aAlterTableItems[$sTable][] = "DROP INDEX `$sField`";
  3787. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3788. }
  3789. else
  3790. {
  3791. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3792. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3793. }
  3794. }
  3795. }
  3796. }
  3797. }
  3798. // Check indexes
  3799. foreach (self::DBGetIndexes($sClass) as $aColumns)
  3800. {
  3801. $sIndexId = implode('_', $aColumns);
  3802. if(!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns))
  3803. {
  3804. $sColumns = "`".implode("`, `", $aColumns)."`";
  3805. if (CMDBSource::HasIndex($sTable, $sIndexId))
  3806. {
  3807. $aErrors[$sClass]['*'][] = "Wrong index '$sIndexId' ($sColumns) in table '$sTable'";
  3808. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`, ADD INDEX `$sIndexId` ($sColumns)";
  3809. }
  3810. else
  3811. {
  3812. $aErrors[$sClass]['*'][] = "Missing index '$sIndexId' ($sColumns) in table '$sTable'";
  3813. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)";
  3814. }
  3815. if (array_key_exists($sTable, $aCreateTable))
  3816. {
  3817. $aCreateTableItems[$sTable][] = "INDEX `$sIndexId` ($sColumns)";
  3818. }
  3819. else
  3820. {
  3821. if (CMDBSource::HasIndex($sTable, $sIndexId))
  3822. {
  3823. $aAlterTableItems[$sTable][] = "DROP INDEX `$sIndexId`";
  3824. }
  3825. $aAlterTableItems[$sTable][] = "ADD INDEX `$sIndexId` ($sColumns)";
  3826. }
  3827. }
  3828. }
  3829. // Find out unused columns
  3830. //
  3831. foreach($aTableInfo['Fields'] as $sField => $aFieldData)
  3832. {
  3833. if (!isset($aFieldData['used']) || !$aFieldData['used'])
  3834. {
  3835. $aErrors[$sClass]['*'][] = "Column '$sField' in table '$sTable' is not used";
  3836. if (!CMDBSource::IsNullAllowed($sTable, $sField))
  3837. {
  3838. // Allow null values so that new record can be inserted
  3839. // without specifying the value of this unknown column
  3840. $sFieldDefinition = "`$sField` ".CMDBSource::GetFieldType($sTable, $sField).' NULL';
  3841. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3842. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3843. }
  3844. }
  3845. }
  3846. }
  3847. $aCondensedQueries = array();
  3848. foreach($aCreateTable as $sTable => $sTableOptions)
  3849. {
  3850. $sTableItems = implode(', ', $aCreateTableItems[$sTable]);
  3851. $aCondensedQueries[] = "CREATE TABLE `$sTable` ($sTableItems) $sTableOptions";
  3852. }
  3853. foreach($aAlterTableItems as $sTable => $aChangeList)
  3854. {
  3855. $sChangeList = implode(', ', $aChangeList);
  3856. $aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList";
  3857. }
  3858. return array($aErrors, $aSugFix, $aCondensedQueries);
  3859. }
  3860. public static function DBCheckViews()
  3861. {
  3862. $aErrors = array();
  3863. $aSugFix = array();
  3864. // Reporting views (must be created after any other table)
  3865. //
  3866. foreach (self::GetClasses('bizmodel') as $sClass)
  3867. {
  3868. $sView = self::DBGetView($sClass);
  3869. if (CMDBSource::IsTable($sView))
  3870. {
  3871. // Check that the view is complete
  3872. //
  3873. // Note: checking the list of attributes is not enough because the columns can be stable while the SELECT is not stable
  3874. // Example: new way to compute the friendly name
  3875. // The correct comparison algorithm is to compare the queries,
  3876. // by using "SHOW CREATE VIEW" (MySQL 5.0.1 required) or to look into INFORMATION_SCHEMA/views
  3877. // both requiring some privileges
  3878. // Decision: to simplify, let's consider the views as being wrong anytime
  3879. if (true)
  3880. {
  3881. // Rework the view
  3882. //
  3883. $oFilter = new DBObjectSearch($sClass, '');
  3884. $oFilter->AllowAllData();
  3885. $sSQL = self::MakeSelectQuery($oFilter);
  3886. $aErrors[$sClass]['*'][] = "Redeclare view '$sView' (systematic - to support an eventual change in the friendly name computation)";
  3887. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  3888. }
  3889. }
  3890. else
  3891. {
  3892. // Create the view
  3893. //
  3894. $oFilter = new DBObjectSearch($sClass, '');
  3895. $oFilter->AllowAllData();
  3896. $sSQL = self::MakeSelectQuery($oFilter);
  3897. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  3898. $aSugFix[$sClass]['*'][] = "DROP VIEW IF EXISTS `$sView`";
  3899. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  3900. }
  3901. }
  3902. return array($aErrors, $aSugFix);
  3903. }
  3904. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  3905. {
  3906. $sRootClass = self::GetRootClass($sClass);
  3907. $sTable = self::DBGetTable($sClass);
  3908. $sKeyField = self::DBGetKey($sClass);
  3909. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3910. {
  3911. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3912. }
  3913. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3914. if (count($aWrongRecords) == 0) return;
  3915. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3916. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3917. foreach ($aWrongRecords as $iRecordId)
  3918. {
  3919. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3920. {
  3921. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3922. {
  3923. case 'Delete':
  3924. // Already planned for a deletion
  3925. // Let's concatenate the errors description together
  3926. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3927. break;
  3928. case 'Update':
  3929. // Let's plan a deletion
  3930. break;
  3931. }
  3932. }
  3933. else
  3934. {
  3935. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3936. }
  3937. if (!$bProcessingFriends)
  3938. {
  3939. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  3940. {
  3941. // Something new to be deleted...
  3942. $iNewDelCount++;
  3943. }
  3944. }
  3945. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  3946. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  3947. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3948. $aPlannedDel[$sTable][] = $iRecordId;
  3949. }
  3950. // Now make sure that we would delete the records of the other tables for that class
  3951. //
  3952. if (!$bProcessingFriends)
  3953. {
  3954. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  3955. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  3956. {
  3957. $sFriendTable = self::DBGetTable($sFriendClass);
  3958. $sFriendKey = self::DBGetKey($sFriendClass);
  3959. // skip the current table
  3960. if ($sFriendTable == $sTable) continue;
  3961. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  3962. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  3963. }
  3964. }
  3965. }
  3966. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3967. {
  3968. $sRootClass = self::GetRootClass($sClass);
  3969. $sTable = self::DBGetTable($sClass);
  3970. $sKeyField = self::DBGetKey($sClass);
  3971. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3972. {
  3973. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3974. }
  3975. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3976. if (count($aWrongRecords) == 0) return;
  3977. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3978. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3979. foreach ($aWrongRecords as $iRecordId)
  3980. {
  3981. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3982. {
  3983. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3984. {
  3985. case 'Delete':
  3986. // No need to update, the record will be deleted!
  3987. break;
  3988. case 'Update':
  3989. // Already planned for an update
  3990. // Add this new update spec to the list
  3991. $bFoundSameSpec = false;
  3992. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  3993. {
  3994. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  3995. {
  3996. $bFoundSameSpec = true;
  3997. }
  3998. }
  3999. if (!$bFoundSameSpec)
  4000. {
  4001. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  4002. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  4003. }
  4004. break;
  4005. }
  4006. }
  4007. else
  4008. {
  4009. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  4010. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  4011. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  4012. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  4013. }
  4014. }
  4015. }
  4016. // returns the count of records found for deletion
  4017. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  4018. {
  4019. foreach (self::GetClasses() as $sClass)
  4020. {
  4021. if (!self::HasTable($sClass)) continue;
  4022. $sRootClass = self::GetRootClass($sClass);
  4023. $sTable = self::DBGetTable($sClass);
  4024. $sKeyField = self::DBGetKey($sClass);
  4025. if (!self::IsStandaloneClass($sClass))
  4026. {
  4027. if (self::IsRootClass($sClass))
  4028. {
  4029. // Check that the final class field contains the name of a class which inherited from the current class
  4030. //
  4031. $sFinalClassField = self::DBGetClassField($sClass);
  4032. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  4033. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  4034. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  4035. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4036. }
  4037. else
  4038. {
  4039. $sRootTable = self::DBGetTable($sRootClass);
  4040. $sRootKey = self::DBGetKey($sRootClass);
  4041. $sFinalClassField = self::DBGetClassField($sRootClass);
  4042. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  4043. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  4044. // Check that any record found here has its counterpart in the root table
  4045. // and which refers to a child class
  4046. //
  4047. $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";
  4048. 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);
  4049. // Check that any record found in the root table and referring to a child class
  4050. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  4051. //
  4052. $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)";
  4053. 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);
  4054. }
  4055. }
  4056. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  4057. {
  4058. // Skip this attribute if not defined in this table
  4059. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  4060. if ($oAttDef->IsExternalKey())
  4061. {
  4062. // Check that any external field is pointing to an existing object
  4063. //
  4064. $sRemoteClass = $oAttDef->GetTargetClass();
  4065. $sRemoteTable = self::DBGetTable($sRemoteClass);
  4066. $sRemoteKey = self::DBGetKey($sRemoteClass);
  4067. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  4068. $sExtKeyField = current($aCols); // get the first column for an external key
  4069. // Note: a class/table may have an external key on itself
  4070. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  4071. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  4072. if ($oAttDef->IsNullAllowed())
  4073. {
  4074. // Exclude the records pointing to 0/null from the errors
  4075. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  4076. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  4077. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4078. }
  4079. else
  4080. {
  4081. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4082. }
  4083. // Do almost the same, taking into account the records planned for deletion
  4084. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  4085. {
  4086. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  4087. // but in that case you won't be able to track the root cause (cascading)
  4088. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  4089. if ($oAttDef->IsNullAllowed())
  4090. {
  4091. // Exclude the records pointing to 0/null from the errors
  4092. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  4093. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  4094. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4095. }
  4096. else
  4097. {
  4098. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4099. }
  4100. }
  4101. }
  4102. else if ($oAttDef->IsDirectField())
  4103. {
  4104. // Check that the values fit the allowed values
  4105. //
  4106. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  4107. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  4108. {
  4109. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  4110. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  4111. $sMyAttributeField = current($aCols); // get the first column for the moment
  4112. $sDefaultValue = $oAttDef->GetDefaultValue();
  4113. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  4114. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4115. }
  4116. }
  4117. }
  4118. }
  4119. }
  4120. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  4121. {
  4122. // Records in error, and action to be taken: delete or update
  4123. // by RootClass/Table/Record
  4124. $aErrorsAndFixes = array();
  4125. // Records to be ignored in the current/next pass
  4126. // by Table = array of RecordId
  4127. $aPlannedDel = array();
  4128. // Count of errors in the next pass: no error means that we can leave...
  4129. $iErrorCount = 0;
  4130. // Limit in case of a bug in the algorythm
  4131. $iLoopCount = 0;
  4132. $iNewDelCount = 1; // startup...
  4133. while ($iNewDelCount > 0)
  4134. {
  4135. $iNewDelCount = 0;
  4136. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  4137. $iErrorCount += $iNewDelCount;
  4138. // Safety net #1 - limit the planned deletions
  4139. //
  4140. $iMaxDel = 1000;
  4141. $iPlannedDel = 0;
  4142. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  4143. {
  4144. $iPlannedDel += count($aPlannedDelOnTable);
  4145. }
  4146. if ($iPlannedDel > $iMaxDel)
  4147. {
  4148. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  4149. break;
  4150. }
  4151. // Safety net #2 - limit the iterations
  4152. //
  4153. $iLoopCount++;
  4154. $iMaxLoops = 10;
  4155. if ($iLoopCount > $iMaxLoops)
  4156. {
  4157. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  4158. break;
  4159. }
  4160. }
  4161. // Display the results
  4162. //
  4163. $iIssueCount = 0;
  4164. $aFixesDelete = array();
  4165. $aFixesUpdate = array();
  4166. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  4167. {
  4168. foreach ($aTables as $sTable => $aRecords)
  4169. {
  4170. foreach ($aRecords as $iRecord => $aError)
  4171. {
  4172. $sAction = $aError['Action'];
  4173. $sReason = $aError['Reason'];
  4174. $iPass = $aError['Pass'];
  4175. switch ($sAction)
  4176. {
  4177. case 'Delete':
  4178. $sActionDetails = "";
  4179. $aFixesDelete[$sTable][] = $iRecord;
  4180. break;
  4181. case 'Update':
  4182. $aUpdateDesc = array();
  4183. foreach($aError['Action_Details'] as $aUpdateSpec)
  4184. {
  4185. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  4186. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  4187. }
  4188. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  4189. break;
  4190. default:
  4191. $sActionDetails = "bug: unknown action '$sAction'";
  4192. }
  4193. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  4194. $iIssueCount++;
  4195. }
  4196. }
  4197. }
  4198. if ($iIssueCount > 0)
  4199. {
  4200. // Build the queries to fix in the database
  4201. //
  4202. // First step, be able to get class data out of the table name
  4203. // Could be optimized, because we've made the job earlier... but few benefits, so...
  4204. $aTable2ClassProp = array();
  4205. foreach (self::GetClasses() as $sClass)
  4206. {
  4207. if (!self::HasTable($sClass)) continue;
  4208. $sRootClass = self::GetRootClass($sClass);
  4209. $sTable = self::DBGetTable($sClass);
  4210. $sKeyField = self::DBGetKey($sClass);
  4211. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  4212. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  4213. }
  4214. // Second step, build a flat list of SQL queries
  4215. $aSQLFixes = array();
  4216. $iPlannedUpdate = 0;
  4217. foreach ($aFixesUpdate as $sTable => $aColumns)
  4218. {
  4219. foreach ($aColumns as $sColumn => $aNewValues)
  4220. {
  4221. foreach ($aNewValues as $sNewValue => $aRecords)
  4222. {
  4223. $iPlannedUpdate += count($aRecords);
  4224. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  4225. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  4226. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  4227. }
  4228. }
  4229. }
  4230. $iPlannedDel = 0;
  4231. foreach ($aFixesDelete as $sTable => $aRecords)
  4232. {
  4233. $iPlannedDel += count($aRecords);
  4234. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  4235. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  4236. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  4237. }
  4238. // Report the results
  4239. //
  4240. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  4241. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  4242. // #@# later -> this is the responsibility of the caller to format the output
  4243. echo "<ul class=\"treeview\">\n";
  4244. foreach ($aIssues as $sIssueDesc)
  4245. {
  4246. echo "<li>$sIssueDesc</li>\n";
  4247. }
  4248. echo "</ul>\n";
  4249. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  4250. echo "<p>Aborting...</p>\n";
  4251. echo "</div>\n";
  4252. exit;
  4253. }
  4254. }
  4255. public static function Startup($config, $bModelOnly = false, $bAllowCache = true, $bTraceSourceFiles = false)
  4256. {
  4257. if (!defined('MODULESROOT'))
  4258. {
  4259. define('MODULESROOT', APPROOT.'env-'.utils::GetCurrentEnvironment().'/');
  4260. self::$m_bTraceSourceFiles = $bTraceSourceFiles;
  4261. // $config can be either a filename, or a Configuration object (volatile!)
  4262. if ($config instanceof Config)
  4263. {
  4264. self::LoadConfig($config, $bAllowCache);
  4265. }
  4266. else
  4267. {
  4268. self::LoadConfig(new Config($config), $bAllowCache);
  4269. }
  4270. if ($bModelOnly) return;
  4271. }
  4272. CMDBSource::SelectDB(self::$m_sDBName);
  4273. foreach(get_declared_classes() as $sPHPClass)
  4274. {
  4275. if (is_subclass_of($sPHPClass, 'ModuleHandlerAPI'))
  4276. {
  4277. $aCallSpec = array($sPHPClass, 'OnMetaModelStarted');
  4278. call_user_func_array($aCallSpec, array());
  4279. }
  4280. }
  4281. if (false)
  4282. {
  4283. echo "Debug<br/>\n";
  4284. self::static_var_dump();
  4285. }
  4286. }
  4287. public static function LoadConfig($oConfiguration, $bAllowCache = false)
  4288. {
  4289. self::$m_oConfig = $oConfiguration;
  4290. // Set log ASAP
  4291. if (self::$m_oConfig->GetLogGlobal())
  4292. {
  4293. if (self::$m_oConfig->GetLogIssue())
  4294. {
  4295. self::$m_bLogIssue = true;
  4296. IssueLog::Enable(APPROOT.'log/error.log');
  4297. }
  4298. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  4299. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  4300. ToolsLog::Enable(APPROOT.'log/tools.log');
  4301. }
  4302. else
  4303. {
  4304. self::$m_bLogIssue = false;
  4305. self::$m_bLogNotification = false;
  4306. self::$m_bLogWebService = false;
  4307. }
  4308. ExecutionKPI::EnableDuration(self::$m_oConfig->Get('log_kpi_duration'));
  4309. ExecutionKPI::EnableMemory(self::$m_oConfig->Get('log_kpi_memory'));
  4310. ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id'));
  4311. self::$m_bTraceQueries = self::$m_oConfig->GetLogQueries();
  4312. self::$m_bIndentQueries = self::$m_oConfig->Get('query_indentation_enabled');
  4313. self::$m_bQueryCacheEnabled = self::$m_oConfig->GetQueryCacheEnabled();
  4314. self::$m_bOptimizeQueries = self::$m_oConfig->Get('query_optimization_enabled');
  4315. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  4316. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  4317. self::$m_bUseAPCCache = $bAllowCache
  4318. && self::$m_oConfig->Get('apc_cache.enabled')
  4319. && function_exists('apc_fetch')
  4320. && function_exists('apc_store');
  4321. self::$m_iQueryCacheTTL = self::$m_oConfig->Get('apc_cache.query_ttl');
  4322. // PHP timezone first...
  4323. //
  4324. $sPHPTimezone = self::$m_oConfig->Get('timezone');
  4325. if ($sPHPTimezone == '')
  4326. {
  4327. // Leave as is... up to the admin to set a value somewhere...
  4328. //$sPHPTimezone = date_default_timezone_get();
  4329. }
  4330. else
  4331. {
  4332. date_default_timezone_set($sPHPTimezone);
  4333. }
  4334. // Note: load the dictionary as soon as possible, because it might be
  4335. // needed when some error occur
  4336. $sAppIdentity = 'itop-'.MetaModel::GetEnvironmentId();
  4337. $bDictInitializedFromData = false;
  4338. if (!self::$m_bUseAPCCache || !Dict::InCache($sAppIdentity))
  4339. {
  4340. $bDictInitializedFromData = true;
  4341. foreach (self::$m_oConfig->GetDictionaries() as $sModule => $sToInclude)
  4342. {
  4343. self::IncludeModule('dictionaries', $sToInclude);
  4344. }
  4345. }
  4346. // Set the language... after the dictionaries have been loaded!
  4347. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  4348. // Romain: this is the only way I've found to cope with the fact that
  4349. // classes have to be derived from cmdbabstract (to be editable in the UI)
  4350. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  4351. foreach (self::$m_oConfig->GetAppModules() as $sModule => $sToInclude)
  4352. {
  4353. self::IncludeModule('application', $sToInclude);
  4354. }
  4355. foreach (self::$m_oConfig->GetDataModels() as $sModule => $sToInclude)
  4356. {
  4357. self::IncludeModule('business', $sToInclude);
  4358. }
  4359. foreach (self::$m_oConfig->GetWebServiceCategories() as $sModule => $sToInclude)
  4360. {
  4361. self::IncludeModule('webservice', $sToInclude);
  4362. }
  4363. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  4364. {
  4365. self::IncludeModule('addons', $sToInclude);
  4366. }
  4367. $sServer = self::$m_oConfig->GetDBHost();
  4368. $sUser = self::$m_oConfig->GetDBUser();
  4369. $sPwd = self::$m_oConfig->GetDBPwd();
  4370. $sSource = self::$m_oConfig->GetDBName();
  4371. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  4372. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  4373. $sCollation = self::$m_oConfig->GetDBCollation();
  4374. if (self::$m_bUseAPCCache)
  4375. {
  4376. $oKPI = new ExecutionKPI();
  4377. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  4378. //
  4379. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-metamodel';
  4380. $result = apc_fetch($sOqlAPCCacheId);
  4381. if (is_array($result))
  4382. {
  4383. // todo - verifier que toutes les classes mentionnees ici sont chargees dans InitClasses()
  4384. self::$m_aExtensionClasses = $result['m_aExtensionClasses'];
  4385. self::$m_Category2Class = $result['m_Category2Class'];
  4386. self::$m_aRootClasses = $result['m_aRootClasses'];
  4387. self::$m_aParentClasses = $result['m_aParentClasses'];
  4388. self::$m_aChildClasses = $result['m_aChildClasses'];
  4389. self::$m_aClassParams = $result['m_aClassParams'];
  4390. self::$m_aAttribDefs = $result['m_aAttribDefs'];
  4391. self::$m_aAttribOrigins = $result['m_aAttribOrigins'];
  4392. self::$m_aExtKeyFriends = $result['m_aExtKeyFriends'];
  4393. self::$m_aIgnoredAttributes = $result['m_aIgnoredAttributes'];
  4394. self::$m_aFilterDefs = $result['m_aFilterDefs'];
  4395. self::$m_aFilterOrigins = $result['m_aFilterOrigins'];
  4396. self::$m_aListInfos = $result['m_aListInfos'];
  4397. self::$m_aListData = $result['m_aListData'];
  4398. self::$m_aRelationInfos = $result['m_aRelationInfos'];
  4399. self::$m_aStates = $result['m_aStates'];
  4400. self::$m_aStimuli = $result['m_aStimuli'];
  4401. self::$m_aTransitions = $result['m_aTransitions'];
  4402. self::$m_aHighlightScales = $result['m_aHighlightScales'];
  4403. }
  4404. $oKPI->ComputeAndReport('Metamodel APC (fetch + read)');
  4405. }
  4406. if (count(self::$m_aAttribDefs) == 0)
  4407. {
  4408. // The includes have been included, let's browse the existing classes and
  4409. // develop some data based on the proposed model
  4410. $oKPI = new ExecutionKPI();
  4411. self::InitClasses($sTablePrefix);
  4412. $oKPI->ComputeAndReport('Initialization of Data model structures');
  4413. if (self::$m_bUseAPCCache)
  4414. {
  4415. $oKPI = new ExecutionKPI();
  4416. $aCache = array();
  4417. $aCache['m_aExtensionClasses'] = self::$m_aExtensionClasses;
  4418. $aCache['m_Category2Class'] = self::$m_Category2Class;
  4419. $aCache['m_aRootClasses'] = self::$m_aRootClasses; // array of "classname" => "rootclass"
  4420. $aCache['m_aParentClasses'] = self::$m_aParentClasses; // array of ("classname" => array of "parentclass")
  4421. $aCache['m_aChildClasses'] = self::$m_aChildClasses; // array of ("classname" => array of "childclass")
  4422. $aCache['m_aClassParams'] = self::$m_aClassParams; // array of ("classname" => array of class information)
  4423. $aCache['m_aAttribDefs'] = self::$m_aAttribDefs; // array of ("classname" => array of attributes)
  4424. $aCache['m_aAttribOrigins'] = self::$m_aAttribOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4425. $aCache['m_aExtKeyFriends'] = self::$m_aExtKeyFriends; // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  4426. $aCache['m_aIgnoredAttributes'] = self::$m_aIgnoredAttributes; //array of ("classname" => array of ("attcode")
  4427. $aCache['m_aFilterDefs'] = self::$m_aFilterDefs; // array of ("classname" => array filterdef)
  4428. $aCache['m_aFilterOrigins'] = self::$m_aFilterOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4429. $aCache['m_aListInfos'] = self::$m_aListInfos; // array of ("listcode" => various info on the list, common to every classes)
  4430. $aCache['m_aListData'] = self::$m_aListData; // array of ("classname" => array of "listcode" => list)
  4431. $aCache['m_aRelationInfos'] = self::$m_aRelationInfos; // array of ("relcode" => various info on the list, common to every classes)
  4432. $aCache['m_aStates'] = self::$m_aStates; // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  4433. $aCache['m_aStimuli'] = self::$m_aStimuli; // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  4434. $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)))
  4435. $aCache['m_aHighlightScales'] = self::$m_aHighlightScales; // array of ("classname" => array of higlightcodes)))
  4436. apc_store($sOqlAPCCacheId, $aCache);
  4437. $oKPI->ComputeAndReport('Metamodel APC (store)');
  4438. }
  4439. }
  4440. if (self::$m_bUseAPCCache && $bDictInitializedFromData)
  4441. {
  4442. Dict::InitCache($sAppIdentity);
  4443. }
  4444. self::$m_sDBName = $sSource;
  4445. self::$m_sTablePrefix = $sTablePrefix;
  4446. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  4447. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  4448. // Later when timezone implementation is correctly done: CMDBSource::SetTimezone($sDBTimezone);
  4449. }
  4450. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  4451. {
  4452. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  4453. }
  4454. public static function GetConfig()
  4455. {
  4456. return self::$m_oConfig;
  4457. }
  4458. public static function GetEnvironmentId()
  4459. {
  4460. return md5(APPROOT).'-'.utils::GetCurrentEnvironment();
  4461. }
  4462. protected static $m_aExtensionClasses = array();
  4463. protected static function IncludeModule($sModuleType, $sToInclude)
  4464. {
  4465. $sFirstChar = substr($sToInclude, 0, 1);
  4466. $sSecondChar = substr($sToInclude, 1, 1);
  4467. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  4468. {
  4469. // It is a relative path, prepend APPROOT
  4470. if (substr($sToInclude, 0, 3) == '../')
  4471. {
  4472. // Preserve compatibility with config files written before 1.0.1
  4473. // Replace '../' by '<root>/'
  4474. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  4475. }
  4476. else
  4477. {
  4478. $sFile = APPROOT.'/'.$sToInclude;
  4479. }
  4480. }
  4481. else
  4482. {
  4483. // Leave as is - should be an absolute path
  4484. $sFile = $sToInclude;
  4485. }
  4486. if (!file_exists($sFile))
  4487. {
  4488. $sConfigFile = self::$m_oConfig->GetLoadedFile();
  4489. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sFile));
  4490. }
  4491. // Note: We do not expect the modules to output characters while loading them.
  4492. // Therefore, and because unexpected characters can corrupt the output,
  4493. // they must be trashed here.
  4494. // Additionnaly, pages aiming at delivering data in their output can call WebPage::TrashUnexpectedOutput()
  4495. // to get rid of chars that could be generated during the execution of the code
  4496. ob_start();
  4497. require_once($sFile);
  4498. $sPreviousContent = ob_get_clean();
  4499. if (self::$m_oConfig->Get('debug_report_spurious_chars'))
  4500. {
  4501. if ($sPreviousContent != '')
  4502. {
  4503. IssueLog::Error("Spurious characters injected by $sModuleType/$sToInclude");
  4504. }
  4505. }
  4506. }
  4507. // Building an object
  4508. //
  4509. //
  4510. private static $aQueryCacheGetObject = array();
  4511. private static $aQueryCacheGetObjectHits = array();
  4512. public static function GetQueryCacheStatus()
  4513. {
  4514. $aRes = array();
  4515. $iTotalHits = 0;
  4516. foreach(self::$aQueryCacheGetObjectHits as $sClassSign => $iHits)
  4517. {
  4518. $aRes[] = "$sClassSign: $iHits";
  4519. $iTotalHits += $iHits;
  4520. }
  4521. return $iTotalHits.' ('.implode(', ', $aRes).')';
  4522. }
  4523. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4524. {
  4525. // Build the query cache signature
  4526. //
  4527. $sQuerySign = $sClass;
  4528. if($bAllowAllData)
  4529. {
  4530. $sQuerySign .= '_all_';
  4531. }
  4532. if (count($aModifierProperties))
  4533. {
  4534. array_multisort($aModifierProperties);
  4535. $sModifierProperties = json_encode($aModifierProperties);
  4536. $sQuerySign .= '_all_'.md5($sModifierProperties);
  4537. }
  4538. if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject))
  4539. {
  4540. // NOTE: Quick and VERY dirty caching mechanism which relies on
  4541. // the fact that the string '987654321' will never appear in the
  4542. // standard query
  4543. // This could be simplified a little, relying solely on the query cache,
  4544. // but this would slow down -by how much time?- the application
  4545. $oFilter = new DBObjectSearch($sClass);
  4546. $oFilter->AddCondition('id', 987654321, '=');
  4547. if ($aModifierProperties)
  4548. {
  4549. foreach ($aModifierProperties as $sPluginClass => $aProperties)
  4550. {
  4551. foreach ($aProperties as $sProperty => $value)
  4552. {
  4553. $oFilter->SetModifierProperty($sPluginClass, $sProperty, $value);
  4554. }
  4555. }
  4556. }
  4557. if ($bAllowAllData)
  4558. {
  4559. $oFilter->AllowAllData();
  4560. }
  4561. $sSQL = self::MakeSelectQuery($oFilter);
  4562. self::$aQueryCacheGetObject[$sQuerySign] = $sSQL;
  4563. self::$aQueryCacheGetObjectHits[$sQuerySign] = 0;
  4564. }
  4565. else
  4566. {
  4567. $sSQL = self::$aQueryCacheGetObject[$sQuerySign];
  4568. self::$aQueryCacheGetObjectHits[$sQuerySign] += 1;
  4569. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sQuerySign]."<br/>\n";
  4570. }
  4571. $sSQL = str_replace(CMDBSource::Quote(987654321), CMDBSource::Quote($iKey), $sSQL);
  4572. $res = CMDBSource::Query($sSQL);
  4573. $aRow = CMDBSource::FetchArray($res);
  4574. CMDBSource::FreeResult($res);
  4575. if ($bMustBeFound && empty($aRow))
  4576. {
  4577. throw new CoreException("No result for the single row query: '$sSQL'");
  4578. }
  4579. return $aRow;
  4580. }
  4581. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  4582. {
  4583. self::_check_subclass($sClass);
  4584. if (strlen($sClassAlias) == 0)
  4585. {
  4586. $sClassAlias = $sClass;
  4587. }
  4588. // Compound objects: if available, get the final object class
  4589. //
  4590. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  4591. {
  4592. // Either this is a bug (forgot to specify a root class with a finalclass field
  4593. // Or this is the expected behavior, because the object is not made of several tables
  4594. }
  4595. elseif (empty($aRow[$sClassAlias."finalclass"]))
  4596. {
  4597. // The data is missing in the DB
  4598. // @#@ possible improvement: check that the class is valid !
  4599. $sRootClass = self::GetRootClass($sClass);
  4600. $sFinalClassField = self::DBGetClassField($sRootClass);
  4601. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  4602. }
  4603. else
  4604. {
  4605. // do the job for the real target class
  4606. $sClass = $aRow[$sClassAlias."finalclass"];
  4607. }
  4608. return new $sClass($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  4609. }
  4610. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4611. {
  4612. self::_check_subclass($sClass);
  4613. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
  4614. if (empty($aRow))
  4615. {
  4616. return null;
  4617. }
  4618. return self::GetObjectByRow($sClass, $aRow);
  4619. }
  4620. public static function GetObjectByName($sClass, $sName, $bMustBeFound = true)
  4621. {
  4622. self::_check_subclass($sClass);
  4623. $oObjSearch = new DBObjectSearch($sClass);
  4624. $oObjSearch->AddNameCondition($sName);
  4625. $oSet = new DBObjectSet($oObjSearch);
  4626. if ($oSet->Count() != 1)
  4627. {
  4628. if ($bMustBeFound) throw new CoreException('Failed to get an object by its name', array('class'=>$sClass, 'name'=>$sName));
  4629. return null;
  4630. }
  4631. $oObj = $oSet->fetch();
  4632. return $oObj;
  4633. }
  4634. static protected $m_aCacheObjectByColumn = array();
  4635. public static function GetObjectByColumn($sClass, $sAttCode, $value, $bMustBeFoundUnique = true)
  4636. {
  4637. if (!isset(self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value]))
  4638. {
  4639. self::_check_subclass($sClass);
  4640. $oObjSearch = new DBObjectSearch($sClass);
  4641. $oObjSearch->AddCondition($sAttCode, $value, '=');
  4642. $oSet = new DBObjectSet($oObjSearch);
  4643. if ($oSet->Count() == 1)
  4644. {
  4645. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch();
  4646. }
  4647. else
  4648. {
  4649. if ($bMustBeFoundUnique) throw new CoreException('Failed to get an object by column', array('class'=>$sClass, 'attcode'=>$sAttCode, 'value'=>$value, 'matches' => $oSet->Count()));
  4650. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null;
  4651. }
  4652. }
  4653. return self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value];
  4654. }
  4655. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  4656. {
  4657. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  4658. if ($bAllowAllData)
  4659. {
  4660. $oFilter->AllowAllData();
  4661. }
  4662. $oSet = new DBObjectSet($oFilter);
  4663. $oObject = $oSet->Fetch();
  4664. return $oObject;
  4665. }
  4666. public static function GetHyperLink($sTargetClass, $iKey)
  4667. {
  4668. if ($iKey < 0)
  4669. {
  4670. return "$sTargetClass: $iKey (invalid value)";
  4671. }
  4672. $oObj = self::GetObject($sTargetClass, $iKey, false);
  4673. if (is_null($oObj))
  4674. {
  4675. // Whatever we are looking for, the root class is the key to search for
  4676. $sRootClass = self::GetRootClass($sTargetClass);
  4677. $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', array('objclass' => $sRootClass, 'objkey' => $iKey));
  4678. $oSet = new DBObjectSet($oSearch);
  4679. $oRecord = $oSet->Fetch();
  4680. // An empty fname is obtained with iTop < 2.0
  4681. if (is_null($oRecord) || (strlen(trim($oRecord->Get('fname'))) == 0))
  4682. {
  4683. $sName = Dict::Format('Core:UnknownObjectLabel', $sTargetClass, $iKey);
  4684. $sTitle = Dict::S('Core:UnknownObjectTip');
  4685. }
  4686. else
  4687. {
  4688. $sName = $oRecord->Get('fname');
  4689. $sTitle = Dict::Format('Core:DeletedObjectTip', $oRecord->Get('date'), $oRecord->Get('userinfo'));
  4690. }
  4691. return '<span class="itop-deleted-object" title="'.htmlentities($sTitle, ENT_QUOTES, 'UTF-8').'">'.htmlentities($sName, ENT_QUOTES, 'UTF-8').'</span>';
  4692. }
  4693. return $oObj->GetHyperLink();
  4694. }
  4695. public static function NewObject($sClass)
  4696. {
  4697. self::_check_subclass($sClass);
  4698. return new $sClass();
  4699. }
  4700. public static function GetNextKey($sClass)
  4701. {
  4702. $sRootClass = MetaModel::GetRootClass($sClass);
  4703. $sRootTable = MetaModel::DBGetTable($sRootClass);
  4704. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  4705. return $iNextKey;
  4706. }
  4707. /**
  4708. * Deletion of records, bypassing DBObject::DBDelete !!!
  4709. * It is NOT recommended to use this shortcut
  4710. * In particular, it will not work
  4711. * - if the class is not a final class
  4712. * - if the class has a hierarchical key (need to rebuild the indexes)
  4713. * - if the class overload DBDelete !
  4714. * Todo: protect it against forbidden usages (in such a case, delete objects one by one)
  4715. */
  4716. public static function BulkDelete(DBObjectSearch $oFilter)
  4717. {
  4718. $sSQL = self::MakeDeleteQuery($oFilter);
  4719. if (!self::DBIsReadOnly())
  4720. {
  4721. CMDBSource::Query($sSQL);
  4722. }
  4723. }
  4724. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  4725. {
  4726. // $aValues is an array of $sAttCode => $value
  4727. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  4728. if (!self::DBIsReadOnly())
  4729. {
  4730. CMDBSource::Query($sSQL);
  4731. }
  4732. }
  4733. /**
  4734. * Helper to remove selected objects without calling any handler
  4735. * Surpasses BulkDelete as it can handle abstract classes, but has the other limitation as it bypasses standard objects handlers
  4736. *
  4737. * @param string $oFilter Scope of objects to wipe out
  4738. * @return The count of deleted objects
  4739. */
  4740. public static function PurgeData($oFilter)
  4741. {
  4742. $sTargetClass = $oFilter->GetClass();
  4743. $oSet = new DBObjectSet($oFilter);
  4744. $oSet->OptimizeColumnLoad(array($sTargetClass => array('finalclass')));
  4745. $aIdToClass = $oSet->GetColumnAsArray('finalclass', true);
  4746. $aIds = array_keys($aIdToClass);
  4747. if (count($aIds) > 0)
  4748. {
  4749. $aQuotedIds = CMDBSource::Quote($aIds);
  4750. $sIdList = implode(',', $aQuotedIds);
  4751. $aTargetClasses = array_merge(
  4752. self::EnumChildClasses($sTargetClass, ENUM_CHILD_CLASSES_ALL),
  4753. self::EnumParentClasses($sTargetClass, ENUM_PARENT_CLASSES_EXCLUDELEAF)
  4754. );
  4755. foreach ($aTargetClasses as $sSomeClass)
  4756. {
  4757. $sTable = MetaModel::DBGetTable($sSomeClass);
  4758. $sPKField = MetaModel::DBGetKey($sSomeClass);
  4759. $sDeleteSQL = "DELETE FROM `$sTable` WHERE `$sPKField` IN ($sIdList)";
  4760. CMDBSource::DeleteFrom($sDeleteSQL);
  4761. }
  4762. }
  4763. return count($aIds);
  4764. }
  4765. // Links
  4766. //
  4767. //
  4768. public static function EnumReferencedClasses($sClass)
  4769. {
  4770. self::_check_subclass($sClass);
  4771. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  4772. $aResult = array();
  4773. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  4774. {
  4775. if ($oAttDef->IsExternalKey())
  4776. {
  4777. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  4778. }
  4779. }
  4780. return $aResult;
  4781. }
  4782. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  4783. {
  4784. self::_check_subclass($sClass);
  4785. if ($bSkipLinkingClasses)
  4786. {
  4787. $aLinksClasses = self::EnumLinksClasses();
  4788. }
  4789. // 1-N links (referencing my class), array of sClass => array of sAttcode
  4790. $aResult = array();
  4791. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4792. {
  4793. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  4794. $aExtKeys = array();
  4795. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4796. {
  4797. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4798. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  4799. {
  4800. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  4801. // Ok, I want this one
  4802. $aExtKeys[$sAttCode] = $oAttDef;
  4803. }
  4804. }
  4805. if (count($aExtKeys) != 0)
  4806. {
  4807. $aResult[$sSomeClass] = $aExtKeys;
  4808. }
  4809. }
  4810. return $aResult;
  4811. }
  4812. /**
  4813. * It is not recommended to use this function: call GetLinkClasses instead
  4814. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  4815. * The only difference with EnumLinkingClasses is the output format
  4816. */
  4817. public static function EnumLinksClasses()
  4818. {
  4819. // Returns a flat array of classes having at least two external keys
  4820. $aResult = array();
  4821. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4822. {
  4823. $iExtKeyCount = 0;
  4824. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4825. {
  4826. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4827. if ($oAttDef->IsExternalKey())
  4828. {
  4829. $iExtKeyCount++;
  4830. }
  4831. }
  4832. if ($iExtKeyCount >= 2)
  4833. {
  4834. $aResult[] = $sSomeClass;
  4835. }
  4836. }
  4837. return $aResult;
  4838. }
  4839. /**
  4840. * It is not recommended to use this function: call GetLinkClasses instead
  4841. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  4842. * The only difference with EnumLinksClasses is the output format
  4843. */
  4844. public static function EnumLinkingClasses($sClass = "")
  4845. {
  4846. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  4847. $aResult = array();
  4848. foreach (self::EnumLinksClasses() as $sSomeClass)
  4849. {
  4850. $aTargets = array();
  4851. $bFoundClass = false;
  4852. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  4853. {
  4854. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4855. if ($oAttDef->IsExternalKey())
  4856. {
  4857. $sRemoteClass = $oAttDef->GetTargetClass();
  4858. if (empty($sClass))
  4859. {
  4860. $aTargets[$sAttCode] = $sRemoteClass;
  4861. }
  4862. elseif ($sClass == $sRemoteClass)
  4863. {
  4864. $bFoundClass = true;
  4865. }
  4866. else
  4867. {
  4868. $aTargets[$sAttCode] = $sRemoteClass;
  4869. }
  4870. }
  4871. }
  4872. if (empty($sClass) || $bFoundClass)
  4873. {
  4874. $aResult[$sSomeClass] = $aTargets;
  4875. }
  4876. }
  4877. return $aResult;
  4878. }
  4879. /**
  4880. * This function has two siblings that will be soon deprecated:
  4881. * EnumLinkingClasses and EnumLinkClasses
  4882. *
  4883. * Using GetLinkClasses is the recommended way to determine if a class is
  4884. * actually an N-N relation because it is based on the decision made by the
  4885. * designer the data model
  4886. */
  4887. public static function GetLinkClasses()
  4888. {
  4889. $aRet = array();
  4890. foreach(self::GetClasses() as $sClass)
  4891. {
  4892. if (isset(self::$m_aClassParams[$sClass]["is_link"]))
  4893. {
  4894. if (self::$m_aClassParams[$sClass]["is_link"])
  4895. {
  4896. $aExtKeys = array();
  4897. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  4898. {
  4899. if ($oAttDef->IsExternalKey())
  4900. {
  4901. $aExtKeys[$sAttCode] = $oAttDef->GetTargetClass();
  4902. }
  4903. }
  4904. $aRet[$sClass] = $aExtKeys;
  4905. }
  4906. }
  4907. }
  4908. return $aRet;
  4909. }
  4910. public static function GetLinkLabel($sLinkClass, $sAttCode)
  4911. {
  4912. self::_check_subclass($sLinkClass);
  4913. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  4914. return self::GetLabel($sLinkClass, $sAttCode);
  4915. }
  4916. /**
  4917. * Replaces all the parameters by the values passed in the hash array
  4918. */
  4919. static public function ApplyParams($aInput, $aParams)
  4920. {
  4921. // Declare magic parameters
  4922. $aParams['APP_URL'] = utils::GetAbsoluteUrlAppRoot();
  4923. $aParams['MODULES_URL'] = utils::GetAbsoluteUrlModulesRoot();
  4924. $aSearches = array();
  4925. $aReplacements = array();
  4926. foreach($aParams as $sSearch => $replace)
  4927. {
  4928. // Some environment parameters are objects, we just need scalars
  4929. if (is_object($replace)) continue;
  4930. $aSearches[] = '$'.$sSearch.'$';
  4931. $aReplacements[] = (string) $replace;
  4932. }
  4933. return str_replace($aSearches, $aReplacements, $aInput);
  4934. }
  4935. /**
  4936. * Returns an array of classes=>instance implementing the given interface
  4937. */
  4938. public static function EnumPlugins($sInterface)
  4939. {
  4940. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4941. {
  4942. return self::$m_aExtensionClasses[$sInterface];
  4943. }
  4944. else
  4945. {
  4946. return array();
  4947. }
  4948. }
  4949. /**
  4950. * Returns the instance of the specified plug-ins for the given interface
  4951. */
  4952. public static function GetPlugins($sInterface, $sClassName)
  4953. {
  4954. $oInstance = null;
  4955. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4956. {
  4957. if (array_key_exists($sClassName, self::$m_aExtensionClasses[$sInterface]))
  4958. {
  4959. return self::$m_aExtensionClasses[$sInterface][$sClassName];
  4960. }
  4961. }
  4962. return $oInstance;
  4963. }
  4964. public static function GetCacheEntries($sEnvironment = null)
  4965. {
  4966. if (!function_exists('apc_cache_info')) return array();
  4967. if (is_null($sEnvironment))
  4968. {
  4969. $sEnvironment = MetaModel::GetEnvironmentId();
  4970. }
  4971. $aEntries = array();
  4972. if (extension_loaded('apcu'))
  4973. {
  4974. // Beware: APCu behaves slightly differently from APC !!
  4975. $aCacheUserData = @apc_cache_info();
  4976. }
  4977. else
  4978. {
  4979. $aCacheUserData = @apc_cache_info('user');
  4980. }
  4981. if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list']))
  4982. {
  4983. $sPrefix = 'itop-'.$sEnvironment.'-';
  4984. foreach($aCacheUserData['cache_list'] as $i => $aEntry)
  4985. {
  4986. $sEntryKey = array_key_exists('info', $aEntry) ? $aEntry['info'] : $aEntry['key'];
  4987. if (strpos($sEntryKey, $sPrefix) === 0)
  4988. {
  4989. $sCleanKey = substr($sEntryKey, strlen($sPrefix));
  4990. $aEntries[$sCleanKey] = $aEntry;
  4991. $aEntries[$sCleanKey]['info'] = $sEntryKey;
  4992. }
  4993. }
  4994. }
  4995. return $aEntries;
  4996. }
  4997. public static function ResetCache($sEnvironmentId = null)
  4998. {
  4999. if (!function_exists('apc_delete')) return;
  5000. if (is_null($sEnvironmentId))
  5001. {
  5002. $sEnvironmentId = MetaModel::GetEnvironmentId();
  5003. }
  5004. $sAppIdentity = 'itop-'.$sEnvironmentId;
  5005. Dict::ResetCache($sAppIdentity);
  5006. foreach(self::GetCacheEntries($sEnvironmentId) as $sKey => $aAPCInfo)
  5007. {
  5008. $sAPCKey = $aAPCInfo['info'];
  5009. apc_delete($sAPCKey);
  5010. }
  5011. }
  5012. } // class MetaModel
  5013. // Standard attribute lists
  5014. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  5015. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  5016. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  5017. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  5018. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  5019. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  5020. ?>