metamodel.class.php 100 KB

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