metamodel.class.php 107 KB

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