metamodel.class.php 106 KB

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