metamodel.class.php 121 KB

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