metamodel.class.php 95 KB

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