metamodel.class.php 92 KB

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