metamodel.class.php 138 KB

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