metamodel.class.php 116 KB

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