metamodel.class.php 118 KB

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