metamodel.class.php 171 KB

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