metamodel.class.php 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952
  1. <?php
  2. // #@# todo: change into class const (see Doctrine)
  3. // Doctrine example
  4. // class toto
  5. // {
  6. // /**
  7. // * VERSION
  8. // */
  9. // const VERSION = '1.0.0';
  10. // }
  11. /**
  12. * add some description here...
  13. *
  14. * @package iTopORM
  15. */
  16. define('ENUM_CHILD_CLASSES_EXCLUDETOP', 1);
  17. /**
  18. * add some description here...
  19. *
  20. * @package iTopORM
  21. */
  22. define('ENUM_CHILD_CLASSES_ALL', 2);
  23. /**
  24. * Specifies that this attribute is hidden in that state
  25. *
  26. * @package iTopORM
  27. */
  28. define('OPT_ATT_HIDDEN', 1);
  29. /**
  30. * Specifies that this attribute is not editable in that state
  31. *
  32. * @package iTopORM
  33. */
  34. define('OPT_ATT_READONLY', 2);
  35. /**
  36. * Specifieds that the attribute must be set (different than default value?) when arriving into that state
  37. *
  38. * @package iTopORM
  39. */
  40. define('OPT_ATT_MANDATORY', 4);
  41. /**
  42. * Specifies that the attribute must change when arriving into that state
  43. *
  44. * @package iTopORM
  45. */
  46. define('OPT_ATT_MUSTCHANGE', 8);
  47. /**
  48. * Specifies that the attribute must be proposed when arriving into that state
  49. *
  50. * @package iTopORM
  51. */
  52. define('OPT_ATT_MUSTPROMPT', 16);
  53. /**
  54. * (API) The objects definitions as well as their mapping to the database
  55. *
  56. * @package iTopORM
  57. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  58. * @author Denis Flaven <denisflave@free.fr>
  59. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  60. * @link www.itop.com
  61. * @since 1.0
  62. * @version 1.1.1.1 $
  63. */
  64. abstract class MetaModel
  65. {
  66. ///////////////////////////////////////////////////////////////////////////
  67. //
  68. // STATIC Members
  69. //
  70. ///////////////////////////////////////////////////////////////////////////
  71. // Purpose: workaround the following limitation = PHP5 does not allow to know the class (derived from the current one)
  72. // from which a static function is called (__CLASS__ and self are interpreted during parsing)
  73. private static function GetCallersPHPClass($sExpectedFunctionName = null)
  74. {
  75. //var_dump(debug_backtrace());
  76. $aBacktrace = debug_backtrace();
  77. // $aBacktrace[0] is where we are
  78. // $aBacktrace[1] is the caller of GetCallersPHPClass
  79. // $aBacktrace[1] is the info we want
  80. if (!empty($sExpectedFunctionName))
  81. {
  82. assert('$aBacktrace[2]["function"] == $sExpectedFunctionName');
  83. }
  84. return $aBacktrace[2]["class"];
  85. }
  86. // Static init -why and how it works
  87. //
  88. // We found the following limitations:
  89. //- it is not possible to define non scalar constants
  90. //- it is not possible to declare a static variable as '= new myclass()'
  91. // Then we had do propose this model, in which a derived (non abstract)
  92. // class should implement Init(), to call InheritAttributes or AddAttribute.
  93. private static function _check_subclass($sClass)
  94. {
  95. // See also IsValidClass()... ???? #@#
  96. // class is mandatory
  97. // (it is not possible to guess it when called as myderived::...)
  98. if (!array_key_exists($sClass, self::$m_aClassParams))
  99. {
  100. throw new CoreException("Unknown class '$sClass', expected a value in {".implode(', ', array_keys(self::$m_aClassParams))."}");
  101. }
  102. }
  103. public static function static_var_dump()
  104. {
  105. var_dump(get_class_vars(__CLASS__));
  106. }
  107. private static $m_bDebugQuery = false;
  108. private static $m_iStackDepthRef = 0;
  109. public static function StartDebugQuery()
  110. {
  111. $aBacktrace = debug_backtrace();
  112. self::$m_iStackDepthRef = count($aBacktrace);
  113. self::$m_bDebugQuery = true;
  114. }
  115. public static function StopDebugQuery()
  116. {
  117. self::$m_bDebugQuery = false;
  118. }
  119. public static function DbgTrace($value)
  120. {
  121. if (!self::$m_bDebugQuery) return;
  122. $aBacktrace = debug_backtrace();
  123. $iCallStackPos = count($aBacktrace) - self::$m_bDebugQuery;
  124. $sIndent = "";
  125. for ($i = 0 ; $i < $iCallStackPos ; $i++)
  126. {
  127. $sIndent .= " .-=^=-. ";
  128. }
  129. $aCallers = array();
  130. foreach($aBacktrace as $aStackInfo)
  131. {
  132. $aCallers[] = $aStackInfo["function"];
  133. }
  134. $sCallers = "Callstack: ".implode(', ', $aCallers);
  135. $sFunction = "<b title=\"$sCallers\">".$aBacktrace[1]["function"]."</b>";
  136. if (is_string($value))
  137. {
  138. echo "$sIndent$sFunction: $value<br/>\n";
  139. }
  140. else if (is_object($value))
  141. {
  142. echo "$sIndent$sFunction:\n<pre>\n";
  143. print_r($value);
  144. echo "</pre>\n";
  145. }
  146. else
  147. {
  148. echo "$sIndent$sFunction: $value<br/>\n";
  149. }
  150. }
  151. private static $m_bTraceQueries = true;
  152. private static $m_aQueriesLog = array();
  153. private static $m_sDBName = "";
  154. private static $m_sTablePrefix = ""; // table prefix for the current application instance (allow several applications on the same DB)
  155. private static $m_Category2Class = array();
  156. private static $m_aRootClasses = array(); // array of "classname" => "rootclass"
  157. private static $m_aParentClasses = array(); // array of ("classname" => array of "parentclass")
  158. private static $m_aChildClasses = array(); // array of ("classname" => array of "childclass")
  159. private static $m_aClassParams = array(); // array of ("classname" => array of class information)
  160. static public function GetParentPersistentClass($sRefClass)
  161. {
  162. $sClass = get_parent_class($sRefClass);
  163. if (!$sClass) return '';
  164. if ($sClass == 'DBObject') return ''; // Warning: __CLASS__ is lower case in my version of PHP
  165. // Note: the UI/business model may implement pure PHP classes (intermediate layers)
  166. if (array_key_exists($sClass, self::$m_aClassParams))
  167. {
  168. return $sClass;
  169. }
  170. return self::GetParentPersistentClass($sClass);
  171. }
  172. final static public function GetName($sClass)
  173. {
  174. self::_check_subclass($sClass);
  175. return self::$m_aClassParams[$sClass]["name"];
  176. }
  177. final static public function GetCategory($sClass)
  178. {
  179. self::_check_subclass($sClass);
  180. return self::$m_aClassParams[$sClass]["category"];
  181. }
  182. final static public function HasCategory($sClass, $sCategory)
  183. {
  184. self::_check_subclass($sClass);
  185. return (strpos(self::$m_aClassParams[$sClass]["category"], $sCategory) !== false);
  186. }
  187. final static public function GetClassDescription($sClass)
  188. {
  189. self::_check_subclass($sClass);
  190. return self::$m_aClassParams[$sClass]["description"];
  191. }
  192. final static public function IsAutoIncrementKey($sClass)
  193. {
  194. self::_check_subclass($sClass);
  195. return (self::$m_aClassParams[$sClass]["key_type"] == "autoincrement");
  196. }
  197. final static public function GetKeyLabel($sClass)
  198. {
  199. self::_check_subclass($sClass);
  200. return self::$m_aClassParams[$sClass]["key_label"];
  201. }
  202. final static public function GetNameAttributeCode($sClass)
  203. {
  204. self::_check_subclass($sClass);
  205. return self::$m_aClassParams[$sClass]["name_attcode"];
  206. }
  207. final static public function GetStateAttributeCode($sClass)
  208. {
  209. self::_check_subclass($sClass);
  210. return self::$m_aClassParams[$sClass]["state_attcode"];
  211. }
  212. final static public function GetDefaultState($sClass)
  213. {
  214. $sDefaultState = '';
  215. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  216. if (!empty($sStateAttrCode))
  217. {
  218. $oStateAttrDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  219. $sDefaultState = $oStateAttrDef->GetDefaultValue();
  220. }
  221. return $sDefaultState;
  222. }
  223. final static public function GetReconcKeys($sClass)
  224. {
  225. self::_check_subclass($sClass);
  226. return self::$m_aClassParams[$sClass]["reconc_keys"];
  227. }
  228. final static public function GetDisplayTemplate($sClass)
  229. {
  230. self::_check_subclass($sClass);
  231. return self::$m_aClassParams[$sClass]["display_template"];
  232. }
  233. final static public function GetAttributeOrigin($sClass, $sAttCode)
  234. {
  235. self::_check_subclass($sClass);
  236. return self::$m_aAttribOrigins[$sClass][$sAttCode];
  237. }
  238. final static public function GetPrequisiteAttributes($sClass, $sAttCode)
  239. {
  240. self::_check_subclass($sClass);
  241. $oAtt = self::GetAttributeDef($sClass, $sAttCode);
  242. // Temporary implementation: later, we might be able to compute
  243. // the dependencies, based on the attributes definition
  244. // (allowed values and default values)
  245. if ($oAtt->IsWritable())
  246. {
  247. return $oAtt->GetPrerequisiteAttributes();
  248. }
  249. else
  250. {
  251. return array();
  252. }
  253. }
  254. // #@# restore to private ?
  255. final static public function DBGetTable($sClass, $sAttCode = null)
  256. {
  257. self::_check_subclass($sClass);
  258. if (empty($sAttCode) || ($sAttCode == "id"))
  259. {
  260. $sTableRaw = self::$m_aClassParams[$sClass]["db_table"];
  261. if (empty($sTableRaw))
  262. {
  263. // return an empty string whenever the table is undefined, meaning that there is no table associated to this 'abstract' class
  264. return '';
  265. }
  266. else
  267. {
  268. return self::$m_sTablePrefix.$sTableRaw;
  269. }
  270. }
  271. // This attribute has been inherited (compound objects)
  272. return self::DBGetTable(self::$m_aAttribOrigins[$sClass][$sAttCode]);
  273. }
  274. final static protected function DBEnumTables()
  275. {
  276. // This API do not rely on our capability to query the DB and retrieve
  277. // the list of existing tables
  278. // Rather, it uses the list of expected tables, corresponding to the data model
  279. $aTables = array();
  280. foreach (self::GetClasses() as $sClass)
  281. {
  282. if (self::IsAbstract($sClass)) continue;
  283. $sTable = self::DBGetTable($sClass);
  284. // Could be completed later with all the classes that are using a given table
  285. if (!array_key_exists($sTable, $aTables))
  286. {
  287. $aTables[$sTable] = array();
  288. }
  289. $aTables[$sTable][] = $sClass;
  290. }
  291. return $aTables;
  292. }
  293. final static public function DBGetKey($sClass)
  294. {
  295. self::_check_subclass($sClass);
  296. return self::$m_aClassParams[$sClass]["db_key_field"];
  297. }
  298. final static public function DBGetClassField($sClass)
  299. {
  300. self::_check_subclass($sClass);
  301. return self::$m_aClassParams[$sClass]["db_finalclass_field"];
  302. }
  303. final static public function HasFinalClassField($sClass)
  304. {
  305. self::_check_subclass($sClass);
  306. if (!array_key_exists("db_finalclass_field", self::$m_aClassParams[$sClass])) return false;
  307. return (self::$m_aClassParams[$sClass]["db_finalclass_field"]);
  308. }
  309. final static public function IsStandaloneClass($sClass)
  310. {
  311. self::_check_subclass($sClass);
  312. $sRootClass = self::GetRootClass($sClass);
  313. return (!self::HasFinalClassField($sRootClass));
  314. }
  315. final static public function IsParentClass($sParentClass, $sChildClass)
  316. {
  317. self::_check_subclass($sChildClass);
  318. self::_check_subclass($sParentClass);
  319. if (in_array($sParentClass, self::$m_aParentClasses[$sChildClass])) return true;
  320. if ($sChildClass == $sParentClass) return true;
  321. return false;
  322. }
  323. final static public function IsSameFamilyBranch($sClassA, $sClassB)
  324. {
  325. self::_check_subclass($sClassA);
  326. self::_check_subclass($sClassB);
  327. if (in_array($sClassA, self::$m_aParentClasses[$sClassB])) return true;
  328. if (in_array($sClassB, self::$m_aParentClasses[$sClassA])) return true;
  329. if ($sClassA == $sClassB) return true;
  330. return false;
  331. }
  332. final static public function IsSameFamily($sClassA, $sClassB)
  333. {
  334. self::_check_subclass($sClassA);
  335. self::_check_subclass($sClassB);
  336. return (self::GetRootClass($sClassA) == self::GetRootClass($sClassB));
  337. }
  338. // Attributes of a given class may contain attributes defined in a parent class
  339. // - Some attributes are a copy of the definition
  340. // - Some attributes correspond to the upper class table definition (compound objects)
  341. // (see also filters definition)
  342. private static $m_aAttribDefs = array(); // array of ("classname" => array of attributes)
  343. private static $m_aAttribOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  344. private static $m_aExtKeyFriends = array(); // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  345. final static public function ListAttributeDefs($sClass)
  346. {
  347. self::_check_subclass($sClass);
  348. return self::$m_aAttribDefs[$sClass];
  349. }
  350. final public static function GetAttributesList($sClass)
  351. {
  352. self::_check_subclass($sClass);
  353. return array_keys(self::$m_aAttribDefs[$sClass]);
  354. }
  355. final public static function GetFiltersList($sClass)
  356. {
  357. self::_check_subclass($sClass);
  358. return array_keys(self::$m_aFilterDefs[$sClass]);
  359. }
  360. final public static function GetKeysList($sClass)
  361. {
  362. self::_check_subclass($sClass);
  363. $aExtKeys = array();
  364. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  365. {
  366. if ($oAttDef->IsExternalKey())
  367. {
  368. $aExtKeys[] = $sAttCode;
  369. }
  370. }
  371. return $aExtKeys;
  372. }
  373. final static public function IsValidKeyAttCode($sClass, $sAttCode)
  374. {
  375. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  376. if (!array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass])) return false;
  377. return (self::$m_aAttribDefs[$sClass][$sAttCode]->IsExternalKey());
  378. }
  379. final static public function IsValidAttCode($sClass, $sAttCode)
  380. {
  381. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  382. return (array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]));
  383. }
  384. final static public function IsAttributeOrigin($sClass, $sAttCode)
  385. {
  386. return (self::$m_aAttribOrigins[$sClass][$sAttCode] == $sClass);
  387. }
  388. final static public function IsValidFilterCode($sClass, $sFilterCode)
  389. {
  390. if (!array_key_exists($sClass, self::$m_aFilterDefs)) return false;
  391. return (array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]));
  392. }
  393. public static function IsValidClass($sClass)
  394. {
  395. return (array_key_exists($sClass, self::$m_aAttribDefs));
  396. }
  397. public static function IsValidObject($oObject)
  398. {
  399. if (!is_object($oObject)) return false;
  400. return (self::IsValidClass(get_class($oObject)));
  401. }
  402. public static function IsReconcKey($sClass, $sAttCode)
  403. {
  404. return (in_array($sAttCode, self::GetReconcKeys($sClass)));
  405. }
  406. final static public function GetAttributeDef($sClass, $sAttCode)
  407. {
  408. self::_check_subclass($sClass);
  409. return self::$m_aAttribDefs[$sClass][$sAttCode];
  410. }
  411. final static public function GetExternalKeys($sClass)
  412. {
  413. $aExtKeys = array();
  414. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  415. {
  416. if ($oAtt->IsExternalKey())
  417. {
  418. $aExtKeys[$sAttCode] = $oAtt;
  419. }
  420. }
  421. return $aExtKeys;
  422. }
  423. final static public function GetLinkedSets($sClass)
  424. {
  425. $aLinkedSets = array();
  426. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  427. {
  428. if (is_subclass_of($oAtt, 'AttributeLinkedSet'))
  429. {
  430. $aLinkedSets[$sAttCode] = $oAtt;
  431. }
  432. }
  433. return $aLinkedSets;
  434. }
  435. final static public function GetExternalFields($sClass, $sKeyAttCode)
  436. {
  437. $aExtFields = array();
  438. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  439. {
  440. if ($oAtt->IsExternalField() && ($oAtt->GetKeyAttCode() == $sKeyAttCode))
  441. {
  442. $aExtFields[] = $oAtt;
  443. }
  444. }
  445. return $aExtFields;
  446. }
  447. final static public function GetExtKeyFriends($sClass, $sExtKeyAttCode)
  448. {
  449. if (array_key_exists($sExtKeyAttCode, self::$m_aExtKeyFriends[$sClass]))
  450. {
  451. return self::$m_aExtKeyFriends[$sClass][$sExtKeyAttCode];
  452. }
  453. else
  454. {
  455. return array();
  456. }
  457. }
  458. public static function GetLabel($sClass, $sAttCode)
  459. {
  460. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  461. if ($oAttDef) return $oAttDef->GetLabel();
  462. return "";
  463. }
  464. public static function GetDescription($sClass, $sAttCode)
  465. {
  466. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  467. if ($oAttDef) return $oAttDef->GetDescription();
  468. return "";
  469. }
  470. // Filters of a given class may contain filters defined in a parent class
  471. // - Some filters are a copy of the definition
  472. // - Some filters correspond to the upper class table definition (compound objects)
  473. // (see also attributes definition)
  474. private static $m_aFilterDefs = array(); // array of ("classname" => array filterdef)
  475. private static $m_aFilterOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  476. public static function GetClassFilterDefs($sClass)
  477. {
  478. self::_check_subclass($sClass);
  479. return self::$m_aFilterDefs[$sClass];
  480. }
  481. final static public function GetClassFilterDef($sClass, $sFilterCode)
  482. {
  483. self::_check_subclass($sClass);
  484. return self::$m_aFilterDefs[$sClass][$sFilterCode];
  485. }
  486. public static function GetFilterLabel($sClass, $sFilterCode)
  487. {
  488. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  489. if ($oFilter) return $oFilter->GetLabel();
  490. return "";
  491. }
  492. public static function GetFilterDescription($sClass, $sFilterCode)
  493. {
  494. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  495. if ($oFilter) return $oFilter->GetDescription();
  496. return "";
  497. }
  498. // returns an array of opcode=>oplabel (e.g. "differs from")
  499. public static function GetFilterOperators($sClass, $sFilterCode)
  500. {
  501. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  502. if ($oFilter) return $oFilter->GetOperators();
  503. return array();
  504. }
  505. // returns an opcode
  506. public static function GetFilterLooseOperator($sClass, $sFilterCode)
  507. {
  508. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  509. if ($oFilter) return $oFilter->GetLooseOperator();
  510. return array();
  511. }
  512. public static function GetFilterOpDescription($sClass, $sFilterCode, $sOpCode)
  513. {
  514. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  515. if ($oFilter) return $oFilter->GetOpDescription($sOpCode);
  516. return "";
  517. }
  518. public static function GetFilterHTMLInput($sFilterCode)
  519. {
  520. return "<INPUT name=\"$sFilterCode\">";
  521. }
  522. // Lists of attributes/search filters
  523. //
  524. private static $m_aListInfos = array(); // array of ("listcode" => various info on the list, common to every classes)
  525. private static $m_aListData = array(); // array of ("classname" => array of "listcode" => list)
  526. // list may be an array of attcode / fltcode
  527. // list may be an array of "groupname" => (array of attcode / fltcode)
  528. public static function EnumZLists()
  529. {
  530. return array_keys(self::$m_aListInfos);
  531. }
  532. final static public function GetZListInfo($sListCode)
  533. {
  534. return self::$m_aListInfos[$sListCode];
  535. }
  536. public static function GetZListItems($sClass, $sListCode)
  537. {
  538. if (array_key_exists($sClass, self::$m_aListData))
  539. {
  540. if (array_key_exists($sListCode, self::$m_aListData[$sClass]))
  541. {
  542. return self::$m_aListData[$sClass][$sListCode];
  543. }
  544. }
  545. $sParentClass = self::GetParentPersistentClass($sClass);
  546. if (empty($sParentClass)) return array(); // nothing for the mother of all classes
  547. // Dig recursively
  548. return self::GetZListItems($sParentClass, $sListCode);
  549. }
  550. public static function IsAttributeInZList($sClass, $sListCode, $sAttCodeOrFltCode, $sGroup = null)
  551. {
  552. $aZList = self::GetZListItems($sClass, $sListCode);
  553. if (!$sGroup)
  554. {
  555. return (in_array($sAttCodeOrFltCode, $aZList));
  556. }
  557. return (in_array($sAttCodeOrFltCode, $aZList[$sGroup]));
  558. }
  559. //
  560. // Relations
  561. //
  562. private static $m_aRelationInfos = array(); // array of ("relcode" => various info on the list, common to every classes)
  563. public static function EnumRelations()
  564. {
  565. return array_keys(self::$m_aRelationInfos);
  566. }
  567. public static function EnumRelationProperties($sRelCode)
  568. {
  569. MyHelpers::CheckKeyInArray('relation code', $sRelCode, self::$m_aRelationInfos);
  570. return self::$m_aRelationInfos[$sRelCode];
  571. }
  572. final static public function GetRelationProperty($sRelCode, $sProperty)
  573. {
  574. MyHelpers::CheckKeyInArray('relation code', $sRelCode, self::$m_aRelationInfos);
  575. MyHelpers::CheckKeyInArray('relation property', $sProperty, self::$m_aRelationInfos[$sRelCode]);
  576. return self::$m_aRelationInfos[$sRelCode][$sProperty];
  577. }
  578. public static function EnumRelationQueries($sClass, $sRelCode)
  579. {
  580. MyHelpers::CheckKeyInArray('relation code', $sRelCode, self::$m_aRelationInfos);
  581. return call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRelCode));
  582. }
  583. //
  584. // Object lifecycle model
  585. //
  586. private static $m_aStates = array(); // array of ("classname" => array of "statecode"=>array('label'=>..., 'description'=>..., attribute_inherit=> attribute_list=>...))
  587. private static $m_aStimuli = array(); // array of ("classname" => array of ("stimuluscode"=>array('label'=>..., 'description'=>...)))
  588. 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)))
  589. public static function EnumStates($sClass)
  590. {
  591. if (array_key_exists($sClass, self::$m_aStates))
  592. {
  593. return self::$m_aStates[$sClass];
  594. }
  595. else
  596. {
  597. return array();
  598. }
  599. }
  600. public static function EnumStimuli($sClass)
  601. {
  602. if (array_key_exists($sClass, self::$m_aStimuli))
  603. {
  604. return self::$m_aStimuli[$sClass];
  605. }
  606. else
  607. {
  608. return array();
  609. }
  610. }
  611. public static function EnumTransitions($sClass, $sStateCode)
  612. {
  613. if (array_key_exists($sClass, self::$m_aTransitions))
  614. {
  615. if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
  616. {
  617. return self::$m_aTransitions[$sClass][$sStateCode];
  618. }
  619. }
  620. return array();
  621. }
  622. public static function GetAttributeFlags($sClass, $sState, $sAttCode)
  623. {
  624. $iFlags = 0; // By default (if no life cycle) no flag at all
  625. $sStateAttCode = self::GetStateAttributeCode($sClass);
  626. if (!empty($sStateAttCode))
  627. {
  628. $aStates = MetaModel::EnumStates($sClass);
  629. if (!array_key_exists($sState, $aStates))
  630. {
  631. throw new CoreException("Invalid state '$sState' for class '$sClass', expecting a value in {".implode(', ', array_keys($aStates))."}");
  632. }
  633. $aCurrentState = $aStates[$sState];
  634. if ( (array_key_exists('attribute_list', $aCurrentState)) && (array_key_exists($sAttCode, $aCurrentState['attribute_list'])) )
  635. {
  636. $iFlags = $aCurrentState['attribute_list'][$sAttCode];
  637. }
  638. }
  639. return $iFlags;
  640. }
  641. //
  642. // Allowed values
  643. //
  644. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sBeginsWith = '')
  645. {
  646. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  647. return $oAttDef->GetAllowedValues($aArgs, $sBeginsWith);
  648. }
  649. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sBeginsWith = '')
  650. {
  651. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  652. return $oFltDef->GetAllowedValues($aArgs, $sBeginsWith);
  653. }
  654. //
  655. // Businezz model declaration verbs (should be static)
  656. //
  657. public static function RegisterZList($sListCode, $aListInfo)
  658. {
  659. // Check mandatory params
  660. $aMandatParams = array(
  661. "description" => "detailed (though one line) description of the list",
  662. "type" => "attributes | filters",
  663. );
  664. foreach($aMandatParams as $sParamName=>$sParamDesc)
  665. {
  666. if (!array_key_exists($sParamName, $aListInfo))
  667. {
  668. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  669. }
  670. }
  671. self::$m_aListInfos[$sListCode] = $aListInfo;
  672. }
  673. public static function RegisterRelation($sRelCode, $aRelationInfo)
  674. {
  675. // Check mandatory params
  676. $aMandatParams = array(
  677. "description" => "detailed (though one line) description of the list",
  678. "verb_down" => "e.g.: 'impacts'",
  679. "verb_up" => "e.g.: 'is impacted by'",
  680. );
  681. foreach($aMandatParams as $sParamName=>$sParamDesc)
  682. {
  683. if (!array_key_exists($sParamName, $aRelationInfo))
  684. {
  685. throw new CoreException("Declaration of relation $sRelCode - missing parameter $sParamName");
  686. }
  687. }
  688. self::$m_aRelationInfos[$sRelCode] = $aRelationInfo;
  689. }
  690. // Must be called once and only once...
  691. public static function InitClasses($sTablePrefix)
  692. {
  693. if (count(self::GetClasses()) > 0)
  694. {
  695. throw new CoreException("InitClasses should not be called more than once -skipped");
  696. return;
  697. }
  698. self::$m_sTablePrefix = $sTablePrefix;
  699. foreach(get_declared_classes() as $sPHPClass) {
  700. if (is_subclass_of($sPHPClass, 'DBObject'))
  701. {
  702. if (method_exists($sPHPClass, 'Init'))
  703. {
  704. call_user_func(array($sPHPClass, 'Init'));
  705. }
  706. }
  707. }
  708. foreach (self::GetClasses() as $sClass)
  709. {
  710. // Compute the fields that will be used to display a pointer to another object
  711. //
  712. self::$m_aExtKeyFriends[$sClass] = array();
  713. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  714. {
  715. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  716. {
  717. // oAttDef is either
  718. // - an external KEY / FIELD (direct),
  719. // - an external field pointing to an external KEY / FIELD
  720. // - an external field pointing to an external field pointing to....
  721. // Get the real external key attribute
  722. // It will be our reference to determine the other ext fields related to the same ext key
  723. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  724. self::$m_aExtKeyFriends[$sClass][$sAttCode] = array();
  725. foreach (self::GetExternalFields($sClass, $oAttDef->GetKeyAttCode($sAttCode)) as $oExtField)
  726. {
  727. // skip : those extfields will be processed as external keys
  728. if ($oExtField->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  729. // Note: I could not compare the objects by the mean of '==='
  730. // because they are copied for the inheritance, and the internal references are NOT updated
  731. if ($oExtField->GetKeyAttDef(EXTKEY_ABSOLUTE) == $oFinalKeyAttDef)
  732. {
  733. self::$m_aExtKeyFriends[$sClass][$sAttCode][$oExtField->GetCode()] = $oExtField;
  734. }
  735. }
  736. }
  737. }
  738. // Add a 'id' filter
  739. //
  740. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  741. {
  742. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  743. }
  744. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  745. {
  746. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  747. }
  748. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  749. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  750. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  751. // Add a 'class' attribute/filter to the root classes and their children
  752. //
  753. if (!self::IsStandaloneClass($sClass))
  754. {
  755. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sClass]))
  756. {
  757. throw new CoreException("Class $sClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  758. }
  759. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sClass]))
  760. {
  761. throw new CoreException("Class $sClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  762. }
  763. $sClassAttCode = 'finalclass';
  764. $sRootClass = self::GetRootClass($sClass);
  765. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  766. $oClassAtt = new AttributeClass($sClassAttCode, array(
  767. "label"=>"Class",
  768. "description"=>"Real (final) object class",
  769. "class_category"=>null,
  770. "more_values"=>'',
  771. "sql"=>$sDbFinalClassField,
  772. "default_value"=>$sClass,
  773. "is_null_allowed"=>false,
  774. "depends_on"=>array()
  775. ));
  776. self::$m_aAttribDefs[$sClass][$sClassAttCode] = $oClassAtt;
  777. self::$m_aAttribOrigins[$sClass][$sClassAttCode] = $sRootClass;
  778. $oClassFlt = new FilterFromAttribute($oClassAtt);
  779. self::$m_aFilterDefs[$sClass][$sClassAttCode] = $oClassFlt;
  780. self::$m_aFilterOrigins[$sClass][$sClassAttCode] = self::GetRootClass($sClass);
  781. }
  782. // Define defaults values for the standard ZLists
  783. //
  784. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  785. //{
  786. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  787. // {
  788. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  789. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  790. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  791. // }
  792. //}
  793. }
  794. }
  795. // To be overriden, must be called for any object class (optimization)
  796. public static function Init()
  797. {
  798. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  799. }
  800. // To be overloaded by biz model declarations
  801. public static function GetRelationQueries($sRelCode)
  802. {
  803. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  804. return array();
  805. }
  806. public static function Init_Params($aParams)
  807. {
  808. // Check mandatory params
  809. $aMandatParams = array(
  810. "category" => "group classes by modules defining their visibility in the UI",
  811. "name" => "internal class name, may be different than the PHP class name",
  812. "description" => "detailed (though one line) description of the class",
  813. "key_type" => "autoincrement | string",
  814. "key_label" => "if set, then display the key as an attribute",
  815. "name_attcode" => "define wich attribute is the class name, may be an inherited attribute",
  816. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  817. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  818. "db_table" => "database table",
  819. "db_key_field" => "database field which is the key",
  820. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  821. );
  822. $sClass = self::GetCallersPHPClass("Init");
  823. if (!array_key_exists("name", $aParams))
  824. {
  825. throw new CoreException("Declaration of class $sClass: missing name ({$aMandatParams["name"]})");
  826. }
  827. foreach($aMandatParams as $sParamName=>$sParamDesc)
  828. {
  829. if (!array_key_exists($sParamName, $aParams))
  830. {
  831. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  832. }
  833. }
  834. $aCategories = explode(',', $aParams['category']);
  835. foreach ($aCategories as $sCategory)
  836. {
  837. self::$m_Category2Class[$sCategory][] = $sClass;
  838. }
  839. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  840. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  841. self::$m_aParentClasses[$sClass] = array();
  842. self::$m_aChildClasses[$sClass] = array();
  843. self::$m_aClassParams[$sClass]= $aParams;
  844. self::$m_aAttribDefs[$sClass] = array();
  845. self::$m_aAttribOrigins[$sClass] = array();
  846. self::$m_aExtKeyFriends[$sClass] = array();
  847. self::$m_aFilterDefs[$sClass] = array();
  848. self::$m_aFilterOrigins[$sClass] = array();
  849. }
  850. protected static function object_array_mergeclone($aSource1, $aSource2)
  851. {
  852. $aRes = array();
  853. foreach ($aSource1 as $key=>$object)
  854. {
  855. $aRes[$key] = clone $object;
  856. }
  857. foreach ($aSource2 as $key=>$object)
  858. {
  859. $aRes[$key] = clone $object;
  860. }
  861. return $aRes;
  862. }
  863. public static function Init_InheritAttributes($sSourceClass = null)
  864. {
  865. $sTargetClass = self::GetCallersPHPClass("Init");
  866. if (empty($sSourceClass))
  867. {
  868. // Default: inherit from parent class
  869. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  870. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  871. }
  872. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  873. {
  874. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  875. {
  876. self::$m_aAttribDefs[$sTargetClass] = array();
  877. self::$m_aAttribOrigins[$sTargetClass] = array();
  878. }
  879. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  880. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  881. }
  882. // later on, we might consider inheritance in different ways !!!
  883. //if (strlen(self::DBGetTable($sSourceClass)) != 0)
  884. if (self::HasFinalClassField(self::$m_aRootClasses[$sSourceClass]))
  885. {
  886. // Inherit the root class
  887. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  888. }
  889. else
  890. {
  891. // I am a root class, standalone as well !
  892. // ????
  893. //self::$m_aRootClasses[$sTargetClass] = $sTargetClass;
  894. }
  895. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  896. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  897. // I am the child of each and every parent...
  898. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  899. {
  900. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  901. }
  902. }
  903. public static function Init_OverloadAttributeParams($sAttCode, $aParams)
  904. {
  905. $sTargetClass = self::GetCallersPHPClass("Init");
  906. if (!self::IsValidAttCode($sTargetClass, $sAttCode))
  907. {
  908. throw new CoreException("Could not overload '$sAttCode', expecting a code from {".implode(", ", self::GetAttributesList($sTargetClass))."}");
  909. }
  910. self::$m_aAttribDefs[$sTargetClass][$sAttCode]->OverloadParams($aParams);
  911. }
  912. public static function Init_AddAttribute(AttributeDefinition $oAtt)
  913. {
  914. $sTargetClass = self::GetCallersPHPClass("Init");
  915. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  916. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  917. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  918. // Specific case of external fields:
  919. // I wanted to simplify the syntax of the declaration of objects in the biz model
  920. // Therefore, the reference to the host class is set there
  921. $oAtt->SetHostClass($sTargetClass);
  922. }
  923. public static function Init_InheritFilters($sSourceClass = null)
  924. {
  925. $sTargetClass = self::GetCallersPHPClass("Init");
  926. if (empty($sSourceClass))
  927. {
  928. // Default: inherit from parent class
  929. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  930. if (empty($sSourceClass)) return; // no filters for the mother of all classes
  931. }
  932. if (isset(self::$m_aFilterDefs[$sSourceClass]))
  933. {
  934. if (!isset(self::$m_aFilterDefs[$sTargetClass]))
  935. {
  936. self::$m_aFilterDefs[$sTargetClass] = array();
  937. self::$m_aFilterOrigins[$sTargetClass] = array();
  938. }
  939. foreach (self::$m_aFilterDefs[$sSourceClass] as $sFltCode=>$oFilter)
  940. {
  941. if ($oFilter instanceof FilterFromAttribute)
  942. {
  943. // In that case, cloning is not enough:
  944. // we must ensure that we will point to the correct
  945. // attribute definition (in case some properties are overloaded)
  946. $oAttDef1 = $oFilter->__GetRefAttribute();
  947. $oAttDef2 = self::GetAttributeDef($sTargetClass, $oAttDef1->GetCode());
  948. $oNewFilter = new FilterFromAttribute($oAttDef2);
  949. }
  950. else
  951. {
  952. $oNewFilter = clone $oFilter;
  953. }
  954. self::$m_aFilterDefs[$sTargetClass][$sFltCode] = $oNewFilter;
  955. }
  956. self::$m_aFilterOrigins[$sTargetClass] = array_merge(self::$m_aFilterOrigins[$sTargetClass], self::$m_aFilterOrigins[$sSourceClass]);
  957. }
  958. }
  959. public static function Init_OverloadFilterParams($sFltCode, $aParams)
  960. {
  961. $sTargetClass = self::GetCallersPHPClass("Init");
  962. if (!self::IsValidFilterCode($sTargetClass, $sFltCode))
  963. {
  964. throw new CoreException("Could not overload '$sFltCode', expecting a code from {".implode(", ", self::GetFiltersList($sTargetClass))."}");
  965. }
  966. self::$m_aFilterDefs[$sTargetClass][$sFltCode]->OverloadParams($aParams);
  967. }
  968. public static function Init_AddFilter(FilterDefinition $oFilter)
  969. {
  970. $sTargetClass = self::GetCallersPHPClass("Init");
  971. self::$m_aFilterDefs[$sTargetClass][$oFilter->GetCode()] = $oFilter;
  972. self::$m_aFilterOrigins[$sTargetClass][$oFilter->GetCode()] = $sTargetClass;
  973. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  974. }
  975. public static function Init_AddFilterFromAttribute($sAttCode)
  976. {
  977. $sTargetClass = self::GetCallersPHPClass("Init");
  978. $oAttDef = self::GetAttributeDef($sTargetClass, $sAttCode);
  979. $sFilterCode = $sAttCode;
  980. $oNewFilter = new FilterFromAttribute($oAttDef);
  981. self::$m_aFilterDefs[$sTargetClass][$sFilterCode] = $oNewFilter;
  982. if ($oAttDef->IsExternalField())
  983. {
  984. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  985. $oKeyDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  986. self::$m_aFilterOrigins[$sTargetClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  987. }
  988. else
  989. {
  990. self::$m_aFilterOrigins[$sTargetClass][$sFilterCode] = $sTargetClass;
  991. }
  992. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  993. }
  994. public static function Init_SetZListItems($sListCode, $aItems)
  995. {
  996. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  997. $sTargetClass = self::GetCallersPHPClass("Init");
  998. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  999. }
  1000. public static function Init_DefineState($sStateCode, $aStateDef)
  1001. {
  1002. $sTargetClass = self::GetCallersPHPClass("Init");
  1003. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  1004. $sParentState = $aStateDef['attribute_inherit'];
  1005. if (!empty($sParentState))
  1006. {
  1007. // Inherit from the given state (must be defined !)
  1008. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  1009. // The inherited configuration could be overriden
  1010. $aStateDef['attribute_list'] = array_merge($aToInherit, $aStateDef['attribute_list']);
  1011. }
  1012. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  1013. // by default, create an empty set of transitions associated to that state
  1014. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  1015. }
  1016. public static function Init_DefineStimulus($sStimulusCode, $oStimulus)
  1017. {
  1018. $sTargetClass = self::GetCallersPHPClass("Init");
  1019. self::$m_aStimuli[$sTargetClass][$sStimulusCode] = $oStimulus;
  1020. }
  1021. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  1022. {
  1023. $sTargetClass = self::GetCallersPHPClass("Init");
  1024. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  1025. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  1026. }
  1027. public static function Init_InheritLifecycle($sSourceClass = '')
  1028. {
  1029. $sTargetClass = self::GetCallersPHPClass("Init");
  1030. if (empty($sSourceClass))
  1031. {
  1032. // Default: inherit from parent class
  1033. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1034. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1035. }
  1036. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  1037. self::$m_aStates[$sTargetClass] = clone self::$m_aStates[$sSourceClass];
  1038. self::$m_aStimuli[$sTargetClass] = clone self::$m_aStimuli[$sSourceClass];
  1039. self::$m_aTransitions[$sTargetClass] = clone self::$m_aTransitions[$sSourceClass];
  1040. }
  1041. //
  1042. // Static API
  1043. //
  1044. public static function GetRootClass($sClass = null)
  1045. {
  1046. self::_check_subclass($sClass);
  1047. return self::$m_aRootClasses[$sClass];
  1048. }
  1049. public static function IsRootClass($sClass)
  1050. {
  1051. self::_check_subclass($sClass);
  1052. return (self::GetRootClass($sClass) == $sClass);
  1053. }
  1054. public static function EnumParentClasses($sClass)
  1055. {
  1056. self::_check_subclass($sClass);
  1057. return self::$m_aParentClasses[$sClass];
  1058. }
  1059. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  1060. {
  1061. self::_check_subclass($sClass);
  1062. $aRes = self::$m_aChildClasses[$sClass];
  1063. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  1064. {
  1065. // Add it to the list
  1066. $aRes[] = $sClass;
  1067. }
  1068. return $aRes;
  1069. }
  1070. public static function EnumCategories()
  1071. {
  1072. return array_keys(self::$m_Category2Class);
  1073. }
  1074. // Note: use EnumChildClasses to take the compound objects into account
  1075. public static function GetSubclasses($sClass)
  1076. {
  1077. self::_check_subclass($sClass);
  1078. $aSubClasses = array();
  1079. foreach(get_declared_classes() as $sSubClass) {
  1080. if (is_subclass_of($sSubClass, $sClass))
  1081. {
  1082. $aSubClasses[] = $sSubClass;
  1083. }
  1084. }
  1085. return $aSubClasses;
  1086. }
  1087. public static function GetClasses($sCategory = '')
  1088. {
  1089. if (array_key_exists($sCategory, self::$m_Category2Class))
  1090. {
  1091. return self::$m_Category2Class[$sCategory];
  1092. }
  1093. if (count(self::$m_Category2Class) > 0)
  1094. {
  1095. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  1096. }
  1097. return array();
  1098. }
  1099. public static function IsAbstract($sClass)
  1100. {
  1101. if (strlen(self::DBGetTable($sClass)) == 0) return true;
  1102. return false;
  1103. }
  1104. protected static $m_aQueryStructCache = array();
  1105. protected static function PrepareQueryArguments($aArgs)
  1106. {
  1107. // Translate any object into scalars
  1108. //
  1109. $aScalarArgs = array();
  1110. foreach($aArgs as $sArgName => $value)
  1111. {
  1112. if (self::IsValidObject($value))
  1113. {
  1114. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgs($sArgName));
  1115. }
  1116. else
  1117. {
  1118. $aScalarArgs[$sArgName] = (string) $value;
  1119. }
  1120. }
  1121. // Add standard contextual arguments
  1122. //
  1123. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1124. return $aScalarArgs;
  1125. }
  1126. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array())
  1127. {
  1128. // Query caching
  1129. //
  1130. $bQueryCacheEnabled = true;
  1131. $aParams = array();
  1132. $sOqlQuery = $oFilter->ToOql($aParams); // Render with arguments in clear
  1133. if ($bQueryCacheEnabled)
  1134. {
  1135. if (array_key_exists($sOqlQuery, self::$m_aQueryStructCache))
  1136. {
  1137. // hit!
  1138. $oSelect = clone self::$m_aQueryStructCache[$sOqlQuery];
  1139. }
  1140. }
  1141. if (!isset($oSelect))
  1142. {
  1143. $aTranslation = array();
  1144. $aClassAliases = array();
  1145. $aTableAliases = array();
  1146. $oConditionTree = $oFilter->GetCriteria();
  1147. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1148. self::$m_aQueryStructCache[$sOqlQuery] = clone $oSelect;
  1149. }
  1150. // Check the order by specification, and prefix with the class alias
  1151. //
  1152. $aOrderSpec = array();
  1153. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  1154. {
  1155. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sFieldAlias, self::GetAttributesList($oFilter->GetClass()));
  1156. if (!is_bool($bAscending))
  1157. {
  1158. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  1159. }
  1160. $aOrderSpec[$oFilter->GetClassAlias().$sFieldAlias] = $bAscending;
  1161. }
  1162. // By default, force the name attribute to be the ordering key
  1163. //
  1164. if (empty($aOrderSpec))
  1165. {
  1166. $sNameAttCode = self::GetNameAttributeCode($oFilter->GetClass());
  1167. if (!empty($sNameAttCode))
  1168. {
  1169. // By default, simply order on the "name" attribute, ascending
  1170. $aOrderSpec[$oFilter->GetClassAlias().$sNameAttCode] = true;
  1171. }
  1172. }
  1173. // Go
  1174. //
  1175. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1176. try
  1177. {
  1178. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs);
  1179. }
  1180. catch (MissingQueryArgument $e)
  1181. {
  1182. // Add some information...
  1183. $e->addInfo('OQL', $sOqlQuery);
  1184. throw $e;
  1185. }
  1186. if (self::$m_bTraceQueries)
  1187. {
  1188. $aParams = array();
  1189. if (!array_key_exists($sOqlQuery, self::$m_aQueriesLog))
  1190. {
  1191. self::$m_aQueriesLog[$sOqlQuery] = array(
  1192. 'sql' => array(),
  1193. 'count' => 0,
  1194. );
  1195. }
  1196. self::$m_aQueriesLog[$sOqlQuery]['count']++;
  1197. self::$m_aQueriesLog[$sOqlQuery]['sql'][] = $sRes;
  1198. }
  1199. return $sRes;
  1200. }
  1201. public static function ShowQueryTrace()
  1202. {
  1203. $iTotal = 0;
  1204. foreach (self::$m_aQueriesLog as $sOql => $aQueryData)
  1205. {
  1206. echo "<h2>$sOql</h2>\n";
  1207. $iTotal += $aQueryData['count'];
  1208. echo '<p>'.$aQueryData['count'].'</p>';
  1209. echo '<p>Example: '.$aQueryData['sql'][0].'</p>';
  1210. }
  1211. echo "<h2>Total</h2>\n";
  1212. echo "<p>Count of executed queries: $iTotal</p>";
  1213. echo "<p>Count of built queries: ".count(self::$m_aQueriesLog)."</p>";
  1214. }
  1215. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  1216. {
  1217. $aTranslation = array();
  1218. $aClassAliases = array();
  1219. $aTableAliases = array();
  1220. $oConditionTree = $oFilter->GetCriteria();
  1221. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1222. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1223. return $oSelect->RenderDelete($aScalarArgs);
  1224. }
  1225. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  1226. {
  1227. // $aValues is an array of $sAttCode => $value
  1228. $aTranslation = array();
  1229. $aClassAliases = array();
  1230. $aTableAliases = array();
  1231. $oConditionTree = $oFilter->GetCriteria();
  1232. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), $aValues);
  1233. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1234. return $oSelect->RenderUpdate($aScalarArgs);
  1235. }
  1236. private static function MakeQuery($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, DBObjectSearch $oFilter, $aExpectedAtts = array(), $aValues = array())
  1237. {
  1238. // Note: query class might be different than the class of the filter
  1239. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1240. // $aExpectedAtts is an array of sAttCode=>array of columns
  1241. $sClass = $oFilter->GetClass();
  1242. $sClassAlias = $oFilter->GetClassAlias();
  1243. $bIsOnQueriedClass = array_key_exists($sClassAlias, $aSelectedClasses);
  1244. if ($bIsOnQueriedClass)
  1245. {
  1246. $aClassAliases = array_merge($aClassAliases, $oFilter->GetJoinedClasses());
  1247. }
  1248. self::DbgTrace("Entering: ".$oFilter->ToSibuSQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1249. $sRootClass = self::GetRootClass($sClass);
  1250. $sKeyField = self::DBGetKey($sClass);
  1251. if ($bIsOnQueriedClass)
  1252. {
  1253. // default to the whole list of attributes + the very std id/finalclass
  1254. $aExpectedAtts['id'][] = $sClassAlias.'id';
  1255. foreach (self::GetAttributesList($sClass) as $sAttCode)
  1256. {
  1257. $aExpectedAtts[$sAttCode][] = $sClassAlias.$sAttCode; // alias == class and attcode
  1258. }
  1259. }
  1260. // Compute a clear view of external keys, and external attributes
  1261. // Build the list of external keys:
  1262. // -> ext keys required by a closed join ???
  1263. // -> ext keys mentionned in a 'pointing to' condition
  1264. // -> ext keys required for an external field
  1265. //
  1266. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1267. //
  1268. // Optimization: could be computed once for all (cached)
  1269. // Could be done in MakeQuerySingleTable ???
  1270. //
  1271. if ($bIsOnQueriedClass)
  1272. {
  1273. // Get all Ext keys for the queried class (??)
  1274. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  1275. {
  1276. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1277. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1278. }
  1279. }
  1280. // Get all Ext keys used by the filter
  1281. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $trash)
  1282. {
  1283. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1284. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1285. }
  1286. // Add the ext fields used in the select (eventually adds an external key)
  1287. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1288. {
  1289. if ($oAttDef->IsExternalField())
  1290. {
  1291. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1292. if (array_key_exists($sAttCode, $aExpectedAtts) || $oConditionTree->RequiresField($sClassAlias, $sAttCode))
  1293. {
  1294. // Add the external attribute
  1295. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1296. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1297. }
  1298. }
  1299. }
  1300. // First query built upon on the leaf (ie current) class
  1301. //
  1302. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  1303. $oSelectBase = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sClass, $aExpectedAtts, $aExtKeys, $aValues);
  1304. // Then we join the queries of the eventual parent classes (compound model)
  1305. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  1306. {
  1307. if (self::DBGetTable($sParentClass) == "") continue;
  1308. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  1309. $oSelectParentTable = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sParentClass, $aExpectedAtts, $aExtKeys, $aValues);
  1310. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  1311. }
  1312. // Filter on objects referencing me
  1313. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1314. {
  1315. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1316. {
  1317. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1318. // We don't want any attribute from the foreign class, just filter on an inner join
  1319. $aExpAtts = array();
  1320. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  1321. //self::DbgTrace($oForeignFilter);
  1322. //self::DbgTrace($oForeignFilter->ToSibuSQL());
  1323. //self::DbgTrace($oSelectForeign);
  1324. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1325. $oSelectForeign = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oForeignFilter, $aExpAtts);
  1326. $sForeignClassAlias = $oForeignFilter->GetClassAlias();
  1327. $sForeignKeyTable = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][0];
  1328. $sForeignKeyColumn = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][1];
  1329. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1330. }
  1331. }
  1332. // Filter on related objects
  1333. //
  1334. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  1335. {
  1336. $oSubFilter = $aCritInfo['flt'];
  1337. $sRelCode = $aCritInfo['relcode'];
  1338. $iMaxDepth = $aCritInfo['maxdepth'];
  1339. // Get the starting point objects
  1340. $oStartSet = new CMDBObjectSet($oSubFilter);
  1341. // Get the objects related to those objects... recursively...
  1342. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  1343. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  1344. // #@# todo - related objects and expressions...
  1345. // Create condition
  1346. if (count($aRestriction) > 0)
  1347. {
  1348. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  1349. }
  1350. else
  1351. {
  1352. // Quick N'dirty -> generate an empty set
  1353. $oSelectBase->AddCondition('false');
  1354. }
  1355. }
  1356. // Translate the conditions... and go
  1357. //
  1358. if ($bIsOnQueriedClass)
  1359. {
  1360. $oConditionTranslated = $oConditionTree->Translate($aTranslation);
  1361. $oSelectBase->SetCondition($oConditionTranslated);
  1362. }
  1363. // That's all... cross fingers and we'll get some working query
  1364. //MyHelpers::var_dump_html($oSelectBase, true);
  1365. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1366. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1367. return $oSelectBase;
  1368. }
  1369. protected static function MakeQuerySingleTable($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, $oFilter, $sTableClass, $aExpectedAtts, $aExtKeys, $aValues)
  1370. {
  1371. // $aExpectedAtts is an array of sAttCode=>sAlias
  1372. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1373. // Prepare the query for a single table (compound objects)
  1374. // Ignores the items (attributes/filters) that are not on the target table
  1375. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1376. //
  1377. // Returns an SQLQuery
  1378. //
  1379. $sTargetClass = $oFilter->GetClass();
  1380. $sTargetAlias = $oFilter->GetClassAlias();
  1381. $sTable = self::DBGetTable($sTableClass);
  1382. $sTableAlias = self::GenerateUniqueAlias($aTableAliases, $sTargetAlias.'_'.$sTable, $sTable);
  1383. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $aSelectedClasses);
  1384. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToSibuSQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1385. // 1 - SELECT and UPDATE
  1386. //
  1387. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1388. //
  1389. $aSelect = array();
  1390. $aUpdateValues = array();
  1391. // 1/a - Get the key
  1392. //
  1393. if ($bIsOnQueriedClass)
  1394. {
  1395. $aSelect[$aExpectedAtts['id'][0]] = new FieldExpression(self::DBGetKey($sTableClass), $sTableAlias);
  1396. }
  1397. // We need one pkey to be the key, let's take the one corresponding to the leaf
  1398. if ($sTableClass == $sTargetClass)
  1399. {
  1400. $aTranslation[$sTargetAlias]['id'] = array($sTableAlias, self::DBGetKey($sTableClass));
  1401. }
  1402. // 1/b - Get the other attributes
  1403. //
  1404. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1405. {
  1406. // Skip this attribute if not defined in this table
  1407. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  1408. // Skip this attribute if not writable (means that it does not correspond
  1409. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1410. // Update...
  1411. //
  1412. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1413. {
  1414. assert ($oAttDef->IsDirectField());
  1415. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1416. {
  1417. $aUpdateValues[$sColumn] = $sValue;
  1418. }
  1419. }
  1420. // Select...
  1421. //
  1422. // Skip, if a list of fields has been specified and it is not there
  1423. if (!array_key_exists($sAttCode, $aExpectedAtts)) continue;
  1424. if ($oAttDef->IsExternalField())
  1425. {
  1426. // skip, this will be handled in the joined tables
  1427. }
  1428. else
  1429. {
  1430. // standard field, or external key
  1431. // add it to the output
  1432. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1433. {
  1434. foreach ($aExpectedAtts[$sAttCode] as $sAttAlias)
  1435. {
  1436. $aSelect[$sAttAlias.$sColId] = new FieldExpression($sSQLExpr, $sTableAlias);
  1437. }
  1438. }
  1439. }
  1440. }
  1441. // 2 - WHERE
  1442. //
  1443. foreach(self::$m_aFilterDefs[$sTargetClass] as $sFltCode => $oFltAtt)
  1444. {
  1445. // Skip this filter if not defined in this table
  1446. if (self::$m_aFilterOrigins[$sTargetClass][$sFltCode] != $sTableClass) continue;
  1447. // #@# todo - aller plus loin... a savoir que la table de translation doit contenir une "Expression"
  1448. foreach($oFltAtt->GetSQLExpressions() as $sColID => $sFltExpr)
  1449. {
  1450. // Note: I did not test it with filters relying on several expressions...
  1451. // as long as sColdID is empty, this is working, otherwise... ?
  1452. $aTranslation[$sTargetAlias][$sFltCode.$sColID] = array($sTableAlias, $sFltExpr);
  1453. }
  1454. }
  1455. // #@# todo - See what a full text search condition should be
  1456. // 2' - WHERE / Full text search condition
  1457. //
  1458. if ($bIsOnQueriedClass)
  1459. {
  1460. $aFullText = $oFilter->GetCriteria_FullText();
  1461. }
  1462. else
  1463. {
  1464. // Pourquoi ???
  1465. $aFullText = array();
  1466. }
  1467. // 3 - The whole stuff, for this table only
  1468. //
  1469. $oSelectBase = new SQLQuery($sTable, $sTableAlias, $aSelect, null, $aFullText, $bIsOnQueriedClass, $aUpdateValues);
  1470. // 4 - The external keys -> joins...
  1471. //
  1472. if (array_key_exists($sTableClass, $aExtKeys))
  1473. {
  1474. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1475. {
  1476. $oKeyAttDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  1477. $oExtFilter = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  1478. // In case the join was not explicitely defined in the filter,
  1479. // we need to do it now
  1480. if (empty($oExtFilter))
  1481. {
  1482. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1483. $sKeyClassAlias = self::GenerateUniqueAlias($aClassAliases, $sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1484. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1485. }
  1486. else
  1487. {
  1488. // The aliases should not conflict because normalization occured while building the filter
  1489. $sKeyClass = $oExtFilter->GetClass();
  1490. $sKeyClassAlias = $oExtFilter->GetClassAlias();
  1491. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1492. }
  1493. // Specify expected attributes for the target class query
  1494. // ... and use the current alias !
  1495. $aExpAtts = array();
  1496. $aIntermediateTranslation = array();
  1497. foreach($aExtFields as $sAttCode => $oAtt)
  1498. {
  1499. $sExtAttCode = $oAtt->GetExtAttCode();
  1500. if (array_key_exists($sAttCode, $aExpectedAtts))
  1501. {
  1502. // Request this attribute... transmit the alias !
  1503. $aExpAtts[$sExtAttCode] = $aExpectedAtts[$sAttCode];
  1504. }
  1505. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1506. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  1507. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  1508. {
  1509. $aIntermediateTranslation[$sTargetAlias.$sColID][$sAttCode] = array($sKeyClassAlias, $sRemoteAttExpr);
  1510. }
  1511. //#@# debug - echo "<p>$sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</p>\n";
  1512. }
  1513. $oConditionTree = $oConditionTree->Translate($aIntermediateTranslation, false);
  1514. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  1515. $oSelectExtKey = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oExtFilter, $aExpAtts);
  1516. $sLocalKeyField = current($oKeyAttDef->GetSQLExpressions()); // get the first column for an external key
  1517. $sExternalKeyField = self::DBGetKey($sKeyClass);
  1518. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1519. if ($oKeyAttDef->IsNullAllowed())
  1520. {
  1521. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1522. }
  1523. else
  1524. {
  1525. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1526. }
  1527. }
  1528. }
  1529. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  1530. return $oSelectBase;
  1531. }
  1532. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  1533. {
  1534. if (!array_key_exists($sNewName, $aAliases))
  1535. {
  1536. $aAliases[$sNewName] = $sRealName;
  1537. return $sNewName;
  1538. }
  1539. for ($i = 1 ; $i < 100 ; $i++)
  1540. {
  1541. $sAnAlias = $sNewName.$i;
  1542. if (!array_key_exists($sAnAlias, $aAliases))
  1543. {
  1544. // Create that new alias
  1545. $aAliases[$sAnAlias] = $sRealName;
  1546. return $sAnAlias;
  1547. }
  1548. }
  1549. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  1550. }
  1551. public static function CheckDefinitions()
  1552. {
  1553. if (count(self::GetClasses()) == 0)
  1554. {
  1555. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  1556. }
  1557. $aErrors = array();
  1558. $aSugFix = array();
  1559. foreach (self::GetClasses() as $sClass)
  1560. {
  1561. if (self::IsAbstract($sClass)) continue;
  1562. $sNameAttCode = self::GetNameAttributeCode($sClass);
  1563. if (empty($sNameAttCode))
  1564. {
  1565. // let's try this !!!
  1566. // $aErrors[$sClass][] = "Missing value for name definition: the framework will (should...) replace it by the id";
  1567. // $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1568. }
  1569. else if(!self::IsValidAttCode($sClass, $sNameAttCode))
  1570. {
  1571. $aErrors[$sClass][] = "Unkown attribute code '".$sNameAttCode."' for the name definition";
  1572. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1573. }
  1574. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  1575. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  1576. {
  1577. $aErrors[$sClass][] = "Unkown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  1578. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1579. }
  1580. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1581. {
  1582. // It makes no sense to check the attributes again and again in the subclasses
  1583. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1584. if ($oAttDef->IsExternalKey())
  1585. {
  1586. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  1587. {
  1588. $aErrors[$sClass][] = "Unkown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  1589. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  1590. }
  1591. }
  1592. elseif ($oAttDef->IsExternalField())
  1593. {
  1594. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1595. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  1596. {
  1597. $aErrors[$sClass][] = "Unkown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  1598. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  1599. }
  1600. else
  1601. {
  1602. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1603. $sTargetClass = $oKeyAttDef->GetTargetClass();
  1604. $sExtAttCode = $oAttDef->GetExtAttCode();
  1605. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  1606. {
  1607. $aErrors[$sClass][] = "Unkown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  1608. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  1609. }
  1610. }
  1611. }
  1612. else // standard attributes
  1613. {
  1614. // Check that the default values definition is a valid object!
  1615. $oValSetDef = $oAttDef->GetValuesDef();
  1616. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  1617. {
  1618. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  1619. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  1620. }
  1621. else
  1622. {
  1623. // Default value must be listed in the allowed values (if defined)
  1624. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  1625. if (!is_null($aAllowedValues))
  1626. {
  1627. $sDefaultValue = $oAttDef->GetDefaultValue();
  1628. if (!array_key_exists($sDefaultValue, $aAllowedValues))
  1629. {
  1630. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  1631. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  1632. }
  1633. }
  1634. }
  1635. }
  1636. // Check dependencies
  1637. if ($oAttDef->IsWritable())
  1638. {
  1639. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  1640. {
  1641. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  1642. {
  1643. $aErrors[$sClass][] = "Unkown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  1644. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1645. }
  1646. }
  1647. }
  1648. }
  1649. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  1650. {
  1651. if (method_exists($oFilterDef, '__GetRefAttribute'))
  1652. {
  1653. $oAttDef = $oFilterDef->__GetRefAttribute();
  1654. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  1655. {
  1656. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  1657. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1658. }
  1659. }
  1660. }
  1661. // Lifecycle
  1662. //
  1663. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1664. if (strlen($sStateAttCode) > 0)
  1665. {
  1666. // Lifecycle - check that the state attribute does exist as an attribute
  1667. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  1668. {
  1669. $aErrors[$sClass][] = "Unkown attribute code '".$sStateAttCode."' for the state definition";
  1670. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1671. }
  1672. else
  1673. {
  1674. // Lifecycle - check that there is a value set constraint on the state attribute
  1675. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  1676. $aStates = array_keys(self::EnumStates($sClass));
  1677. if (is_null($aAllowedValuesRaw))
  1678. {
  1679. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  1680. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  1681. }
  1682. else
  1683. {
  1684. $aAllowedValues = array_keys($aAllowedValuesRaw);
  1685. // Lifecycle - check the the state attribute allowed values are defined states
  1686. foreach($aAllowedValues as $sValue)
  1687. {
  1688. if (!in_array($sValue, $aStates))
  1689. {
  1690. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  1691. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1692. }
  1693. }
  1694. // Lifecycle - check that defined states are allowed values
  1695. foreach($aStates as $sStateValue)
  1696. {
  1697. if (!in_array($sStateValue, $aAllowedValues))
  1698. {
  1699. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  1700. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1701. }
  1702. }
  1703. }
  1704. // Lifcycle - check that the action handlers are defined
  1705. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  1706. {
  1707. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  1708. {
  1709. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1710. {
  1711. if (!method_exists($sClass, $sActionHandler))
  1712. {
  1713. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  1714. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  1715. }
  1716. }
  1717. }
  1718. }
  1719. }
  1720. }
  1721. // ZList
  1722. //
  1723. foreach(self::EnumZLists() as $sListCode)
  1724. {
  1725. foreach (self::GetZListItems($sClass, $sListCode) as $sMyAttCode)
  1726. {
  1727. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  1728. {
  1729. $aErrors[$sClass][] = "Unkown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  1730. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1731. }
  1732. }
  1733. }
  1734. }
  1735. if (count($aErrors) > 0)
  1736. {
  1737. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  1738. echo "<h3>Business model inconsistencies have been found</h3>\n";
  1739. // #@# later -> this is the responsibility of the caller to format the output
  1740. foreach ($aErrors as $sClass => $aMessages)
  1741. {
  1742. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  1743. echo "<ul class=\"treeview\">\n";
  1744. $i = 0;
  1745. foreach ($aMessages as $sMsg)
  1746. {
  1747. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  1748. $i++;
  1749. }
  1750. echo "</ul>\n";
  1751. }
  1752. echo "<p>Aborting...</p>\n";
  1753. echo "</div>\n";
  1754. exit;
  1755. }
  1756. }
  1757. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  1758. {
  1759. if (empty($sRepairUrl)) return;
  1760. if (count($aSQLFixes) == 0) return;
  1761. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  1762. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aSQLFixes))."\">\n";
  1763. echo " <input type=\"submit\" value=\" Apply the changes (".count($aSQLFixes)." queries) \">\n";
  1764. echo "</form>\n";
  1765. }
  1766. public static function DBExists($bMustBeComplete = true)
  1767. {
  1768. // returns true if at least one table exists
  1769. //
  1770. if (!CMDBSource::IsDB(self::$m_sDBName))
  1771. {
  1772. return false;
  1773. }
  1774. CMDBSource::SelectDB(self::$m_sDBName);
  1775. $aFound = array();
  1776. $aMissing = array();
  1777. foreach (self::DBEnumTables() as $sTable => $aClasses)
  1778. {
  1779. if (CMDBSource::IsTable($sTable))
  1780. {
  1781. $aFound[] = $sTable;
  1782. }
  1783. else
  1784. {
  1785. $aMissing[] = $sTable;
  1786. }
  1787. }
  1788. if (count($aFound) == 0)
  1789. {
  1790. // no expected table has been found
  1791. return false;
  1792. }
  1793. else
  1794. {
  1795. if (count($aMissing) == 0)
  1796. {
  1797. // the database is complete (still, could be some fields missing!)
  1798. return true;
  1799. }
  1800. else
  1801. {
  1802. // not all the tables, could be an older version
  1803. if ($bMustBeComplete)
  1804. {
  1805. return false;
  1806. }
  1807. else
  1808. {
  1809. return true;
  1810. }
  1811. }
  1812. }
  1813. }
  1814. public static function DBDrop()
  1815. {
  1816. $bDropEntireDB = true;
  1817. if (!empty(self::$m_sTablePrefix))
  1818. {
  1819. // Do drop only tables corresponding to the sub-database (table prefix)
  1820. // then possibly drop the DB itself (if no table remain)
  1821. foreach (CMDBSource::EnumTables() as $sTable)
  1822. {
  1823. // perform a case insensitive test because on Windows the table names become lowercase :-(
  1824. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  1825. {
  1826. CMDBSource::DropTable($sTable);
  1827. }
  1828. else
  1829. {
  1830. // There is at least one table which is out of the scope of the current application
  1831. $bDropEntireDB = false;
  1832. }
  1833. }
  1834. }
  1835. if ($bDropEntireDB)
  1836. {
  1837. CMDBSource::DropDB(self::$m_sDBName);
  1838. }
  1839. }
  1840. public static function DBCreate()
  1841. {
  1842. // Note: we have to check if the DB does exist, because we may share the DB
  1843. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  1844. if (!CMDBSource::IsDB(self::$m_sDBName))
  1845. {
  1846. CMDBSource::CreateDB(self::$m_sDBName);
  1847. }
  1848. self::DBCreateTables();
  1849. }
  1850. protected static function DBCreateTables()
  1851. {
  1852. list($aErrors, $aSugFix) = self::DBCheckFormat();
  1853. $aSQL = array();
  1854. foreach ($aSugFix as $sClass => $aTarget)
  1855. {
  1856. foreach ($aTarget as $aQueries)
  1857. {
  1858. foreach ($aQueries as $sQuery)
  1859. {
  1860. //$aSQL[] = $sQuery;
  1861. // forces a refresh of cached information
  1862. CMDBSource::CreateTable($sQuery);
  1863. }
  1864. }
  1865. }
  1866. // does not work -how to have multiple statements in a single query?
  1867. // $sDoCreateAll = implode(" ; ", $aSQL);
  1868. }
  1869. public static function DBDump()
  1870. {
  1871. $aDataDump = array();
  1872. foreach (self::DBEnumTables() as $sTable => $aClasses)
  1873. {
  1874. $aRows = CMDBSource::DumpTable($sTable);
  1875. $aDataDump[$sTable] = $aRows;
  1876. }
  1877. return $aDataDump;
  1878. }
  1879. public static function DBCheckFormat()
  1880. {
  1881. $aErrors = array();
  1882. $aSugFix = array();
  1883. foreach (self::GetClasses() as $sClass)
  1884. {
  1885. if (self::IsAbstract($sClass)) continue;
  1886. // Check that the table exists
  1887. //
  1888. $sTable = self::DBGetTable($sClass);
  1889. $sKeyField = self::DBGetKey($sClass);
  1890. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  1891. if (!CMDBSource::IsTable($sTable))
  1892. {
  1893. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  1894. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` (`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY) ENGINE = innodb CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  1895. }
  1896. // Check that the key field exists
  1897. //
  1898. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  1899. {
  1900. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  1901. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD `$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  1902. }
  1903. else
  1904. {
  1905. // Check the key field properties
  1906. //
  1907. if (!CMDBSource::IsKey($sTable, $sKeyField))
  1908. {
  1909. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  1910. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  1911. }
  1912. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  1913. {
  1914. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  1915. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` `$sKeyField` INT(11) NOT NULL AUTO_INCREMENT";
  1916. }
  1917. }
  1918. // Check that any defined field exists
  1919. //
  1920. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  1921. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1922. {
  1923. // Skip this attribute if not originaly defined in this class
  1924. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1925. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  1926. {
  1927. $sFieldSpecs = $oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL";
  1928. if (!CMDBSource::IsField($sTable, $sField))
  1929. {
  1930. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  1931. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD `$sField` $sFieldSpecs";
  1932. if ($oAttDef->IsExternalKey())
  1933. {
  1934. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  1935. }
  1936. }
  1937. else
  1938. {
  1939. // The field already exists, does it have the relevant properties?
  1940. //
  1941. $bToBeChanged = false;
  1942. if ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  1943. {
  1944. $bToBeChanged = true;
  1945. if ($oAttDef->IsNullAllowed())
  1946. {
  1947. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could be NULL";
  1948. }
  1949. else
  1950. {
  1951. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could NOT be NULL";
  1952. }
  1953. }
  1954. $sActualFieldType = CMDBSource::GetFieldType($sTable, $sField);
  1955. if (strcasecmp($sDBFieldType, $sActualFieldType) != 0)
  1956. {
  1957. $bToBeChanged = true;
  1958. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldType' while expecting '$sDBFieldType'";
  1959. }
  1960. if ($bToBeChanged)
  1961. {
  1962. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` `$sField` $sFieldSpecs";
  1963. }
  1964. // Create indexes (external keys only... so far)
  1965. //
  1966. if ($oAttDef->IsExternalKey() && !CMDBSource::HasIndex($sTable, $sField))
  1967. {
  1968. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  1969. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  1970. }
  1971. }
  1972. }
  1973. }
  1974. }
  1975. return array($aErrors, $aSugFix);
  1976. }
  1977. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  1978. {
  1979. $sRootClass = self::GetRootClass($sClass);
  1980. $sTable = self::DBGetTable($sClass);
  1981. $sKeyField = self::DBGetKey($sClass);
  1982. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  1983. {
  1984. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  1985. }
  1986. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  1987. if (count($aWrongRecords) == 0) return;
  1988. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  1989. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  1990. foreach ($aWrongRecords as $iRecordId)
  1991. {
  1992. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  1993. {
  1994. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  1995. {
  1996. case 'Delete':
  1997. // Already planned for a deletion
  1998. // Let's concatenate the errors description together
  1999. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2000. break;
  2001. case 'Update':
  2002. // Let's plan a deletion
  2003. break;
  2004. }
  2005. }
  2006. else
  2007. {
  2008. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2009. }
  2010. if (!$bProcessingFriends)
  2011. {
  2012. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  2013. {
  2014. // Something new to be deleted...
  2015. $iNewDelCount++;
  2016. }
  2017. }
  2018. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  2019. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  2020. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2021. $aPlannedDel[$sTable][] = $iRecordId;
  2022. }
  2023. // Now make sure that we would delete the records of the other tables for that class
  2024. //
  2025. if (!$bProcessingFriends)
  2026. {
  2027. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  2028. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  2029. {
  2030. $sFriendTable = self::DBGetTable($sFriendClass);
  2031. $sFriendKey = self::DBGetKey($sFriendClass);
  2032. // skip the current table
  2033. if ($sFriendTable == $sTable) continue;
  2034. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  2035. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  2036. }
  2037. }
  2038. }
  2039. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2040. {
  2041. $sRootClass = self::GetRootClass($sClass);
  2042. $sTable = self::DBGetTable($sClass);
  2043. $sKeyField = self::DBGetKey($sClass);
  2044. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2045. {
  2046. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2047. }
  2048. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2049. if (count($aWrongRecords) == 0) return;
  2050. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2051. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2052. foreach ($aWrongRecords as $iRecordId)
  2053. {
  2054. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2055. {
  2056. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2057. {
  2058. case 'Delete':
  2059. // No need to update, the record will be deleted!
  2060. break;
  2061. case 'Update':
  2062. // Already planned for an update
  2063. // Add this new update spec to the list
  2064. $bFoundSameSpec = false;
  2065. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  2066. {
  2067. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  2068. {
  2069. $bFoundSameSpec = true;
  2070. }
  2071. }
  2072. if (!$bFoundSameSpec)
  2073. {
  2074. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2075. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2076. }
  2077. break;
  2078. }
  2079. }
  2080. else
  2081. {
  2082. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2083. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  2084. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2085. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2086. }
  2087. }
  2088. }
  2089. // returns the count of records found for deletion
  2090. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2091. {
  2092. foreach (self::GetClasses() as $sClass)
  2093. {
  2094. if (self::IsAbstract($sClass)) continue;
  2095. $sRootClass = self::GetRootClass($sClass);
  2096. $sTable = self::DBGetTable($sClass);
  2097. $sKeyField = self::DBGetKey($sClass);
  2098. // Check that the final class field contains the name of a class which inherited from the current class
  2099. //
  2100. if (self::HasFinalClassField($sClass))
  2101. {
  2102. $sFinalClassField = self::DBGetClassField($sClass);
  2103. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2104. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  2105. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  2106. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2107. }
  2108. // Compound objects model - node/leaf classes (not the root itself)
  2109. //
  2110. if (!self::IsStandaloneClass($sClass) && !self::HasFinalClassField($sClass))
  2111. {
  2112. $sRootTable = self::DBGetTable($sRootClass);
  2113. $sRootKey = self::DBGetKey($sRootClass);
  2114. $sFinalClassField = self::DBGetClassField($sRootClass);
  2115. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2116. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  2117. // Check that any record found here has its counterpart in the root table
  2118. // and which refers to a child class
  2119. //
  2120. $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";
  2121. 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);
  2122. // Check that any record found in the root table and referring to a child class
  2123. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  2124. //
  2125. $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)";
  2126. 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);
  2127. }
  2128. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2129. {
  2130. // Skip this attribute if not defined in this table
  2131. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2132. if ($oAttDef->IsExternalKey())
  2133. {
  2134. // Check that any external field is pointing to an existing object
  2135. //
  2136. $sRemoteClass = $oAttDef->GetTargetClass();
  2137. $sRemoteTable = self::DBGetTable($sRemoteClass);
  2138. $sRemoteKey = self::DBGetKey($sRemoteClass);
  2139. $sExtKeyField = current($oAttDef->GetSQLExpressions()); // get the first column for an external key
  2140. // Note: a class/table may have an external key on itself
  2141. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  2142. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  2143. if ($oAttDef->IsNullAllowed())
  2144. {
  2145. // Exclude the records pointing to 0/null from the errors
  2146. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2147. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2148. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2149. }
  2150. else
  2151. {
  2152. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2153. }
  2154. // Do almost the same, taking into account the records planned for deletion
  2155. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  2156. {
  2157. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  2158. // but in that case you won't be able to track the root cause (cascading)
  2159. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  2160. if ($oAttDef->IsNullAllowed())
  2161. {
  2162. // Exclude the records pointing to 0/null from the errors
  2163. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2164. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2165. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2166. }
  2167. else
  2168. {
  2169. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2170. }
  2171. }
  2172. }
  2173. else if ($oAttDef->IsDirectField())
  2174. {
  2175. // Check that the values fit the allowed values
  2176. //
  2177. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2178. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  2179. {
  2180. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  2181. $sMyAttributeField = current($oAttDef->GetSQLExpressions()); // get the first column for the moment
  2182. $sDefaultValue = $oAttDef->GetDefaultValue();
  2183. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  2184. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2185. }
  2186. }
  2187. }
  2188. }
  2189. }
  2190. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  2191. {
  2192. // Records in error, and action to be taken: delete or update
  2193. // by RootClass/Table/Record
  2194. $aErrorsAndFixes = array();
  2195. // Records to be ignored in the current/next pass
  2196. // by Table = array of RecordId
  2197. $aPlannedDel = array();
  2198. // Count of errors in the next pass: no error means that we can leave...
  2199. $iErrorCount = 0;
  2200. // Limit in case of a bug in the algorythm
  2201. $iLoopCount = 0;
  2202. $iNewDelCount = 1; // startup...
  2203. while ($iNewDelCount > 0)
  2204. {
  2205. $iNewDelCount = 0;
  2206. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2207. $iErrorCount += $iNewDelCount;
  2208. // Safety net #1 - limit the planned deletions
  2209. //
  2210. $iMaxDel = 1000;
  2211. $iPlannedDel = 0;
  2212. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  2213. {
  2214. $iPlannedDel += count($aPlannedDelOnTable);
  2215. }
  2216. if ($iPlannedDel > $iMaxDel)
  2217. {
  2218. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  2219. break;
  2220. }
  2221. // Safety net #2 - limit the iterations
  2222. //
  2223. $iLoopCount++;
  2224. $iMaxLoops = 10;
  2225. if ($iLoopCount > $iMaxLoops)
  2226. {
  2227. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  2228. break;
  2229. }
  2230. }
  2231. // Display the results
  2232. //
  2233. $iIssueCount = 0;
  2234. $aFixesDelete = array();
  2235. $aFixesUpdate = array();
  2236. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  2237. {
  2238. foreach ($aTables as $sTable => $aRecords)
  2239. {
  2240. foreach ($aRecords as $iRecord => $aError)
  2241. {
  2242. $sAction = $aError['Action'];
  2243. $sReason = $aError['Reason'];
  2244. $iPass = $aError['Pass'];
  2245. switch ($sAction)
  2246. {
  2247. case 'Delete':
  2248. $sActionDetails = "";
  2249. $aFixesDelete[$sTable][] = $iRecord;
  2250. break;
  2251. case 'Update':
  2252. $aUpdateDesc = array();
  2253. foreach($aError['Action_Details'] as $aUpdateSpec)
  2254. {
  2255. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  2256. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  2257. }
  2258. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  2259. break;
  2260. default:
  2261. $sActionDetails = "bug: unknown action '$sAction'";
  2262. }
  2263. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  2264. $iIssueCount++;
  2265. }
  2266. }
  2267. }
  2268. if ($iIssueCount > 0)
  2269. {
  2270. // Build the queries to fix in the database
  2271. //
  2272. // First step, be able to get class data out of the table name
  2273. // Could be optimized, because we've made the job earlier... but few benefits, so...
  2274. $aTable2ClassProp = array();
  2275. foreach (self::GetClasses() as $sClass)
  2276. {
  2277. if (self::IsAbstract($sClass)) continue;
  2278. $sRootClass = self::GetRootClass($sClass);
  2279. $sTable = self::DBGetTable($sClass);
  2280. $sKeyField = self::DBGetKey($sClass);
  2281. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2282. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  2283. }
  2284. // Second step, build a flat list of SQL queries
  2285. $aSQLFixes = array();
  2286. $iPlannedUpdate = 0;
  2287. foreach ($aFixesUpdate as $sTable => $aColumns)
  2288. {
  2289. foreach ($aColumns as $sColumn => $aNewValues)
  2290. {
  2291. foreach ($aNewValues as $sNewValue => $aRecords)
  2292. {
  2293. $iPlannedUpdate += count($aRecords);
  2294. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2295. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2296. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  2297. }
  2298. }
  2299. }
  2300. $iPlannedDel = 0;
  2301. foreach ($aFixesDelete as $sTable => $aRecords)
  2302. {
  2303. $iPlannedDel += count($aRecords);
  2304. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2305. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2306. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  2307. }
  2308. // Report the results
  2309. //
  2310. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2311. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  2312. // #@# later -> this is the responsibility of the caller to format the output
  2313. echo "<ul class=\"treeview\">\n";
  2314. foreach ($aIssues as $sIssueDesc)
  2315. {
  2316. echo "<li>$sIssueDesc</li>\n";
  2317. }
  2318. echo "</ul>\n";
  2319. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  2320. echo "<p>Aborting...</p>\n";
  2321. echo "</div>\n";
  2322. exit;
  2323. }
  2324. }
  2325. public static function Startup($sConfigFile, $bAllowMissingDB = false)
  2326. {
  2327. self::LoadConfig($sConfigFile);
  2328. if (self::DBExists())
  2329. {
  2330. CMDBSource::SelectDB(self::$m_sDBName);
  2331. // Some of the init could not be done earlier (requiring classes to be declared and DB to be accessible)
  2332. self::InitPlugins();
  2333. }
  2334. else
  2335. {
  2336. if (!$bAllowMissingDB)
  2337. {
  2338. throw new CoreException('Database not found, check your configuration file', array('config_file'=>$sConfigFile, 'db_name'=>self::$m_sDBName));
  2339. }
  2340. }
  2341. }
  2342. public static function LoadConfig($sConfigFile)
  2343. {
  2344. $oConfig = new Config($sConfigFile);
  2345. foreach ($oConfig->GetAppModules() as $sModule => $sToInclude)
  2346. {
  2347. self::Plugin($sConfigFile, 'application', $sToInclude);
  2348. }
  2349. foreach ($oConfig->GetDataModels() as $sModule => $sToInclude)
  2350. {
  2351. self::Plugin($sConfigFile, 'business', $sToInclude);
  2352. }
  2353. foreach ($oConfig->GetAddons() as $sModule => $sToInclude)
  2354. {
  2355. self::Plugin($sConfigFile, 'addons', $sToInclude);
  2356. }
  2357. $sServer = $oConfig->GetDBHost();
  2358. $sUser = $oConfig->GetDBUser();
  2359. $sPwd = $oConfig->GetDBPwd();
  2360. $sSource = $oConfig->GetDBName();
  2361. $sTablePrefix = $oConfig->GetDBSubname();
  2362. // The include have been included, let's browse the existing classes and
  2363. // develop some data based on the proposed model
  2364. self::InitClasses($sTablePrefix);
  2365. self::$m_sDBName = $sSource;
  2366. self::$m_sTablePrefix = $sTablePrefix;
  2367. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  2368. }
  2369. protected static $m_aPlugins = array();
  2370. public static function RegisterPlugin($sType, $sName, $aInitCallSpec = array())
  2371. {
  2372. self::$m_aPlugins[$sName] = array(
  2373. 'type' => $sType,
  2374. 'init' => $aInitCallSpec,
  2375. );
  2376. }
  2377. protected static function Plugin($sConfigFile, $sModuleType, $sToInclude)
  2378. {
  2379. if (!file_exists($sToInclude))
  2380. {
  2381. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sToInclude));
  2382. }
  2383. require_once($sToInclude);
  2384. }
  2385. protected static function InitPlugins()
  2386. {
  2387. foreach(self::$m_aPlugins as $sName => $aData)
  2388. {
  2389. $aCallSpec = @$aData['init'];
  2390. if (count($aCallSpec) == 2)
  2391. {
  2392. if (!is_callable($aCallSpec))
  2393. {
  2394. throw new CoreException('Wrong declaration in plugin', array('plugin' => $aData['name'], 'type' => $aData['type'], 'class' => $aData['class'], 'init' => $aData['init']));
  2395. }
  2396. call_user_func($aCallSpec);
  2397. }
  2398. }
  2399. }
  2400. // Building an object
  2401. //
  2402. //
  2403. private static $aQueryCacheGetObject = array();
  2404. private static $aQueryCacheGetObjectHits = array();
  2405. public static function GetQueryCacheStatus()
  2406. {
  2407. $aRes = array();
  2408. $iTotalHits = 0;
  2409. foreach(self::$aQueryCacheGetObjectHits as $sClass => $iHits)
  2410. {
  2411. $aRes[] = "$sClass: $iHits";
  2412. $iTotalHits += $iHits;
  2413. }
  2414. return $iTotalHits.' ('.implode(', ', $aRes).')';
  2415. }
  2416. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true)
  2417. {
  2418. if (!array_key_exists($sClass, self::$aQueryCacheGetObject))
  2419. {
  2420. // NOTE: Quick and VERY dirty caching mechanism which relies on
  2421. // the fact that the string '987654321' will never appear in the
  2422. // standard query
  2423. // This will be replaced for sure with a prepared statement
  2424. // or a view... next optimization to come!
  2425. $oFilter = new DBObjectSearch($sClass);
  2426. $oFilter->AddCondition('id', 987654321, '=');
  2427. $sSQL = self::MakeSelectQuery($oFilter);
  2428. self::$aQueryCacheGetObject[$sClass] = $sSQL;
  2429. self::$aQueryCacheGetObjectHits[$sClass] = 0;
  2430. }
  2431. else
  2432. {
  2433. $sSQL = self::$aQueryCacheGetObject[$sClass];
  2434. self::$aQueryCacheGetObjectHits[$sClass] += 1;
  2435. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sClass]."<br/>\n";
  2436. }
  2437. $sSQL = str_replace('987654321', CMDBSource::Quote($iKey), $sSQL);
  2438. $res = CMDBSource::Query($sSQL);
  2439. $aRow = CMDBSource::FetchArray($res);
  2440. CMDBSource::FreeResult($res);
  2441. if ($bMustBeFound && empty($aRow))
  2442. {
  2443. throw new CoreException("No result for the single row query: '$sSQL'");
  2444. }
  2445. return $aRow;
  2446. }
  2447. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '')
  2448. {
  2449. self::_check_subclass($sClass);
  2450. // Compound objects: if available, get the final object class
  2451. //
  2452. if (!array_key_exists("finalclass", $aRow))
  2453. {
  2454. // Either this is a bug (forgot to specify a root class with a finalclass field
  2455. // Or this is the expected behavior, because the object is not made of several tables
  2456. }
  2457. elseif (empty($aRow["finalclass"]))
  2458. {
  2459. // The data is missing in the DB
  2460. // @#@ possible improvement: check that the class is valid !
  2461. $sRootClass = self::GetRootClass($sClass);
  2462. $sFinalClassField = self::DBGetClassField($sRootClass);
  2463. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  2464. }
  2465. else
  2466. {
  2467. // do the job for the real target class
  2468. $sClass = $aRow["finalclass"];
  2469. }
  2470. return new $sClass($aRow, $sClassAlias);
  2471. }
  2472. public static function GetObject($sClass, $iKey, $bMustBeFound = true)
  2473. {
  2474. self::_check_subclass($sClass);
  2475. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound);
  2476. if (empty($aRow))
  2477. {
  2478. return null;
  2479. }
  2480. return self::GetObjectByRow($sClass, $aRow);
  2481. }
  2482. public static function GetHyperLink($sTargetClass, $iKey)
  2483. {
  2484. if ($iKey < 0)
  2485. {
  2486. return "$sTargetClass: $iKey (invalid value)";
  2487. }
  2488. $oObj = self::GetObject($sTargetClass, $iKey, false);
  2489. if (is_null($oObj))
  2490. {
  2491. return "$sTargetClass: $iKey (not found)";
  2492. }
  2493. return $oObj->GetHyperLink();
  2494. }
  2495. public static function NewObject($sClass)
  2496. {
  2497. self::_check_subclass($sClass);
  2498. return new $sClass();
  2499. }
  2500. public static function GetNextKey($sClass)
  2501. {
  2502. $sRootClass = MetaModel::GetRootClass($sClass);
  2503. $sRootTable = MetaModel::DBGetTable($sRootClass);
  2504. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  2505. return $iNextKey;
  2506. }
  2507. public static function BulkDelete(DBObjectSearch $oFilter)
  2508. {
  2509. $sSQL = self::MakeDeleteQuery($oFilter);
  2510. CMDBSource::Query($sSQL);
  2511. }
  2512. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  2513. {
  2514. // $aValues is an array of $sAttCode => $value
  2515. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  2516. CMDBSource::Query($sSQL);
  2517. }
  2518. // Links
  2519. //
  2520. //
  2521. public static function EnumReferencedClasses($sClass)
  2522. {
  2523. self::_check_subclass($sClass);
  2524. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  2525. $aResult = array();
  2526. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  2527. {
  2528. if ($oAttDef->IsExternalKey())
  2529. {
  2530. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  2531. }
  2532. }
  2533. return $aResult;
  2534. }
  2535. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  2536. {
  2537. self::_check_subclass($sClass);
  2538. if ($bSkipLinkingClasses)
  2539. {
  2540. $aLinksClasses = self::EnumLinksClasses();
  2541. }
  2542. // 1-N links (referencing my class), array of sClass => array of sAttcode
  2543. $aResult = array();
  2544. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2545. {
  2546. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  2547. $aExtKeys = array();
  2548. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  2549. {
  2550. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2551. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  2552. {
  2553. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  2554. // Ok, I want this one
  2555. $aExtKeys[$sAttCode] = $oAttDef;
  2556. }
  2557. }
  2558. if (count($aExtKeys) != 0)
  2559. {
  2560. $aResult[$sSomeClass] = $aExtKeys;
  2561. }
  2562. }
  2563. return $aResult;
  2564. }
  2565. public static function EnumLinksClasses()
  2566. {
  2567. // Returns a flat array of classes having at least two external keys
  2568. $aResult = array();
  2569. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2570. {
  2571. $iExtKeyCount = 0;
  2572. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  2573. {
  2574. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2575. if ($oAttDef->IsExternalKey())
  2576. {
  2577. $iExtKeyCount++;
  2578. }
  2579. }
  2580. if ($iExtKeyCount >= 2)
  2581. {
  2582. $aResult[] = $sSomeClass;
  2583. }
  2584. }
  2585. return $aResult;
  2586. }
  2587. public static function EnumLinkingClasses($sClass = "")
  2588. {
  2589. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  2590. $aResult = array();
  2591. foreach (self::EnumLinksClasses() as $sSomeClass)
  2592. {
  2593. $aTargets = array();
  2594. $bFoundClass = false;
  2595. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  2596. {
  2597. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2598. if ($oAttDef->IsExternalKey())
  2599. {
  2600. $sRemoteClass = $oAttDef->GetTargetClass();
  2601. if (empty($sClass))
  2602. {
  2603. $aTargets[$sAttCode] = $sRemoteClass;
  2604. }
  2605. elseif ($sClass == $sRemoteClass)
  2606. {
  2607. $bFoundClass = true;
  2608. }
  2609. else
  2610. {
  2611. $aTargets[$sAttCode] = $sRemoteClass;
  2612. }
  2613. }
  2614. }
  2615. if (empty($sClass) || $bFoundClass)
  2616. {
  2617. $aResult[$sSomeClass] = $aTargets;
  2618. }
  2619. }
  2620. return $aResult;
  2621. }
  2622. public static function GetLinkLabel($sLinkClass, $sAttCode)
  2623. {
  2624. self::_check_subclass($sLinkClass);
  2625. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  2626. return self::GetLabel($sLinkClass, $sAttCode);
  2627. }
  2628. /**
  2629. * Replaces all the parameters by the values passed in the hash array
  2630. */
  2631. static public function ApplyParams($aInput, $aParams)
  2632. {
  2633. $aSearches = array();
  2634. $aReplacements = array();
  2635. foreach($aParams as $sSearch => $sReplace)
  2636. {
  2637. $aSearches[] = '$'.$sSearch.'$';
  2638. $aReplacements[] = $sReplace;
  2639. }
  2640. return str_replace($aSearches, $aReplacements, $aInput);
  2641. }
  2642. } // class MetaModel
  2643. // Standard attribute lists
  2644. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  2645. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  2646. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  2647. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  2648. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  2649. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  2650. ?>