metamodel.class.php 93 KB

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