metamodel.class.php 139 KB

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