metamodel.class.php 174 KB

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