metamodel.class.php 120 KB

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