metamodel.class.php 137 KB

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