metamodel.class.php 123 KB

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