metamodel.class.php 158 KB

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