metamodel.class.php 102 KB

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