metamodel.class.php 108 KB

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