metamodel.class.php 100 KB

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