metamodel.class.php 162 KB

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