metamodel.class.php 172 KB

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