metamodel.class.php 168 KB

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