metamodel.class.php 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955
  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->GetFirstJoinedClass()));
  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->GetFirstJoinedClassAlias().$sFieldAlias] = $bAscending;
  1161. }
  1162. // By default, force the name attribute to be the ordering key
  1163. //
  1164. if (empty($aOrderSpec))
  1165. {
  1166. foreach ($oFilter->GetSelectedClasses() as $sSelectedAlias => $sSelectedClass)
  1167. {
  1168. $sNameAttCode = self::GetNameAttributeCode($sSelectedClass);
  1169. if (!empty($sNameAttCode))
  1170. {
  1171. // By default, simply order on the "name" attribute, ascending
  1172. $aOrderSpec[$sSelectedAlias.$sNameAttCode] = true;
  1173. }
  1174. }
  1175. }
  1176. // Go
  1177. //
  1178. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1179. try
  1180. {
  1181. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs);
  1182. }
  1183. catch (MissingQueryArgument $e)
  1184. {
  1185. // Add some information...
  1186. $e->addInfo('OQL', $sOqlQuery);
  1187. throw $e;
  1188. }
  1189. if (self::$m_bTraceQueries)
  1190. {
  1191. $aParams = array();
  1192. if (!array_key_exists($sOqlQuery, self::$m_aQueriesLog))
  1193. {
  1194. self::$m_aQueriesLog[$sOqlQuery] = array(
  1195. 'sql' => array(),
  1196. 'count' => 0,
  1197. );
  1198. }
  1199. self::$m_aQueriesLog[$sOqlQuery]['count']++;
  1200. self::$m_aQueriesLog[$sOqlQuery]['sql'][] = $sRes;
  1201. }
  1202. return $sRes;
  1203. }
  1204. public static function ShowQueryTrace()
  1205. {
  1206. $iTotal = 0;
  1207. foreach (self::$m_aQueriesLog as $sOql => $aQueryData)
  1208. {
  1209. echo "<h2>$sOql</h2>\n";
  1210. $iTotal += $aQueryData['count'];
  1211. echo '<p>'.$aQueryData['count'].'</p>';
  1212. echo '<p>Example: '.$aQueryData['sql'][0].'</p>';
  1213. }
  1214. echo "<h2>Total</h2>\n";
  1215. echo "<p>Count of executed queries: $iTotal</p>";
  1216. echo "<p>Count of built queries: ".count(self::$m_aQueriesLog)."</p>";
  1217. }
  1218. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  1219. {
  1220. $aTranslation = array();
  1221. $aClassAliases = array();
  1222. $aTableAliases = array();
  1223. $oConditionTree = $oFilter->GetCriteria();
  1224. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1225. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1226. return $oSelect->RenderDelete($aScalarArgs);
  1227. }
  1228. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  1229. {
  1230. // $aValues is an array of $sAttCode => $value
  1231. $aTranslation = array();
  1232. $aClassAliases = array();
  1233. $aTableAliases = array();
  1234. $oConditionTree = $oFilter->GetCriteria();
  1235. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), $aValues);
  1236. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1237. return $oSelect->RenderUpdate($aScalarArgs);
  1238. }
  1239. private static function MakeQuery($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, DBObjectSearch $oFilter, $aExpectedAtts = array(), $aValues = array())
  1240. {
  1241. // Note: query class might be different than the class of the filter
  1242. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1243. // $aExpectedAtts is an array of sAttCode=>array of columns
  1244. $sClass = $oFilter->GetFirstJoinedClass();
  1245. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  1246. $bIsOnQueriedClass = array_key_exists($sClassAlias, $aSelectedClasses);
  1247. if ($bIsOnQueriedClass)
  1248. {
  1249. $aClassAliases = array_merge($aClassAliases, $oFilter->GetJoinedClasses());
  1250. }
  1251. self::DbgTrace("Entering: ".$oFilter->ToSibuSQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1252. $sRootClass = self::GetRootClass($sClass);
  1253. $sKeyField = self::DBGetKey($sClass);
  1254. if ($bIsOnQueriedClass)
  1255. {
  1256. // default to the whole list of attributes + the very std id/finalclass
  1257. $aExpectedAtts['id'][] = $sClassAlias.'id';
  1258. foreach (self::GetAttributesList($sClass) as $sAttCode)
  1259. {
  1260. $aExpectedAtts[$sAttCode][] = $sClassAlias.$sAttCode; // alias == class and attcode
  1261. }
  1262. }
  1263. // Compute a clear view of external keys, and external attributes
  1264. // Build the list of external keys:
  1265. // -> ext keys required by a closed join ???
  1266. // -> ext keys mentionned in a 'pointing to' condition
  1267. // -> ext keys required for an external field
  1268. //
  1269. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1270. //
  1271. // Optimization: could be computed once for all (cached)
  1272. // Could be done in MakeQuerySingleTable ???
  1273. //
  1274. if ($bIsOnQueriedClass)
  1275. {
  1276. // Get all Ext keys for the queried class (??)
  1277. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  1278. {
  1279. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1280. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1281. }
  1282. }
  1283. // Get all Ext keys used by the filter
  1284. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $trash)
  1285. {
  1286. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1287. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1288. }
  1289. // Add the ext fields used in the select (eventually adds an external key)
  1290. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1291. {
  1292. if ($oAttDef->IsExternalField())
  1293. {
  1294. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1295. if (array_key_exists($sAttCode, $aExpectedAtts) || $oConditionTree->RequiresField($sClassAlias, $sAttCode))
  1296. {
  1297. // Add the external attribute
  1298. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1299. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1300. }
  1301. }
  1302. }
  1303. // First query built upon on the leaf (ie current) class
  1304. //
  1305. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  1306. $oSelectBase = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sClass, $aExpectedAtts, $aExtKeys, $aValues);
  1307. // Then we join the queries of the eventual parent classes (compound model)
  1308. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  1309. {
  1310. if (self::DBGetTable($sParentClass) == "") continue;
  1311. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  1312. $oSelectParentTable = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sParentClass, $aExpectedAtts, $aExtKeys, $aValues);
  1313. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  1314. }
  1315. // Filter on objects referencing me
  1316. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1317. {
  1318. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1319. {
  1320. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1321. // We don't want any attribute from the foreign class, just filter on an inner join
  1322. $aExpAtts = array();
  1323. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  1324. //self::DbgTrace($oForeignFilter);
  1325. //self::DbgTrace($oForeignFilter->ToSibuSQL());
  1326. //self::DbgTrace($oSelectForeign);
  1327. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1328. $oSelectForeign = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oForeignFilter, $aExpAtts);
  1329. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1330. $sForeignKeyTable = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][0];
  1331. $sForeignKeyColumn = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][1];
  1332. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1333. }
  1334. }
  1335. // Filter on related objects
  1336. //
  1337. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  1338. {
  1339. $oSubFilter = $aCritInfo['flt'];
  1340. $sRelCode = $aCritInfo['relcode'];
  1341. $iMaxDepth = $aCritInfo['maxdepth'];
  1342. // Get the starting point objects
  1343. $oStartSet = new CMDBObjectSet($oSubFilter);
  1344. // Get the objects related to those objects... recursively...
  1345. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  1346. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  1347. // #@# todo - related objects and expressions...
  1348. // Create condition
  1349. if (count($aRestriction) > 0)
  1350. {
  1351. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  1352. }
  1353. else
  1354. {
  1355. // Quick N'dirty -> generate an empty set
  1356. $oSelectBase->AddCondition('false');
  1357. }
  1358. }
  1359. // Translate the conditions... and go
  1360. //
  1361. if ($bIsOnQueriedClass)
  1362. {
  1363. $oConditionTranslated = $oConditionTree->Translate($aTranslation);
  1364. $oSelectBase->SetCondition($oConditionTranslated);
  1365. }
  1366. // That's all... cross fingers and we'll get some working query
  1367. //MyHelpers::var_dump_html($oSelectBase, true);
  1368. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1369. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1370. return $oSelectBase;
  1371. }
  1372. protected static function MakeQuerySingleTable($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, $oFilter, $sTableClass, $aExpectedAtts, $aExtKeys, $aValues)
  1373. {
  1374. // $aExpectedAtts is an array of sAttCode=>sAlias
  1375. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1376. // Prepare the query for a single table (compound objects)
  1377. // Ignores the items (attributes/filters) that are not on the target table
  1378. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1379. //
  1380. // Returns an SQLQuery
  1381. //
  1382. $sTargetClass = $oFilter->GetFirstJoinedClass();
  1383. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  1384. $sTable = self::DBGetTable($sTableClass);
  1385. $sTableAlias = self::GenerateUniqueAlias($aTableAliases, $sTargetAlias.'_'.$sTable, $sTable);
  1386. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $aSelectedClasses);
  1387. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToSibuSQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1388. // 1 - SELECT and UPDATE
  1389. //
  1390. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1391. //
  1392. $aSelect = array();
  1393. $aUpdateValues = array();
  1394. // 1/a - Get the key
  1395. //
  1396. if ($bIsOnQueriedClass)
  1397. {
  1398. $aSelect[$aExpectedAtts['id'][0]] = new FieldExpression(self::DBGetKey($sTableClass), $sTableAlias);
  1399. }
  1400. // We need one pkey to be the key, let's take the one corresponding to the leaf
  1401. if ($sTableClass == $sTargetClass)
  1402. {
  1403. $aTranslation[$sTargetAlias]['id'] = array($sTableAlias, self::DBGetKey($sTableClass));
  1404. }
  1405. // 1/b - Get the other attributes
  1406. //
  1407. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1408. {
  1409. // Skip this attribute if not defined in this table
  1410. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  1411. // Skip this attribute if not writable (means that it does not correspond
  1412. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1413. // Update...
  1414. //
  1415. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1416. {
  1417. assert ($oAttDef->IsDirectField());
  1418. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1419. {
  1420. $aUpdateValues[$sColumn] = $sValue;
  1421. }
  1422. }
  1423. // Select...
  1424. //
  1425. // Skip, if a list of fields has been specified and it is not there
  1426. if (!array_key_exists($sAttCode, $aExpectedAtts)) continue;
  1427. if ($oAttDef->IsExternalField())
  1428. {
  1429. // skip, this will be handled in the joined tables
  1430. }
  1431. else
  1432. {
  1433. // standard field, or external key
  1434. // add it to the output
  1435. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1436. {
  1437. foreach ($aExpectedAtts[$sAttCode] as $sAttAlias)
  1438. {
  1439. $aSelect[$sAttAlias.$sColId] = new FieldExpression($sSQLExpr, $sTableAlias);
  1440. }
  1441. }
  1442. }
  1443. }
  1444. // 2 - WHERE
  1445. //
  1446. foreach(self::$m_aFilterDefs[$sTargetClass] as $sFltCode => $oFltAtt)
  1447. {
  1448. // Skip this filter if not defined in this table
  1449. if (self::$m_aFilterOrigins[$sTargetClass][$sFltCode] != $sTableClass) continue;
  1450. // #@# todo - aller plus loin... a savoir que la table de translation doit contenir une "Expression"
  1451. foreach($oFltAtt->GetSQLExpressions() as $sColID => $sFltExpr)
  1452. {
  1453. // Note: I did not test it with filters relying on several expressions...
  1454. // as long as sColdID is empty, this is working, otherwise... ?
  1455. $aTranslation[$sTargetAlias][$sFltCode.$sColID] = array($sTableAlias, $sFltExpr);
  1456. }
  1457. }
  1458. // #@# todo - See what a full text search condition should be
  1459. // 2' - WHERE / Full text search condition
  1460. //
  1461. if ($bIsOnQueriedClass)
  1462. {
  1463. $aFullText = $oFilter->GetCriteria_FullText();
  1464. }
  1465. else
  1466. {
  1467. // Pourquoi ???
  1468. $aFullText = array();
  1469. }
  1470. // 3 - The whole stuff, for this table only
  1471. //
  1472. $oSelectBase = new SQLQuery($sTable, $sTableAlias, $aSelect, null, $aFullText, $bIsOnQueriedClass, $aUpdateValues);
  1473. // 4 - The external keys -> joins...
  1474. //
  1475. if (array_key_exists($sTableClass, $aExtKeys))
  1476. {
  1477. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1478. {
  1479. $oKeyAttDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  1480. $oExtFilter = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  1481. // In case the join was not explicitely defined in the filter,
  1482. // we need to do it now
  1483. if (empty($oExtFilter))
  1484. {
  1485. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1486. $sKeyClassAlias = self::GenerateUniqueAlias($aClassAliases, $sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1487. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1488. }
  1489. else
  1490. {
  1491. // The aliases should not conflict because normalization occured while building the filter
  1492. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  1493. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  1494. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1495. }
  1496. // Specify expected attributes for the target class query
  1497. // ... and use the current alias !
  1498. $aExpAtts = array();
  1499. $aIntermediateTranslation = array();
  1500. foreach($aExtFields as $sAttCode => $oAtt)
  1501. {
  1502. $sExtAttCode = $oAtt->GetExtAttCode();
  1503. if (array_key_exists($sAttCode, $aExpectedAtts))
  1504. {
  1505. // Request this attribute... transmit the alias !
  1506. $aExpAtts[$sExtAttCode] = $aExpectedAtts[$sAttCode];
  1507. }
  1508. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1509. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  1510. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  1511. {
  1512. $aIntermediateTranslation[$sTargetAlias.$sColID][$sAttCode] = array($sKeyClassAlias, $sRemoteAttExpr);
  1513. }
  1514. //#@# debug - echo "<p>$sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</p>\n";
  1515. }
  1516. $oConditionTree = $oConditionTree->Translate($aIntermediateTranslation, false);
  1517. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  1518. $oSelectExtKey = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oExtFilter, $aExpAtts);
  1519. $sLocalKeyField = current($oKeyAttDef->GetSQLExpressions()); // get the first column for an external key
  1520. $sExternalKeyField = self::DBGetKey($sKeyClass);
  1521. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1522. if ($oKeyAttDef->IsNullAllowed())
  1523. {
  1524. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1525. }
  1526. else
  1527. {
  1528. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1529. }
  1530. }
  1531. }
  1532. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  1533. return $oSelectBase;
  1534. }
  1535. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  1536. {
  1537. if (!array_key_exists($sNewName, $aAliases))
  1538. {
  1539. $aAliases[$sNewName] = $sRealName;
  1540. return $sNewName;
  1541. }
  1542. for ($i = 1 ; $i < 100 ; $i++)
  1543. {
  1544. $sAnAlias = $sNewName.$i;
  1545. if (!array_key_exists($sAnAlias, $aAliases))
  1546. {
  1547. // Create that new alias
  1548. $aAliases[$sAnAlias] = $sRealName;
  1549. return $sAnAlias;
  1550. }
  1551. }
  1552. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  1553. }
  1554. public static function CheckDefinitions()
  1555. {
  1556. if (count(self::GetClasses()) == 0)
  1557. {
  1558. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  1559. }
  1560. $aErrors = array();
  1561. $aSugFix = array();
  1562. foreach (self::GetClasses() as $sClass)
  1563. {
  1564. if (self::IsAbstract($sClass)) continue;
  1565. $sNameAttCode = self::GetNameAttributeCode($sClass);
  1566. if (empty($sNameAttCode))
  1567. {
  1568. // let's try this !!!
  1569. // $aErrors[$sClass][] = "Missing value for name definition: the framework will (should...) replace it by the id";
  1570. // $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1571. }
  1572. else if(!self::IsValidAttCode($sClass, $sNameAttCode))
  1573. {
  1574. $aErrors[$sClass][] = "Unkown attribute code '".$sNameAttCode."' for the name definition";
  1575. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1576. }
  1577. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  1578. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  1579. {
  1580. $aErrors[$sClass][] = "Unkown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  1581. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1582. }
  1583. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1584. {
  1585. // It makes no sense to check the attributes again and again in the subclasses
  1586. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1587. if ($oAttDef->IsExternalKey())
  1588. {
  1589. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  1590. {
  1591. $aErrors[$sClass][] = "Unkown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  1592. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  1593. }
  1594. }
  1595. elseif ($oAttDef->IsExternalField())
  1596. {
  1597. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1598. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  1599. {
  1600. $aErrors[$sClass][] = "Unkown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  1601. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  1602. }
  1603. else
  1604. {
  1605. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1606. $sTargetClass = $oKeyAttDef->GetTargetClass();
  1607. $sExtAttCode = $oAttDef->GetExtAttCode();
  1608. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  1609. {
  1610. $aErrors[$sClass][] = "Unkown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  1611. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  1612. }
  1613. }
  1614. }
  1615. else // standard attributes
  1616. {
  1617. // Check that the default values definition is a valid object!
  1618. $oValSetDef = $oAttDef->GetValuesDef();
  1619. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  1620. {
  1621. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  1622. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  1623. }
  1624. else
  1625. {
  1626. // Default value must be listed in the allowed values (if defined)
  1627. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  1628. if (!is_null($aAllowedValues))
  1629. {
  1630. $sDefaultValue = $oAttDef->GetDefaultValue();
  1631. if (!array_key_exists($sDefaultValue, $aAllowedValues))
  1632. {
  1633. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  1634. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  1635. }
  1636. }
  1637. }
  1638. }
  1639. // Check dependencies
  1640. if ($oAttDef->IsWritable())
  1641. {
  1642. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  1643. {
  1644. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  1645. {
  1646. $aErrors[$sClass][] = "Unkown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  1647. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1648. }
  1649. }
  1650. }
  1651. }
  1652. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  1653. {
  1654. if (method_exists($oFilterDef, '__GetRefAttribute'))
  1655. {
  1656. $oAttDef = $oFilterDef->__GetRefAttribute();
  1657. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  1658. {
  1659. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  1660. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1661. }
  1662. }
  1663. }
  1664. // Lifecycle
  1665. //
  1666. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1667. if (strlen($sStateAttCode) > 0)
  1668. {
  1669. // Lifecycle - check that the state attribute does exist as an attribute
  1670. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  1671. {
  1672. $aErrors[$sClass][] = "Unkown attribute code '".$sStateAttCode."' for the state definition";
  1673. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1674. }
  1675. else
  1676. {
  1677. // Lifecycle - check that there is a value set constraint on the state attribute
  1678. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  1679. $aStates = array_keys(self::EnumStates($sClass));
  1680. if (is_null($aAllowedValuesRaw))
  1681. {
  1682. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  1683. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  1684. }
  1685. else
  1686. {
  1687. $aAllowedValues = array_keys($aAllowedValuesRaw);
  1688. // Lifecycle - check the the state attribute allowed values are defined states
  1689. foreach($aAllowedValues as $sValue)
  1690. {
  1691. if (!in_array($sValue, $aStates))
  1692. {
  1693. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  1694. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1695. }
  1696. }
  1697. // Lifecycle - check that defined states are allowed values
  1698. foreach($aStates as $sStateValue)
  1699. {
  1700. if (!in_array($sStateValue, $aAllowedValues))
  1701. {
  1702. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  1703. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1704. }
  1705. }
  1706. }
  1707. // Lifcycle - check that the action handlers are defined
  1708. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  1709. {
  1710. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  1711. {
  1712. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1713. {
  1714. if (!method_exists($sClass, $sActionHandler))
  1715. {
  1716. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  1717. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  1718. }
  1719. }
  1720. }
  1721. }
  1722. }
  1723. }
  1724. // ZList
  1725. //
  1726. foreach(self::EnumZLists() as $sListCode)
  1727. {
  1728. foreach (self::GetZListItems($sClass, $sListCode) as $sMyAttCode)
  1729. {
  1730. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  1731. {
  1732. $aErrors[$sClass][] = "Unkown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  1733. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1734. }
  1735. }
  1736. }
  1737. }
  1738. if (count($aErrors) > 0)
  1739. {
  1740. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  1741. echo "<h3>Business model inconsistencies have been found</h3>\n";
  1742. // #@# later -> this is the responsibility of the caller to format the output
  1743. foreach ($aErrors as $sClass => $aMessages)
  1744. {
  1745. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  1746. echo "<ul class=\"treeview\">\n";
  1747. $i = 0;
  1748. foreach ($aMessages as $sMsg)
  1749. {
  1750. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  1751. $i++;
  1752. }
  1753. echo "</ul>\n";
  1754. }
  1755. echo "<p>Aborting...</p>\n";
  1756. echo "</div>\n";
  1757. exit;
  1758. }
  1759. }
  1760. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  1761. {
  1762. if (empty($sRepairUrl)) return;
  1763. if (count($aSQLFixes) == 0) return;
  1764. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  1765. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aSQLFixes))."\">\n";
  1766. echo " <input type=\"submit\" value=\" Apply the changes (".count($aSQLFixes)." queries) \">\n";
  1767. echo "</form>\n";
  1768. }
  1769. public static function DBExists($bMustBeComplete = true)
  1770. {
  1771. // returns true if at least one table exists
  1772. //
  1773. if (!CMDBSource::IsDB(self::$m_sDBName))
  1774. {
  1775. return false;
  1776. }
  1777. CMDBSource::SelectDB(self::$m_sDBName);
  1778. $aFound = array();
  1779. $aMissing = array();
  1780. foreach (self::DBEnumTables() as $sTable => $aClasses)
  1781. {
  1782. if (CMDBSource::IsTable($sTable))
  1783. {
  1784. $aFound[] = $sTable;
  1785. }
  1786. else
  1787. {
  1788. $aMissing[] = $sTable;
  1789. }
  1790. }
  1791. if (count($aFound) == 0)
  1792. {
  1793. // no expected table has been found
  1794. return false;
  1795. }
  1796. else
  1797. {
  1798. if (count($aMissing) == 0)
  1799. {
  1800. // the database is complete (still, could be some fields missing!)
  1801. return true;
  1802. }
  1803. else
  1804. {
  1805. // not all the tables, could be an older version
  1806. if ($bMustBeComplete)
  1807. {
  1808. return false;
  1809. }
  1810. else
  1811. {
  1812. return true;
  1813. }
  1814. }
  1815. }
  1816. }
  1817. public static function DBDrop()
  1818. {
  1819. $bDropEntireDB = true;
  1820. if (!empty(self::$m_sTablePrefix))
  1821. {
  1822. // Do drop only tables corresponding to the sub-database (table prefix)
  1823. // then possibly drop the DB itself (if no table remain)
  1824. foreach (CMDBSource::EnumTables() as $sTable)
  1825. {
  1826. // perform a case insensitive test because on Windows the table names become lowercase :-(
  1827. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  1828. {
  1829. CMDBSource::DropTable($sTable);
  1830. }
  1831. else
  1832. {
  1833. // There is at least one table which is out of the scope of the current application
  1834. $bDropEntireDB = false;
  1835. }
  1836. }
  1837. }
  1838. if ($bDropEntireDB)
  1839. {
  1840. CMDBSource::DropDB(self::$m_sDBName);
  1841. }
  1842. }
  1843. public static function DBCreate()
  1844. {
  1845. // Note: we have to check if the DB does exist, because we may share the DB
  1846. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  1847. if (!CMDBSource::IsDB(self::$m_sDBName))
  1848. {
  1849. CMDBSource::CreateDB(self::$m_sDBName);
  1850. }
  1851. self::DBCreateTables();
  1852. }
  1853. protected static function DBCreateTables()
  1854. {
  1855. list($aErrors, $aSugFix) = self::DBCheckFormat();
  1856. $aSQL = array();
  1857. foreach ($aSugFix as $sClass => $aTarget)
  1858. {
  1859. foreach ($aTarget as $aQueries)
  1860. {
  1861. foreach ($aQueries as $sQuery)
  1862. {
  1863. //$aSQL[] = $sQuery;
  1864. // forces a refresh of cached information
  1865. CMDBSource::CreateTable($sQuery);
  1866. }
  1867. }
  1868. }
  1869. // does not work -how to have multiple statements in a single query?
  1870. // $sDoCreateAll = implode(" ; ", $aSQL);
  1871. }
  1872. public static function DBDump()
  1873. {
  1874. $aDataDump = array();
  1875. foreach (self::DBEnumTables() as $sTable => $aClasses)
  1876. {
  1877. $aRows = CMDBSource::DumpTable($sTable);
  1878. $aDataDump[$sTable] = $aRows;
  1879. }
  1880. return $aDataDump;
  1881. }
  1882. public static function DBCheckFormat()
  1883. {
  1884. $aErrors = array();
  1885. $aSugFix = array();
  1886. foreach (self::GetClasses() as $sClass)
  1887. {
  1888. if (self::IsAbstract($sClass)) continue;
  1889. // Check that the table exists
  1890. //
  1891. $sTable = self::DBGetTable($sClass);
  1892. $sKeyField = self::DBGetKey($sClass);
  1893. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  1894. if (!CMDBSource::IsTable($sTable))
  1895. {
  1896. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  1897. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` (`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY) ENGINE = innodb CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  1898. }
  1899. // Check that the key field exists
  1900. //
  1901. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  1902. {
  1903. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  1904. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD `$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  1905. }
  1906. else
  1907. {
  1908. // Check the key field properties
  1909. //
  1910. if (!CMDBSource::IsKey($sTable, $sKeyField))
  1911. {
  1912. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  1913. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  1914. }
  1915. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  1916. {
  1917. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  1918. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` `$sKeyField` INT(11) NOT NULL AUTO_INCREMENT";
  1919. }
  1920. }
  1921. // Check that any defined field exists
  1922. //
  1923. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  1924. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1925. {
  1926. // Skip this attribute if not originaly defined in this class
  1927. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1928. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  1929. {
  1930. $sFieldSpecs = $oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL";
  1931. if (!CMDBSource::IsField($sTable, $sField))
  1932. {
  1933. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  1934. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD `$sField` $sFieldSpecs";
  1935. if ($oAttDef->IsExternalKey())
  1936. {
  1937. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  1938. }
  1939. }
  1940. else
  1941. {
  1942. // The field already exists, does it have the relevant properties?
  1943. //
  1944. $bToBeChanged = false;
  1945. if ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  1946. {
  1947. $bToBeChanged = true;
  1948. if ($oAttDef->IsNullAllowed())
  1949. {
  1950. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could be NULL";
  1951. }
  1952. else
  1953. {
  1954. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could NOT be NULL";
  1955. }
  1956. }
  1957. $sActualFieldType = CMDBSource::GetFieldType($sTable, $sField);
  1958. if (strcasecmp($sDBFieldType, $sActualFieldType) != 0)
  1959. {
  1960. $bToBeChanged = true;
  1961. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldType' while expecting '$sDBFieldType'";
  1962. }
  1963. if ($bToBeChanged)
  1964. {
  1965. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` `$sField` $sFieldSpecs";
  1966. }
  1967. // Create indexes (external keys only... so far)
  1968. //
  1969. if ($oAttDef->IsExternalKey() && !CMDBSource::HasIndex($sTable, $sField))
  1970. {
  1971. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  1972. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  1973. }
  1974. }
  1975. }
  1976. }
  1977. }
  1978. return array($aErrors, $aSugFix);
  1979. }
  1980. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  1981. {
  1982. $sRootClass = self::GetRootClass($sClass);
  1983. $sTable = self::DBGetTable($sClass);
  1984. $sKeyField = self::DBGetKey($sClass);
  1985. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  1986. {
  1987. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  1988. }
  1989. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  1990. if (count($aWrongRecords) == 0) return;
  1991. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  1992. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  1993. foreach ($aWrongRecords as $iRecordId)
  1994. {
  1995. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  1996. {
  1997. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  1998. {
  1999. case 'Delete':
  2000. // Already planned for a deletion
  2001. // Let's concatenate the errors description together
  2002. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2003. break;
  2004. case 'Update':
  2005. // Let's plan a deletion
  2006. break;
  2007. }
  2008. }
  2009. else
  2010. {
  2011. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2012. }
  2013. if (!$bProcessingFriends)
  2014. {
  2015. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  2016. {
  2017. // Something new to be deleted...
  2018. $iNewDelCount++;
  2019. }
  2020. }
  2021. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  2022. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  2023. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2024. $aPlannedDel[$sTable][] = $iRecordId;
  2025. }
  2026. // Now make sure that we would delete the records of the other tables for that class
  2027. //
  2028. if (!$bProcessingFriends)
  2029. {
  2030. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  2031. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  2032. {
  2033. $sFriendTable = self::DBGetTable($sFriendClass);
  2034. $sFriendKey = self::DBGetKey($sFriendClass);
  2035. // skip the current table
  2036. if ($sFriendTable == $sTable) continue;
  2037. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  2038. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  2039. }
  2040. }
  2041. }
  2042. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2043. {
  2044. $sRootClass = self::GetRootClass($sClass);
  2045. $sTable = self::DBGetTable($sClass);
  2046. $sKeyField = self::DBGetKey($sClass);
  2047. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2048. {
  2049. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2050. }
  2051. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2052. if (count($aWrongRecords) == 0) return;
  2053. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2054. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2055. foreach ($aWrongRecords as $iRecordId)
  2056. {
  2057. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2058. {
  2059. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2060. {
  2061. case 'Delete':
  2062. // No need to update, the record will be deleted!
  2063. break;
  2064. case 'Update':
  2065. // Already planned for an update
  2066. // Add this new update spec to the list
  2067. $bFoundSameSpec = false;
  2068. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  2069. {
  2070. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  2071. {
  2072. $bFoundSameSpec = true;
  2073. }
  2074. }
  2075. if (!$bFoundSameSpec)
  2076. {
  2077. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2078. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2079. }
  2080. break;
  2081. }
  2082. }
  2083. else
  2084. {
  2085. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2086. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  2087. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2088. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2089. }
  2090. }
  2091. }
  2092. // returns the count of records found for deletion
  2093. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2094. {
  2095. foreach (self::GetClasses() as $sClass)
  2096. {
  2097. if (self::IsAbstract($sClass)) continue;
  2098. $sRootClass = self::GetRootClass($sClass);
  2099. $sTable = self::DBGetTable($sClass);
  2100. $sKeyField = self::DBGetKey($sClass);
  2101. // Check that the final class field contains the name of a class which inherited from the current class
  2102. //
  2103. if (self::HasFinalClassField($sClass))
  2104. {
  2105. $sFinalClassField = self::DBGetClassField($sClass);
  2106. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2107. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  2108. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  2109. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2110. }
  2111. // Compound objects model - node/leaf classes (not the root itself)
  2112. //
  2113. if (!self::IsStandaloneClass($sClass) && !self::HasFinalClassField($sClass))
  2114. {
  2115. $sRootTable = self::DBGetTable($sRootClass);
  2116. $sRootKey = self::DBGetKey($sRootClass);
  2117. $sFinalClassField = self::DBGetClassField($sRootClass);
  2118. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2119. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  2120. // Check that any record found here has its counterpart in the root table
  2121. // and which refers to a child class
  2122. //
  2123. $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";
  2124. 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);
  2125. // Check that any record found in the root table and referring to a child class
  2126. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  2127. //
  2128. $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)";
  2129. 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);
  2130. }
  2131. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2132. {
  2133. // Skip this attribute if not defined in this table
  2134. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2135. if ($oAttDef->IsExternalKey())
  2136. {
  2137. // Check that any external field is pointing to an existing object
  2138. //
  2139. $sRemoteClass = $oAttDef->GetTargetClass();
  2140. $sRemoteTable = self::DBGetTable($sRemoteClass);
  2141. $sRemoteKey = self::DBGetKey($sRemoteClass);
  2142. $sExtKeyField = current($oAttDef->GetSQLExpressions()); // get the first column for an external key
  2143. // Note: a class/table may have an external key on itself
  2144. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  2145. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  2146. if ($oAttDef->IsNullAllowed())
  2147. {
  2148. // Exclude the records pointing to 0/null from the errors
  2149. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2150. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2151. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2152. }
  2153. else
  2154. {
  2155. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2156. }
  2157. // Do almost the same, taking into account the records planned for deletion
  2158. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  2159. {
  2160. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  2161. // but in that case you won't be able to track the root cause (cascading)
  2162. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  2163. if ($oAttDef->IsNullAllowed())
  2164. {
  2165. // Exclude the records pointing to 0/null from the errors
  2166. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2167. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2168. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2169. }
  2170. else
  2171. {
  2172. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2173. }
  2174. }
  2175. }
  2176. else if ($oAttDef->IsDirectField())
  2177. {
  2178. // Check that the values fit the allowed values
  2179. //
  2180. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2181. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  2182. {
  2183. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  2184. $sMyAttributeField = current($oAttDef->GetSQLExpressions()); // get the first column for the moment
  2185. $sDefaultValue = $oAttDef->GetDefaultValue();
  2186. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  2187. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2188. }
  2189. }
  2190. }
  2191. }
  2192. }
  2193. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  2194. {
  2195. // Records in error, and action to be taken: delete or update
  2196. // by RootClass/Table/Record
  2197. $aErrorsAndFixes = array();
  2198. // Records to be ignored in the current/next pass
  2199. // by Table = array of RecordId
  2200. $aPlannedDel = array();
  2201. // Count of errors in the next pass: no error means that we can leave...
  2202. $iErrorCount = 0;
  2203. // Limit in case of a bug in the algorythm
  2204. $iLoopCount = 0;
  2205. $iNewDelCount = 1; // startup...
  2206. while ($iNewDelCount > 0)
  2207. {
  2208. $iNewDelCount = 0;
  2209. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2210. $iErrorCount += $iNewDelCount;
  2211. // Safety net #1 - limit the planned deletions
  2212. //
  2213. $iMaxDel = 1000;
  2214. $iPlannedDel = 0;
  2215. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  2216. {
  2217. $iPlannedDel += count($aPlannedDelOnTable);
  2218. }
  2219. if ($iPlannedDel > $iMaxDel)
  2220. {
  2221. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  2222. break;
  2223. }
  2224. // Safety net #2 - limit the iterations
  2225. //
  2226. $iLoopCount++;
  2227. $iMaxLoops = 10;
  2228. if ($iLoopCount > $iMaxLoops)
  2229. {
  2230. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  2231. break;
  2232. }
  2233. }
  2234. // Display the results
  2235. //
  2236. $iIssueCount = 0;
  2237. $aFixesDelete = array();
  2238. $aFixesUpdate = array();
  2239. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  2240. {
  2241. foreach ($aTables as $sTable => $aRecords)
  2242. {
  2243. foreach ($aRecords as $iRecord => $aError)
  2244. {
  2245. $sAction = $aError['Action'];
  2246. $sReason = $aError['Reason'];
  2247. $iPass = $aError['Pass'];
  2248. switch ($sAction)
  2249. {
  2250. case 'Delete':
  2251. $sActionDetails = "";
  2252. $aFixesDelete[$sTable][] = $iRecord;
  2253. break;
  2254. case 'Update':
  2255. $aUpdateDesc = array();
  2256. foreach($aError['Action_Details'] as $aUpdateSpec)
  2257. {
  2258. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  2259. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  2260. }
  2261. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  2262. break;
  2263. default:
  2264. $sActionDetails = "bug: unknown action '$sAction'";
  2265. }
  2266. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  2267. $iIssueCount++;
  2268. }
  2269. }
  2270. }
  2271. if ($iIssueCount > 0)
  2272. {
  2273. // Build the queries to fix in the database
  2274. //
  2275. // First step, be able to get class data out of the table name
  2276. // Could be optimized, because we've made the job earlier... but few benefits, so...
  2277. $aTable2ClassProp = array();
  2278. foreach (self::GetClasses() as $sClass)
  2279. {
  2280. if (self::IsAbstract($sClass)) continue;
  2281. $sRootClass = self::GetRootClass($sClass);
  2282. $sTable = self::DBGetTable($sClass);
  2283. $sKeyField = self::DBGetKey($sClass);
  2284. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2285. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  2286. }
  2287. // Second step, build a flat list of SQL queries
  2288. $aSQLFixes = array();
  2289. $iPlannedUpdate = 0;
  2290. foreach ($aFixesUpdate as $sTable => $aColumns)
  2291. {
  2292. foreach ($aColumns as $sColumn => $aNewValues)
  2293. {
  2294. foreach ($aNewValues as $sNewValue => $aRecords)
  2295. {
  2296. $iPlannedUpdate += count($aRecords);
  2297. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2298. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2299. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  2300. }
  2301. }
  2302. }
  2303. $iPlannedDel = 0;
  2304. foreach ($aFixesDelete as $sTable => $aRecords)
  2305. {
  2306. $iPlannedDel += count($aRecords);
  2307. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2308. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2309. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  2310. }
  2311. // Report the results
  2312. //
  2313. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2314. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  2315. // #@# later -> this is the responsibility of the caller to format the output
  2316. echo "<ul class=\"treeview\">\n";
  2317. foreach ($aIssues as $sIssueDesc)
  2318. {
  2319. echo "<li>$sIssueDesc</li>\n";
  2320. }
  2321. echo "</ul>\n";
  2322. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  2323. echo "<p>Aborting...</p>\n";
  2324. echo "</div>\n";
  2325. exit;
  2326. }
  2327. }
  2328. public static function Startup($sConfigFile, $bAllowMissingDB = false)
  2329. {
  2330. self::LoadConfig($sConfigFile);
  2331. if (self::DBExists())
  2332. {
  2333. CMDBSource::SelectDB(self::$m_sDBName);
  2334. // Some of the init could not be done earlier (requiring classes to be declared and DB to be accessible)
  2335. self::InitPlugins();
  2336. }
  2337. else
  2338. {
  2339. if (!$bAllowMissingDB)
  2340. {
  2341. throw new CoreException('Database not found, check your configuration file', array('config_file'=>$sConfigFile, 'db_name'=>self::$m_sDBName));
  2342. }
  2343. }
  2344. }
  2345. public static function LoadConfig($sConfigFile)
  2346. {
  2347. $oConfig = new Config($sConfigFile);
  2348. foreach ($oConfig->GetAppModules() as $sModule => $sToInclude)
  2349. {
  2350. self::Plugin($sConfigFile, 'application', $sToInclude);
  2351. }
  2352. foreach ($oConfig->GetDataModels() as $sModule => $sToInclude)
  2353. {
  2354. self::Plugin($sConfigFile, 'business', $sToInclude);
  2355. }
  2356. foreach ($oConfig->GetAddons() as $sModule => $sToInclude)
  2357. {
  2358. self::Plugin($sConfigFile, 'addons', $sToInclude);
  2359. }
  2360. $sServer = $oConfig->GetDBHost();
  2361. $sUser = $oConfig->GetDBUser();
  2362. $sPwd = $oConfig->GetDBPwd();
  2363. $sSource = $oConfig->GetDBName();
  2364. $sTablePrefix = $oConfig->GetDBSubname();
  2365. // The include have been included, let's browse the existing classes and
  2366. // develop some data based on the proposed model
  2367. self::InitClasses($sTablePrefix);
  2368. self::$m_sDBName = $sSource;
  2369. self::$m_sTablePrefix = $sTablePrefix;
  2370. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  2371. }
  2372. protected static $m_aPlugins = array();
  2373. public static function RegisterPlugin($sType, $sName, $aInitCallSpec = array())
  2374. {
  2375. self::$m_aPlugins[$sName] = array(
  2376. 'type' => $sType,
  2377. 'init' => $aInitCallSpec,
  2378. );
  2379. }
  2380. protected static function Plugin($sConfigFile, $sModuleType, $sToInclude)
  2381. {
  2382. if (!file_exists($sToInclude))
  2383. {
  2384. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sToInclude));
  2385. }
  2386. require_once($sToInclude);
  2387. }
  2388. protected static function InitPlugins()
  2389. {
  2390. foreach(self::$m_aPlugins as $sName => $aData)
  2391. {
  2392. $aCallSpec = @$aData['init'];
  2393. if (count($aCallSpec) == 2)
  2394. {
  2395. if (!is_callable($aCallSpec))
  2396. {
  2397. throw new CoreException('Wrong declaration in plugin', array('plugin' => $aData['name'], 'type' => $aData['type'], 'class' => $aData['class'], 'init' => $aData['init']));
  2398. }
  2399. call_user_func($aCallSpec);
  2400. }
  2401. }
  2402. }
  2403. // Building an object
  2404. //
  2405. //
  2406. private static $aQueryCacheGetObject = array();
  2407. private static $aQueryCacheGetObjectHits = array();
  2408. public static function GetQueryCacheStatus()
  2409. {
  2410. $aRes = array();
  2411. $iTotalHits = 0;
  2412. foreach(self::$aQueryCacheGetObjectHits as $sClass => $iHits)
  2413. {
  2414. $aRes[] = "$sClass: $iHits";
  2415. $iTotalHits += $iHits;
  2416. }
  2417. return $iTotalHits.' ('.implode(', ', $aRes).')';
  2418. }
  2419. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true)
  2420. {
  2421. if (!array_key_exists($sClass, self::$aQueryCacheGetObject))
  2422. {
  2423. // NOTE: Quick and VERY dirty caching mechanism which relies on
  2424. // the fact that the string '987654321' will never appear in the
  2425. // standard query
  2426. // This will be replaced for sure with a prepared statement
  2427. // or a view... next optimization to come!
  2428. $oFilter = new DBObjectSearch($sClass);
  2429. $oFilter->AddCondition('id', 987654321, '=');
  2430. $sSQL = self::MakeSelectQuery($oFilter);
  2431. self::$aQueryCacheGetObject[$sClass] = $sSQL;
  2432. self::$aQueryCacheGetObjectHits[$sClass] = 0;
  2433. }
  2434. else
  2435. {
  2436. $sSQL = self::$aQueryCacheGetObject[$sClass];
  2437. self::$aQueryCacheGetObjectHits[$sClass] += 1;
  2438. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sClass]."<br/>\n";
  2439. }
  2440. $sSQL = str_replace('987654321', CMDBSource::Quote($iKey), $sSQL);
  2441. $res = CMDBSource::Query($sSQL);
  2442. $aRow = CMDBSource::FetchArray($res);
  2443. CMDBSource::FreeResult($res);
  2444. if ($bMustBeFound && empty($aRow))
  2445. {
  2446. throw new CoreException("No result for the single row query: '$sSQL'");
  2447. }
  2448. return $aRow;
  2449. }
  2450. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '')
  2451. {
  2452. self::_check_subclass($sClass);
  2453. // Compound objects: if available, get the final object class
  2454. //
  2455. if (!array_key_exists("finalclass", $aRow))
  2456. {
  2457. // Either this is a bug (forgot to specify a root class with a finalclass field
  2458. // Or this is the expected behavior, because the object is not made of several tables
  2459. }
  2460. elseif (empty($aRow["finalclass"]))
  2461. {
  2462. // The data is missing in the DB
  2463. // @#@ possible improvement: check that the class is valid !
  2464. $sRootClass = self::GetRootClass($sClass);
  2465. $sFinalClassField = self::DBGetClassField($sRootClass);
  2466. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  2467. }
  2468. else
  2469. {
  2470. // do the job for the real target class
  2471. $sClass = $aRow["finalclass"];
  2472. }
  2473. return new $sClass($aRow, $sClassAlias);
  2474. }
  2475. public static function GetObject($sClass, $iKey, $bMustBeFound = true)
  2476. {
  2477. self::_check_subclass($sClass);
  2478. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound);
  2479. if (empty($aRow))
  2480. {
  2481. return null;
  2482. }
  2483. return self::GetObjectByRow($sClass, $aRow);
  2484. }
  2485. public static function GetHyperLink($sTargetClass, $iKey)
  2486. {
  2487. if ($iKey < 0)
  2488. {
  2489. return "$sTargetClass: $iKey (invalid value)";
  2490. }
  2491. $oObj = self::GetObject($sTargetClass, $iKey, false);
  2492. if (is_null($oObj))
  2493. {
  2494. return "$sTargetClass: $iKey (not found)";
  2495. }
  2496. return $oObj->GetHyperLink();
  2497. }
  2498. public static function NewObject($sClass)
  2499. {
  2500. self::_check_subclass($sClass);
  2501. return new $sClass();
  2502. }
  2503. public static function GetNextKey($sClass)
  2504. {
  2505. $sRootClass = MetaModel::GetRootClass($sClass);
  2506. $sRootTable = MetaModel::DBGetTable($sRootClass);
  2507. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  2508. return $iNextKey;
  2509. }
  2510. public static function BulkDelete(DBObjectSearch $oFilter)
  2511. {
  2512. $sSQL = self::MakeDeleteQuery($oFilter);
  2513. CMDBSource::Query($sSQL);
  2514. }
  2515. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  2516. {
  2517. // $aValues is an array of $sAttCode => $value
  2518. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  2519. CMDBSource::Query($sSQL);
  2520. }
  2521. // Links
  2522. //
  2523. //
  2524. public static function EnumReferencedClasses($sClass)
  2525. {
  2526. self::_check_subclass($sClass);
  2527. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  2528. $aResult = array();
  2529. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  2530. {
  2531. if ($oAttDef->IsExternalKey())
  2532. {
  2533. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  2534. }
  2535. }
  2536. return $aResult;
  2537. }
  2538. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  2539. {
  2540. self::_check_subclass($sClass);
  2541. if ($bSkipLinkingClasses)
  2542. {
  2543. $aLinksClasses = self::EnumLinksClasses();
  2544. }
  2545. // 1-N links (referencing my class), array of sClass => array of sAttcode
  2546. $aResult = array();
  2547. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2548. {
  2549. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  2550. $aExtKeys = array();
  2551. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  2552. {
  2553. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2554. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  2555. {
  2556. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  2557. // Ok, I want this one
  2558. $aExtKeys[$sAttCode] = $oAttDef;
  2559. }
  2560. }
  2561. if (count($aExtKeys) != 0)
  2562. {
  2563. $aResult[$sSomeClass] = $aExtKeys;
  2564. }
  2565. }
  2566. return $aResult;
  2567. }
  2568. public static function EnumLinksClasses()
  2569. {
  2570. // Returns a flat array of classes having at least two external keys
  2571. $aResult = array();
  2572. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2573. {
  2574. $iExtKeyCount = 0;
  2575. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  2576. {
  2577. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2578. if ($oAttDef->IsExternalKey())
  2579. {
  2580. $iExtKeyCount++;
  2581. }
  2582. }
  2583. if ($iExtKeyCount >= 2)
  2584. {
  2585. $aResult[] = $sSomeClass;
  2586. }
  2587. }
  2588. return $aResult;
  2589. }
  2590. public static function EnumLinkingClasses($sClass = "")
  2591. {
  2592. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  2593. $aResult = array();
  2594. foreach (self::EnumLinksClasses() as $sSomeClass)
  2595. {
  2596. $aTargets = array();
  2597. $bFoundClass = false;
  2598. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  2599. {
  2600. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2601. if ($oAttDef->IsExternalKey())
  2602. {
  2603. $sRemoteClass = $oAttDef->GetTargetClass();
  2604. if (empty($sClass))
  2605. {
  2606. $aTargets[$sAttCode] = $sRemoteClass;
  2607. }
  2608. elseif ($sClass == $sRemoteClass)
  2609. {
  2610. $bFoundClass = true;
  2611. }
  2612. else
  2613. {
  2614. $aTargets[$sAttCode] = $sRemoteClass;
  2615. }
  2616. }
  2617. }
  2618. if (empty($sClass) || $bFoundClass)
  2619. {
  2620. $aResult[$sSomeClass] = $aTargets;
  2621. }
  2622. }
  2623. return $aResult;
  2624. }
  2625. public static function GetLinkLabel($sLinkClass, $sAttCode)
  2626. {
  2627. self::_check_subclass($sLinkClass);
  2628. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  2629. return self::GetLabel($sLinkClass, $sAttCode);
  2630. }
  2631. /**
  2632. * Replaces all the parameters by the values passed in the hash array
  2633. */
  2634. static public function ApplyParams($aInput, $aParams)
  2635. {
  2636. $aSearches = array();
  2637. $aReplacements = array();
  2638. foreach($aParams as $sSearch => $sReplace)
  2639. {
  2640. $aSearches[] = '$'.$sSearch.'$';
  2641. $aReplacements[] = $sReplace;
  2642. }
  2643. return str_replace($aSearches, $aReplacements, $aInput);
  2644. }
  2645. } // class MetaModel
  2646. // Standard attribute lists
  2647. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  2648. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  2649. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  2650. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  2651. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  2652. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  2653. ?>