metamodel.class.php 99 KB

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