metamodel.class.php 140 KB

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