metamodel.class.php 97 KB

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