metamodel.class.php 150 KB

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