metamodel.class.php 120 KB

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