metamodel.class.php 115 KB

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