metamodel.class.php 161 KB

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