metamodel.class.php 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. require_once(APPROOT.'core/modulehandler.class.inc.php');
  19. require_once(APPROOT.'core/querybuildercontext.class.inc.php');
  20. require_once(APPROOT.'core/querymodifier.class.inc.php');
  21. require_once(APPROOT.'core/metamodelmodifier.inc.php');
  22. require_once(APPROOT.'core/computing.inc.php');
  23. require_once(APPROOT.'core/relationgraph.class.inc.php');
  24. /**
  25. * Metamodel
  26. *
  27. * @copyright Copyright (C) 2010-2016 Combodo SARL
  28. * @license http://opensource.org/licenses/AGPL-3.0
  29. */
  30. /**
  31. * @package iTopORM
  32. */
  33. define('ENUM_PARENT_CLASSES_EXCLUDELEAF', 1);
  34. /**
  35. * @package iTopORM
  36. */
  37. define('ENUM_PARENT_CLASSES_ALL', 2);
  38. /**
  39. * Specifies that this attribute is visible/editable.... normal (default config)
  40. *
  41. * @package iTopORM
  42. */
  43. define('OPT_ATT_NORMAL', 0);
  44. /**
  45. * Specifies that this attribute is hidden in that state
  46. *
  47. * @package iTopORM
  48. */
  49. define('OPT_ATT_HIDDEN', 1);
  50. /**
  51. * Specifies that this attribute is not editable in that state
  52. *
  53. * @package iTopORM
  54. */
  55. define('OPT_ATT_READONLY', 2);
  56. /**
  57. * Specifieds that the attribute must be set (different than default value?) when arriving into that state
  58. *
  59. * @package iTopORM
  60. */
  61. define('OPT_ATT_MANDATORY', 4);
  62. /**
  63. * Specifies that the attribute must change when arriving into that state
  64. *
  65. * @package iTopORM
  66. */
  67. define('OPT_ATT_MUSTCHANGE', 8);
  68. /**
  69. * Specifies that the attribute must be proposed when arriving into that state
  70. *
  71. * @package iTopORM
  72. */
  73. define('OPT_ATT_MUSTPROMPT', 16);
  74. /**
  75. * Specifies that the attribute is in 'slave' mode compared to one data exchange task:
  76. * it should not be edited inside iTop anymore
  77. *
  78. * @package iTopORM
  79. */
  80. define('OPT_ATT_SLAVE', 32);
  81. /**
  82. * DB Engine -should be moved into CMDBSource
  83. *
  84. * @package iTopORM
  85. */
  86. define('MYSQL_ENGINE', 'innodb');
  87. //define('MYSQL_ENGINE', 'myisam');
  88. /**
  89. * (API) The objects definitions as well as their mapping to the database
  90. *
  91. * @package iTopORM
  92. */
  93. abstract class MetaModel
  94. {
  95. ///////////////////////////////////////////////////////////////////////////
  96. //
  97. // STATIC Members
  98. //
  99. ///////////////////////////////////////////////////////////////////////////
  100. private static $m_bTraceSourceFiles = false;
  101. private static $m_aClassToFile = array();
  102. public static function GetClassFiles()
  103. {
  104. return self::$m_aClassToFile;
  105. }
  106. // Purpose: workaround the following limitation = PHP5 does not allow to know the class (derived from the current one)
  107. // from which a static function is called (__CLASS__ and self are interpreted during parsing)
  108. private static function GetCallersPHPClass($sExpectedFunctionName = null, $bRecordSourceFile = false)
  109. {
  110. //var_dump(debug_backtrace());
  111. $aBacktrace = debug_backtrace();
  112. // $aBacktrace[0] is where we are
  113. // $aBacktrace[1] is the caller of GetCallersPHPClass
  114. // $aBacktrace[1] is the info we want
  115. if (!empty($sExpectedFunctionName))
  116. {
  117. assert('$aBacktrace[2]["function"] == $sExpectedFunctionName');
  118. }
  119. if ($bRecordSourceFile)
  120. {
  121. self::$m_aClassToFile[$aBacktrace[2]["class"]] = $aBacktrace[1]["file"];
  122. }
  123. return $aBacktrace[2]["class"];
  124. }
  125. // Static init -why and how it works
  126. //
  127. // We found the following limitations:
  128. //- it is not possible to define non scalar constants
  129. //- it is not possible to declare a static variable as '= new myclass()'
  130. // Then we had do propose this model, in which a derived (non abstract)
  131. // class should implement Init(), to call InheritAttributes or AddAttribute.
  132. private static function _check_subclass($sClass)
  133. {
  134. // See also IsValidClass()... ???? #@#
  135. // class is mandatory
  136. // (it is not possible to guess it when called as myderived::...)
  137. if (!array_key_exists($sClass, self::$m_aClassParams))
  138. {
  139. throw new CoreException("Unknown class '$sClass'");
  140. }
  141. }
  142. public static function static_var_dump()
  143. {
  144. var_dump(get_class_vars(__CLASS__));
  145. }
  146. private static $m_oConfig = null;
  147. protected static $m_aModulesParameters = array();
  148. private static $m_bSkipCheckToWrite = false;
  149. private static $m_bSkipCheckExtKeys = false;
  150. private static $m_bUseAPCCache = false;
  151. private static $m_bLogIssue = false;
  152. private static $m_bLogNotification = false;
  153. private static $m_bLogWebService = false;
  154. public static function SkipCheckToWrite()
  155. {
  156. return self::$m_bSkipCheckToWrite;
  157. }
  158. public static function SkipCheckExtKeys()
  159. {
  160. return self::$m_bSkipCheckExtKeys;
  161. }
  162. public static function IsLogEnabledIssue()
  163. {
  164. return self::$m_bLogIssue;
  165. }
  166. public static function IsLogEnabledNotification()
  167. {
  168. return self::$m_bLogNotification;
  169. }
  170. public static function IsLogEnabledWebService()
  171. {
  172. return self::$m_bLogWebService;
  173. }
  174. private static $m_sDBName = "";
  175. private static $m_sTablePrefix = ""; // table prefix for the current application instance (allow several applications on the same DB)
  176. private static $m_Category2Class = array();
  177. private static $m_aRootClasses = array(); // array of "classname" => "rootclass"
  178. private static $m_aParentClasses = array(); // array of ("classname" => array of "parentclass")
  179. private static $m_aChildClasses = array(); // array of ("classname" => array of "childclass")
  180. private static $m_aClassParams = array(); // array of ("classname" => array of class information)
  181. private static $m_aHighlightScales = array(); // array of ("classname" => array of highlightscale information)
  182. static public function GetParentPersistentClass($sRefClass)
  183. {
  184. $sClass = get_parent_class($sRefClass);
  185. if (!$sClass) return '';
  186. if ($sClass == 'DBObject') return ''; // Warning: __CLASS__ is lower case in my version of PHP
  187. // Note: the UI/business model may implement pure PHP classes (intermediate layers)
  188. if (array_key_exists($sClass, self::$m_aClassParams))
  189. {
  190. return $sClass;
  191. }
  192. return self::GetParentPersistentClass($sClass);
  193. }
  194. final static public function GetName($sClass)
  195. {
  196. self::_check_subclass($sClass);
  197. $sStringCode = 'Class:'.$sClass;
  198. return Dict::S($sStringCode, str_replace('_', ' ', $sClass));
  199. }
  200. final static public function GetName_Obsolete($sClass)
  201. {
  202. // Written for compatibility with a data model written prior to version 0.9.1
  203. self::_check_subclass($sClass);
  204. if (array_key_exists('name', self::$m_aClassParams[$sClass]))
  205. {
  206. return self::$m_aClassParams[$sClass]['name'];
  207. }
  208. else
  209. {
  210. return self::GetName($sClass);
  211. }
  212. }
  213. final static public function GetClassFromLabel($sClassLabel, $bCaseSensitive = true)
  214. {
  215. foreach(self::GetClasses() as $sClass)
  216. {
  217. if ($bCaseSensitive)
  218. {
  219. if (self::GetName($sClass) == $sClassLabel)
  220. {
  221. return $sClass;
  222. }
  223. }
  224. else
  225. {
  226. if (strcasecmp(self::GetName($sClass), $sClassLabel) == 0)
  227. {
  228. return $sClass;
  229. }
  230. }
  231. }
  232. return null;
  233. }
  234. final static public function GetCategory($sClass)
  235. {
  236. self::_check_subclass($sClass);
  237. return self::$m_aClassParams[$sClass]["category"];
  238. }
  239. final static public function HasCategory($sClass, $sCategory)
  240. {
  241. self::_check_subclass($sClass);
  242. return (strpos(self::$m_aClassParams[$sClass]["category"], $sCategory) !== false);
  243. }
  244. final static public function GetClassDescription($sClass)
  245. {
  246. self::_check_subclass($sClass);
  247. $sStringCode = 'Class:'.$sClass.'+';
  248. return Dict::S($sStringCode, '');
  249. }
  250. final static public function GetClassDescription_Obsolete($sClass)
  251. {
  252. // Written for compatibility with a data model written prior to version 0.9.1
  253. self::_check_subclass($sClass);
  254. if (array_key_exists('description', self::$m_aClassParams[$sClass]))
  255. {
  256. return self::$m_aClassParams[$sClass]['description'];
  257. }
  258. else
  259. {
  260. return self::GetClassDescription($sClass);
  261. }
  262. }
  263. final static public function GetClassIcon($sClass, $bImgTag = true, $sMoreStyles = '')
  264. {
  265. self::_check_subclass($sClass);
  266. $sIcon = '';
  267. if (array_key_exists('icon', self::$m_aClassParams[$sClass]))
  268. {
  269. $sIcon = self::$m_aClassParams[$sClass]['icon'];
  270. }
  271. if (strlen($sIcon) == 0)
  272. {
  273. $sParentClass = self::GetParentPersistentClass($sClass);
  274. if (strlen($sParentClass) > 0)
  275. {
  276. return self::GetClassIcon($sParentClass, $bImgTag, $sMoreStyles);
  277. }
  278. }
  279. $sIcon = str_replace('/modules/', '/env-'.utils::GetCurrentEnvironment().'/', $sIcon); // Support of pre-2.0 modules
  280. if ($bImgTag && ($sIcon != ''))
  281. {
  282. $sIcon = "<img src=\"$sIcon\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  283. }
  284. return $sIcon;
  285. }
  286. final static public function IsAutoIncrementKey($sClass)
  287. {
  288. self::_check_subclass($sClass);
  289. return (self::$m_aClassParams[$sClass]["key_type"] == "autoincrement");
  290. }
  291. final static public function GetNameSpec($sClass)
  292. {
  293. self::_check_subclass($sClass);
  294. $nameRawSpec = self::$m_aClassParams[$sClass]["name_attcode"];
  295. if (is_array($nameRawSpec))
  296. {
  297. $sFormat = Dict::S("Class:$sClass/Name", '');
  298. if (strlen($sFormat) == 0)
  299. {
  300. // Default to "%1$s %2$s..."
  301. for($i = 1 ; $i <= count($nameRawSpec) ; $i++)
  302. {
  303. if (empty($sFormat))
  304. {
  305. $sFormat .= '%'.$i.'$s';
  306. }
  307. else
  308. {
  309. $sFormat .= ' %'.$i.'$s';
  310. }
  311. }
  312. }
  313. return array($sFormat, $nameRawSpec);
  314. }
  315. elseif (empty($nameRawSpec))
  316. {
  317. //return array($sClass.' %s', array('id'));
  318. return array($sClass, array());
  319. }
  320. else
  321. {
  322. // string -> attcode
  323. return array('%1$s', array($nameRawSpec));
  324. }
  325. }
  326. /**
  327. * Get the friendly name expression for a given class
  328. */
  329. final static public function GetNameExpression($sClass)
  330. {
  331. $aNameSpec = self::GetNameSpec($sClass);
  332. $sFormat = $aNameSpec[0];
  333. $aAttributes = $aNameSpec[1];
  334. $aPieces = preg_split('/%([0-9])\\$s/', $sFormat, -1, PREG_SPLIT_DELIM_CAPTURE);
  335. $aExpressions = array();
  336. foreach($aPieces as $i => $sPiece)
  337. {
  338. if ($i & 1)
  339. {
  340. // $i is ODD - sPiece is a delimiter
  341. //
  342. $iReplacement = (int)$sPiece - 1;
  343. if (isset($aAttributes[$iReplacement]))
  344. {
  345. $sAttCode = $aAttributes[$iReplacement];
  346. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  347. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  348. {
  349. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  350. $sClassOfAttribute = self::GetAttributeOrigin($sClass, $sKeyAttCode);
  351. }
  352. else
  353. {
  354. $sClassOfAttribute = self::GetAttributeOrigin($sClass, $sAttCode);
  355. }
  356. $aExpressions[] = new FieldExpression($sAttCode, $sClassOfAttribute);
  357. }
  358. }
  359. else
  360. {
  361. // $i is EVEN - sPiece is a literal
  362. //
  363. if (strlen($sPiece) > 0)
  364. {
  365. $aExpressions[] = new ScalarExpression($sPiece);
  366. }
  367. }
  368. }
  369. $oNameExpr = new CharConcatExpression($aExpressions);
  370. return $oNameExpr;
  371. }
  372. /**
  373. * Returns the friendly name IIF it is equivalent to a single attribute
  374. */
  375. final static public function GetFriendlyNameAttributeCode($sClass)
  376. {
  377. $aNameSpec = self::GetNameSpec($sClass);
  378. $sFormat = trim($aNameSpec[0]);
  379. $aAttributes = $aNameSpec[1];
  380. if (($sFormat != '') && ($sFormat != '%1$s'))
  381. {
  382. return null;
  383. }
  384. if (count($aAttributes) > 1)
  385. {
  386. return null;
  387. }
  388. return reset($aAttributes);
  389. }
  390. final static public function GetStateAttributeCode($sClass)
  391. {
  392. self::_check_subclass($sClass);
  393. return self::$m_aClassParams[$sClass]["state_attcode"];
  394. }
  395. final static public function GetDefaultState($sClass)
  396. {
  397. $sDefaultState = '';
  398. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  399. if (!empty($sStateAttrCode))
  400. {
  401. $oStateAttrDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  402. $sDefaultState = $oStateAttrDef->GetDefaultValue();
  403. }
  404. return $sDefaultState;
  405. }
  406. final static public function GetReconcKeys($sClass)
  407. {
  408. self::_check_subclass($sClass);
  409. return self::$m_aClassParams[$sClass]["reconc_keys"];
  410. }
  411. final static public function GetDisplayTemplate($sClass)
  412. {
  413. self::_check_subclass($sClass);
  414. return array_key_exists("display_template", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["display_template"]: '';
  415. }
  416. final static public function GetOrderByDefault($sClass, $bOnlyDeclared = false)
  417. {
  418. self::_check_subclass($sClass);
  419. $aOrderBy = array_key_exists("order_by_default", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["order_by_default"]: array();
  420. if ($bOnlyDeclared)
  421. {
  422. // Used to reverse engineer the declaration of the data model
  423. return $aOrderBy;
  424. }
  425. else
  426. {
  427. if (count($aOrderBy) == 0)
  428. {
  429. $aOrderBy['friendlyname'] = true;
  430. }
  431. return $aOrderBy;
  432. }
  433. }
  434. final static public function GetAttributeOrigin($sClass, $sAttCode)
  435. {
  436. self::_check_subclass($sClass);
  437. return self::$m_aAttribOrigins[$sClass][$sAttCode];
  438. }
  439. final static public function GetPrerequisiteAttributes($sClass, $sAttCode)
  440. {
  441. self::_check_subclass($sClass);
  442. $oAtt = self::GetAttributeDef($sClass, $sAttCode);
  443. // Temporary implementation: later, we might be able to compute
  444. // the dependencies, based on the attributes definition
  445. // (allowed values and default values)
  446. // Even non-writable attributes (like ExternalFields) can now have Prerequisites
  447. return $oAtt->GetPrerequisiteAttributes();
  448. }
  449. /**
  450. * Find all attributes that depend on the specified one (reverse of GetPrerequisiteAttributes)
  451. * @param string $sClass Name of the class
  452. * @param string $sAttCode Code of the attributes
  453. * @return Array List of attribute codes that depend on the given attribute, empty array if none.
  454. */
  455. final static public function GetDependentAttributes($sClass, $sAttCode)
  456. {
  457. $aResults = array();
  458. self::_check_subclass($sClass);
  459. foreach (self::ListAttributeDefs($sClass) as $sDependentAttCode=>$void)
  460. {
  461. $aPrerequisites = self::GetPrerequisiteAttributes($sClass, $sDependentAttCode);
  462. if (in_array($sAttCode, $aPrerequisites))
  463. {
  464. $aResults[] = $sDependentAttCode;
  465. }
  466. }
  467. return $aResults;
  468. }
  469. // #@# restore to private ?
  470. final static public function DBGetTable($sClass, $sAttCode = null)
  471. {
  472. self::_check_subclass($sClass);
  473. if (empty($sAttCode) || ($sAttCode == "id"))
  474. {
  475. $sTableRaw = self::$m_aClassParams[$sClass]["db_table"];
  476. if (empty($sTableRaw))
  477. {
  478. // return an empty string whenever the table is undefined, meaning that there is no table associated to this 'abstract' class
  479. return '';
  480. }
  481. else
  482. {
  483. // If the format changes here, do not forget to update the setup index page (detection of installed modules)
  484. return self::$m_sTablePrefix.$sTableRaw;
  485. }
  486. }
  487. // This attribute has been inherited (compound objects)
  488. return self::DBGetTable(self::$m_aAttribOrigins[$sClass][$sAttCode]);
  489. }
  490. final static public function DBGetView($sClass)
  491. {
  492. return self::$m_sTablePrefix."view_".$sClass;
  493. }
  494. final static public function DBEnumTables()
  495. {
  496. // This API does not rely on our capability to query the DB and retrieve
  497. // the list of existing tables
  498. // Rather, it uses the list of expected tables, corresponding to the data model
  499. $aTables = array();
  500. foreach (self::GetClasses() as $sClass)
  501. {
  502. if (!self::HasTable($sClass)) continue;
  503. $sTable = self::DBGetTable($sClass);
  504. // Could be completed later with all the classes that are using a given table
  505. if (!array_key_exists($sTable, $aTables))
  506. {
  507. $aTables[$sTable] = array();
  508. }
  509. $aTables[$sTable][] = $sClass;
  510. }
  511. return $aTables;
  512. }
  513. final static public function DBGetIndexes($sClass)
  514. {
  515. self::_check_subclass($sClass);
  516. if (isset(self::$m_aClassParams[$sClass]['indexes']))
  517. {
  518. return self::$m_aClassParams[$sClass]['indexes'];
  519. }
  520. else
  521. {
  522. return array();
  523. }
  524. }
  525. final static public function DBGetKey($sClass)
  526. {
  527. self::_check_subclass($sClass);
  528. return self::$m_aClassParams[$sClass]["db_key_field"];
  529. }
  530. final static public function DBGetClassField($sClass)
  531. {
  532. self::_check_subclass($sClass);
  533. return self::$m_aClassParams[$sClass]["db_finalclass_field"];
  534. }
  535. final static public function IsStandaloneClass($sClass)
  536. {
  537. self::_check_subclass($sClass);
  538. if (count(self::$m_aChildClasses[$sClass]) == 0)
  539. {
  540. if (count(self::$m_aParentClasses[$sClass]) == 0)
  541. {
  542. return true;
  543. }
  544. }
  545. return false;
  546. }
  547. final static public function IsParentClass($sParentClass, $sChildClass)
  548. {
  549. self::_check_subclass($sChildClass);
  550. self::_check_subclass($sParentClass);
  551. if (in_array($sParentClass, self::$m_aParentClasses[$sChildClass])) return true;
  552. if ($sChildClass == $sParentClass) return true;
  553. return false;
  554. }
  555. final static public function IsSameFamilyBranch($sClassA, $sClassB)
  556. {
  557. self::_check_subclass($sClassA);
  558. self::_check_subclass($sClassB);
  559. if (in_array($sClassA, self::$m_aParentClasses[$sClassB])) return true;
  560. if (in_array($sClassB, self::$m_aParentClasses[$sClassA])) return true;
  561. if ($sClassA == $sClassB) return true;
  562. return false;
  563. }
  564. final static public function IsSameFamily($sClassA, $sClassB)
  565. {
  566. self::_check_subclass($sClassA);
  567. self::_check_subclass($sClassB);
  568. return (self::GetRootClass($sClassA) == self::GetRootClass($sClassB));
  569. }
  570. // Attributes of a given class may contain attributes defined in a parent class
  571. // - Some attributes are a copy of the definition
  572. // - Some attributes correspond to the upper class table definition (compound objects)
  573. // (see also filters definition)
  574. private static $m_aAttribDefs = array(); // array of ("classname" => array of attributes)
  575. private static $m_aAttribOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  576. private static $m_aExtKeyFriends = array(); // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  577. private static $m_aIgnoredAttributes = array(); //array of ("classname" => array of ("attcode"))
  578. private static $m_aEnumToMeta = array(); // array of ("classname" => array of ("attcode" => array of ("metaattcode" => oMetaAttDef))
  579. final static public function ListAttributeDefs($sClass)
  580. {
  581. self::_check_subclass($sClass);
  582. return self::$m_aAttribDefs[$sClass];
  583. }
  584. final public static function GetAttributesList($sClass)
  585. {
  586. self::_check_subclass($sClass);
  587. return array_keys(self::$m_aAttribDefs[$sClass]);
  588. }
  589. final public static function GetFiltersList($sClass)
  590. {
  591. self::_check_subclass($sClass);
  592. return array_keys(self::$m_aFilterDefs[$sClass]);
  593. }
  594. final public static function GetKeysList($sClass)
  595. {
  596. self::_check_subclass($sClass);
  597. $aExtKeys = array();
  598. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  599. {
  600. if ($oAttDef->IsExternalKey())
  601. {
  602. $aExtKeys[] = $sAttCode;
  603. }
  604. }
  605. return $aExtKeys;
  606. }
  607. final static public function IsValidKeyAttCode($sClass, $sAttCode)
  608. {
  609. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  610. if (!array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass])) return false;
  611. return (self::$m_aAttribDefs[$sClass][$sAttCode]->IsExternalKey());
  612. }
  613. final static public function IsValidAttCode($sClass, $sAttCode, $bExtended = false)
  614. {
  615. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  616. if ($bExtended)
  617. {
  618. if (($iPos = strpos($sAttCode, '->')) === false)
  619. {
  620. $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
  621. }
  622. else
  623. {
  624. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  625. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  626. if (MetaModel::IsValidAttCode($sClass, $sExtKeyAttCode))
  627. {
  628. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  629. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  630. $bRes = MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode, true);
  631. }
  632. else
  633. {
  634. $bRes = false;
  635. }
  636. }
  637. }
  638. else
  639. {
  640. $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
  641. }
  642. return $bRes;
  643. }
  644. final static public function IsAttributeOrigin($sClass, $sAttCode)
  645. {
  646. return (self::$m_aAttribOrigins[$sClass][$sAttCode] == $sClass);
  647. }
  648. final static public function IsValidFilterCode($sClass, $sFilterCode)
  649. {
  650. if (!array_key_exists($sClass, self::$m_aFilterDefs)) return false;
  651. return (array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]));
  652. }
  653. public static function IsValidClass($sClass)
  654. {
  655. return (array_key_exists($sClass, self::$m_aAttribDefs));
  656. }
  657. public static function IsValidObject($oObject)
  658. {
  659. if (!is_object($oObject)) return false;
  660. return (self::IsValidClass(get_class($oObject)));
  661. }
  662. public static function IsReconcKey($sClass, $sAttCode)
  663. {
  664. return (in_array($sAttCode, self::GetReconcKeys($sClass)));
  665. }
  666. final static public function GetAttributeDef($sClass, $sAttCode)
  667. {
  668. self::_check_subclass($sClass);
  669. if (isset(self::$m_aAttribDefs[$sClass][$sAttCode]))
  670. {
  671. return self::$m_aAttribDefs[$sClass][$sAttCode];
  672. }
  673. elseif (($iPos = strpos($sAttCode, '->')) !== false)
  674. {
  675. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  676. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  677. $oKeyAttDef = self::GetAttributeDef($sClass, $sExtKeyAttCode);
  678. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  679. return self::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  680. }
  681. else
  682. {
  683. throw new Exception("Unknown attribute $sAttCode from class $sClass");
  684. }
  685. }
  686. final static public function GetExternalKeys($sClass)
  687. {
  688. $aExtKeys = array();
  689. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  690. {
  691. if ($oAtt->IsExternalKey())
  692. {
  693. $aExtKeys[$sAttCode] = $oAtt;
  694. }
  695. }
  696. return $aExtKeys;
  697. }
  698. final static public function GetLinkedSets($sClass)
  699. {
  700. $aLinkedSets = array();
  701. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  702. {
  703. if (is_subclass_of($oAtt, 'AttributeLinkedSet'))
  704. {
  705. $aLinkedSets[$sAttCode] = $oAtt;
  706. }
  707. }
  708. return $aLinkedSets;
  709. }
  710. final static public function GetExternalFields($sClass, $sKeyAttCode)
  711. {
  712. static $aExtFields = array();
  713. if (!isset($aExtFields[$sClass][$sKeyAttCode]))
  714. {
  715. $aExtFields[$sClass][$sKeyAttCode] = array();
  716. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  717. {
  718. if ($oAtt->IsExternalField() && ($oAtt->GetKeyAttCode() == $sKeyAttCode))
  719. {
  720. $aExtFields[$sClass][$sKeyAttCode][$oAtt->GetExtAttCode()] = $oAtt;
  721. }
  722. }
  723. }
  724. return $aExtFields[$sClass][$sKeyAttCode];
  725. }
  726. final static public function FindExternalField($sClass, $sKeyAttCode, $sRemoteAttCode)
  727. {
  728. $aExtFields = self::GetExternalFields($sClass, $sKeyAttCode);
  729. if (isset($aExtFields[$sRemoteAttCode]))
  730. {
  731. return $aExtFields[$sRemoteAttCode];
  732. }
  733. else
  734. {
  735. return null;
  736. }
  737. }
  738. final static public function GetExtKeyFriends($sClass, $sExtKeyAttCode)
  739. {
  740. if (array_key_exists($sExtKeyAttCode, self::$m_aExtKeyFriends[$sClass]))
  741. {
  742. return self::$m_aExtKeyFriends[$sClass][$sExtKeyAttCode];
  743. }
  744. else
  745. {
  746. return array();
  747. }
  748. }
  749. protected static $m_aTrackForwardCache = array();
  750. /**
  751. * List external keys for which there is a LinkSet (direct or indirect) on the other end
  752. * For those external keys, a change will have a special meaning on the other end
  753. * in term of change tracking
  754. */
  755. final static public function GetTrackForwardExternalKeys($sClass)
  756. {
  757. if (!isset(self::$m_aTrackForwardCache[$sClass]))
  758. {
  759. $aRes = array();
  760. foreach (MetaModel::GetExternalKeys($sClass) as $sAttCode => $oAttDef)
  761. {
  762. $sRemoteClass = $oAttDef->GetTargetClass();
  763. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  764. {
  765. if (!$oRemoteAttDef->IsLinkSet()) continue;
  766. if (!is_subclass_of($sClass, $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $sClass) continue;
  767. if ($oRemoteAttDef->GetExtKeyToMe() != $sAttCode) continue;
  768. $aRes[$sAttCode] = $oRemoteAttDef;
  769. }
  770. }
  771. self::$m_aTrackForwardCache[$sClass] = $aRes;
  772. }
  773. return self::$m_aTrackForwardCache[$sClass];
  774. }
  775. final static public function ListMetaAttributes($sClass, $sAttCode)
  776. {
  777. if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode]))
  778. {
  779. $aRet = self::$m_aEnumToMeta[$sClass][$sAttCode];
  780. }
  781. else
  782. {
  783. $aRet = array();
  784. }
  785. return $aRet;
  786. }
  787. /**
  788. * Get the attribute label
  789. * @param string sClass Persistent class
  790. * @param string sAttCodeEx Extended attribute code: attcode[->attcode]
  791. * @param bool $bShowMandatory If true, add a star character (at the end or before the ->) to show that the field is mandatory
  792. * @return string A user friendly format of the string: AttributeName or AttributeName->ExtAttributeName
  793. */
  794. public static function GetLabel($sClass, $sAttCodeEx, $bShowMandatory = false)
  795. {
  796. $sLabel = '';
  797. if (($iPos = strpos($sAttCodeEx, '->')) === false)
  798. {
  799. if ($sAttCodeEx == 'id')
  800. {
  801. $sLabel = Dict::S('UI:CSVImport:idField');
  802. }
  803. else
  804. {
  805. $oAttDef = self::GetAttributeDef($sClass, $sAttCodeEx);
  806. $sMandatory = ($bShowMandatory && !$oAttDef->IsNullAllowed()) ? '*' : '';
  807. $sLabel = $oAttDef->GetLabel().$sMandatory;
  808. }
  809. }
  810. else
  811. {
  812. $sExtKeyAttCode = substr($sAttCodeEx, 0, $iPos);
  813. $sRemoteAttCode = substr($sAttCodeEx, $iPos + 2);
  814. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  815. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  816. // Recurse
  817. $sLabel = self::GetLabel($sClass, $sExtKeyAttCode).'->'.self::GetLabel($sRemoteClass, $sRemoteAttCode);
  818. }
  819. return $sLabel;
  820. }
  821. public static function GetDescription($sClass, $sAttCode)
  822. {
  823. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  824. if ($oAttDef) return $oAttDef->GetDescription();
  825. return "";
  826. }
  827. // Filters of a given class may contain filters defined in a parent class
  828. // - Some filters are a copy of the definition
  829. // - Some filters correspond to the upper class table definition (compound objects)
  830. // (see also attributes definition)
  831. private static $m_aFilterDefs = array(); // array of ("classname" => array filterdef)
  832. private static $m_aFilterOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  833. public static function GetClassFilterDefs($sClass)
  834. {
  835. self::_check_subclass($sClass);
  836. return self::$m_aFilterDefs[$sClass];
  837. }
  838. final static public function GetClassFilterDef($sClass, $sFilterCode)
  839. {
  840. self::_check_subclass($sClass);
  841. if (!array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]))
  842. {
  843. throw new CoreException("Unknown filter code '$sFilterCode' for class '$sClass'");
  844. }
  845. return self::$m_aFilterDefs[$sClass][$sFilterCode];
  846. }
  847. public static function GetFilterLabel($sClass, $sFilterCode)
  848. {
  849. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  850. if ($oFilter) return $oFilter->GetLabel();
  851. return "";
  852. }
  853. public static function GetFilterDescription($sClass, $sFilterCode)
  854. {
  855. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  856. if ($oFilter) return $oFilter->GetDescription();
  857. return "";
  858. }
  859. // returns an array of opcode=>oplabel (e.g. "differs from")
  860. public static function GetFilterOperators($sClass, $sFilterCode)
  861. {
  862. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  863. if ($oFilter) return $oFilter->GetOperators();
  864. return array();
  865. }
  866. // returns an opcode
  867. public static function GetFilterLooseOperator($sClass, $sFilterCode)
  868. {
  869. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  870. if ($oFilter) return $oFilter->GetLooseOperator();
  871. return array();
  872. }
  873. public static function GetFilterOpDescription($sClass, $sFilterCode, $sOpCode)
  874. {
  875. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  876. if ($oFilter) return $oFilter->GetOpDescription($sOpCode);
  877. return "";
  878. }
  879. public static function GetFilterHTMLInput($sFilterCode)
  880. {
  881. return "<INPUT name=\"$sFilterCode\">";
  882. }
  883. // Lists of attributes/search filters
  884. //
  885. private static $m_aListInfos = array(); // array of ("listcode" => various info on the list, common to every classes)
  886. private static $m_aListData = array(); // array of ("classname" => array of "listcode" => list)
  887. // list may be an array of attcode / fltcode
  888. // list may be an array of "groupname" => (array of attcode / fltcode)
  889. public static function EnumZLists()
  890. {
  891. return array_keys(self::$m_aListInfos);
  892. }
  893. final static public function GetZListInfo($sListCode)
  894. {
  895. return self::$m_aListInfos[$sListCode];
  896. }
  897. public static function GetZListItems($sClass, $sListCode)
  898. {
  899. if (array_key_exists($sClass, self::$m_aListData))
  900. {
  901. if (array_key_exists($sListCode, self::$m_aListData[$sClass]))
  902. {
  903. return self::$m_aListData[$sClass][$sListCode];
  904. }
  905. }
  906. $sParentClass = self::GetParentPersistentClass($sClass);
  907. if (empty($sParentClass)) return array(); // nothing for the mother of all classes
  908. // Dig recursively
  909. return self::GetZListItems($sParentClass, $sListCode);
  910. }
  911. public static function IsAttributeInZList($sClass, $sListCode, $sAttCodeOrFltCode, $sGroup = null)
  912. {
  913. $aZList = self::FlattenZlist(self::GetZListItems($sClass, $sListCode));
  914. if (!$sGroup)
  915. {
  916. return (in_array($sAttCodeOrFltCode, $aZList));
  917. }
  918. return (in_array($sAttCodeOrFltCode, $aZList[$sGroup]));
  919. }
  920. //
  921. // Relations
  922. //
  923. private static $m_aRelationInfos = array(); // array of ("relcode" => various info on the list, common to every classes)
  924. /**
  925. * TO BE DEPRECATED: use EnumRelationsEx instead
  926. * @param string $sClass
  927. * @return multitype:string unknown |Ambigous <string, multitype:>
  928. */
  929. public static function EnumRelations($sClass = '')
  930. {
  931. $aResult = array_keys(self::$m_aRelationInfos);
  932. if (!empty($sClass))
  933. {
  934. // Return only the relations that have a meaning (i.e. for which at least one query is defined)
  935. // for the specified class
  936. $aClassRelations = array();
  937. foreach($aResult as $sRelCode)
  938. {
  939. $aQueriesDown = self::EnumRelationQueries($sClass, $sRelCode);
  940. if (count($aQueriesDown) > 0)
  941. {
  942. $aClassRelations[] = $sRelCode;
  943. }
  944. // Temporary patch: until the impact analysis GUI gets rewritten,
  945. // let's consider that "depends on" is equivalent to "impacts/up"
  946. // The current patch has been implemented in DBObject and MetaModel
  947. if ($sRelCode == 'impacts')
  948. {
  949. $aQueriesUp = self::EnumRelationQueries($sClass, 'impacts', false);
  950. if (count($aQueriesUp) > 0)
  951. {
  952. $aClassRelations[] = 'depends on';
  953. }
  954. }
  955. }
  956. return $aClassRelations;
  957. }
  958. // Temporary patch: until the impact analysis GUI gets rewritten,
  959. // let's consider that "depends on" is equivalent to "impacts/up"
  960. // The current patch has been implemented in DBObject and MetaModel
  961. if (in_array('impacts', $aResult))
  962. {
  963. $aResult[] = 'depends on';
  964. }
  965. return $aResult;
  966. }
  967. public static function EnumRelationsEx($sClass)
  968. {
  969. $aRelationInfo = array_keys(self::$m_aRelationInfos);
  970. // Return only the relations that have a meaning (i.e. for which at least one query is defined)
  971. // for the specified class
  972. $aClassRelations = array();
  973. foreach($aRelationInfo as $sRelCode)
  974. {
  975. $aQueriesDown = self::EnumRelationQueries($sClass, $sRelCode, true /* Down */);
  976. if (count($aQueriesDown) > 0)
  977. {
  978. $aClassRelations[$sRelCode]['down'] = self::GetRelationLabel($sRelCode, true);
  979. }
  980. $aQueriesUp = self::EnumRelationQueries($sClass, $sRelCode, false /* Up */);
  981. if (count($aQueriesUp) > 0)
  982. {
  983. $aClassRelations[$sRelCode]['up'] = self::GetRelationLabel($sRelCode, false);
  984. }
  985. }
  986. return $aClassRelations;
  987. }
  988. final static public function GetRelationDescription($sRelCode)
  989. {
  990. return Dict::S("Relation:$sRelCode/Description");
  991. }
  992. final static public function GetRelationLabel($sRelCode, $bDown = true)
  993. {
  994. if ($bDown)
  995. {
  996. // The legacy convention is confusing with regard to the way we have conceptualized the relations:
  997. // In the former representation, the main stream was named after "up"
  998. // Now, the relation from A to B says that something is transmitted from A to B, thus going DOWNstream as described in a petri net.
  999. $sKey = "Relation:$sRelCode/DownStream";
  1000. $sLegacy = Dict::S("Relation:$sRelCode/VerbUp", $sKey);
  1001. }
  1002. else
  1003. {
  1004. $sKey = "Relation:$sRelCode/UpStream";
  1005. $sLegacy = Dict::S("Relation:$sRelCode/VerbDown", $sKey);
  1006. }
  1007. $sRet = Dict::S($sKey, $sLegacy);
  1008. return $sRet;
  1009. }
  1010. protected static function ComputeRelationQueries($sRelCode)
  1011. {
  1012. $bHasLegacy = false;
  1013. $aQueries = array();
  1014. foreach (self::GetClasses() as $sClass)
  1015. {
  1016. $aQueries[$sClass]['down'] = array();
  1017. if (!array_key_exists('up', $aQueries[$sClass]))
  1018. {
  1019. $aQueries[$sClass]['up'] = array();
  1020. }
  1021. $aNeighboursDown = call_user_func_array(array($sClass, 'GetRelationQueriesEx'), array($sRelCode));
  1022. // Translate attributes into queries (new style of spec only)
  1023. foreach($aNeighboursDown as $sNeighbourId => $aNeighbourData)
  1024. {
  1025. $aNeighbourData['sFromClass'] = $aNeighbourData['sDefinedInClass'];
  1026. try
  1027. {
  1028. if (strlen($aNeighbourData['sQueryDown']) == 0)
  1029. {
  1030. $oAttDef = self::GetAttributeDef($sClass, $aNeighbourData['sAttribute']);
  1031. if ($oAttDef instanceof AttributeExternalKey)
  1032. {
  1033. $sTargetClass = $oAttDef->GetTargetClass();
  1034. $aNeighbourData['sToClass'] = $sTargetClass;
  1035. $aNeighbourData['sQueryDown'] = 'SELECT '.$sTargetClass.' AS o WHERE o.id = :this->'.$aNeighbourData['sAttribute'];
  1036. $aNeighbourData['sQueryUp'] = 'SELECT '.$aNeighbourData['sFromClass'].' AS o WHERE o.'.$aNeighbourData['sAttribute'].' = :this->id';
  1037. }
  1038. elseif ($oAttDef instanceof AttributeLinkedSet)
  1039. {
  1040. $sLinkedClass = $oAttDef->GetLinkedClass();
  1041. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  1042. if ($oAttDef->IsIndirect())
  1043. {
  1044. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  1045. $oRemoteAttDef = self::GetAttributeDef($sLinkedClass, $sExtKeyToRemote);
  1046. $sRemoteClass = $oRemoteAttDef->GetTargetClass();
  1047. $aNeighbourData['sToClass'] = $sRemoteClass;
  1048. $aNeighbourData['sQueryDown'] = "SELECT $sRemoteClass AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToRemote = o.id WHERE lnk.$sExtKeyToMe = :this->id";
  1049. $aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o JOIN $sLinkedClass AS lnk ON lnk.$sExtKeyToMe = o.id WHERE lnk.$sExtKeyToRemote = :this->id";
  1050. }
  1051. else
  1052. {
  1053. $aNeighbourData['sToClass'] = $sLinkedClass;
  1054. $aNeighbourData['sQueryDown'] = "SELECT $sLinkedClass AS o WHERE o.$sExtKeyToMe = :this->id";
  1055. $aNeighbourData['sQueryUp'] = "SELECT ".$aNeighbourData['sFromClass']." AS o WHERE o.id = :this->$sExtKeyToMe";
  1056. }
  1057. }
  1058. else
  1059. {
  1060. throw new Exception("Unexpected attribute type for '{$aNeighbourData['sAttribute']}'. Expecting a link set or external key.");
  1061. }
  1062. }
  1063. else
  1064. {
  1065. $oSearch = DBObjectSearch::FromOQL($aNeighbourData['sQueryDown']);
  1066. $aNeighbourData['sToClass'] = $oSearch->GetClass();
  1067. }
  1068. }
  1069. catch (Exception $e)
  1070. {
  1071. throw new Exception("Wrong definition for the relation $sRelCode/{$aNeighbourData['sDefinedInClass']}/{$aNeighbourData['sNeighbour']}: ".$e->getMessage());
  1072. }
  1073. if ($aNeighbourData['sDirection'] == 'down')
  1074. {
  1075. $aNeighbourData['sQueryUp'] = null;
  1076. }
  1077. $sArrowId = $aNeighbourData['sDefinedInClass'].'_'.$sNeighbourId;
  1078. $aQueries[$sClass]['down'][$sArrowId] = $aNeighbourData;
  1079. // Compute the reverse index
  1080. if ($aNeighbourData['sDefinedInClass'] == $sClass)
  1081. {
  1082. if ($aNeighbourData['sDirection'] == 'both')
  1083. {
  1084. $sFromClass = $aNeighbourData['sFromClass'];
  1085. $sToClass = $aNeighbourData['sToClass'];
  1086. foreach (self::EnumChildClasses($sToClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
  1087. {
  1088. $aQueries[$sSubClass]['up'][$sArrowId] = $aNeighbourData;
  1089. }
  1090. }
  1091. }
  1092. }
  1093. // Read legacy definitions
  1094. // The up/down queries have to be reconcilied, which can only be done later when all the classes have been browsed
  1095. //
  1096. // The keys used to store a query (up or down) into the array are built differently between the modern and legacy made data:
  1097. // Modern way: aQueries[sClass]['up'|'down'][sArrowId], where sArrowId is made of the source class + neighbour id (XML def)
  1098. // Legacy way: aQueries[sClass]['up'|'down'][sRemoteClass]
  1099. // The modern way does allow for several arrows between two classes
  1100. // The legacy way aims at simplifying the transformation (reconciliation between up and down)
  1101. if ($sRelCode == 'impacts')
  1102. {
  1103. $sRevertCode = 'depends on';
  1104. $aLegacy = call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRelCode));
  1105. foreach($aLegacy as $sId => $aLegacyEntry)
  1106. {
  1107. $bHasLegacy = true;
  1108. $oFilter = DBObjectSearch::FromOQL($aLegacyEntry['sQuery']);
  1109. $sRemoteClass = $oFilter->GetClass();
  1110. // Determine wether the query is inherited from a parent or not
  1111. $bInherited = false;
  1112. foreach (self::EnumParentClasses($sClass) as $sParent)
  1113. {
  1114. if (!isset($aQueries[$sParent]['down'][$sRemoteClass])) continue;
  1115. if ($aLegacyEntry['sQuery'] == $aQueries[$sParent]['down'][$sRemoteClass]['sQueryDown'])
  1116. {
  1117. $bInherited = true;
  1118. $aQueries[$sClass]['down'][$sRemoteClass] = $aQueries[$sParent]['down'][$sRemoteClass];
  1119. break;
  1120. }
  1121. }
  1122. if (!$bInherited)
  1123. {
  1124. $aQueries[$sClass]['down'][$sRemoteClass] = array(
  1125. '_legacy_' => true,
  1126. 'sDefinedInClass' => $sClass,
  1127. 'sFromClass' => $sClass,
  1128. 'sToClass' => $sRemoteClass,
  1129. 'sDirection' => 'down',
  1130. 'sQueryDown' => $aLegacyEntry['sQuery'],
  1131. 'sQueryUp' => null,
  1132. 'sNeighbour' => $sRemoteClass // Normalize the neighbour id
  1133. );
  1134. }
  1135. }
  1136. $aLegacy = call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRevertCode));
  1137. foreach($aLegacy as $sId => $aLegacyEntry)
  1138. {
  1139. $bHasLegacy = true;
  1140. $oFilter = DBObjectSearch::FromOQL($aLegacyEntry['sQuery']);
  1141. $sRemoteClass = $oFilter->GetClass();
  1142. // Determine wether the query is inherited from a parent or not
  1143. $bInherited = false;
  1144. foreach (self::EnumParentClasses($sClass) as $sParent)
  1145. {
  1146. if (!isset($aQueries[$sParent]['up'][$sRemoteClass])) continue;
  1147. if ($aLegacyEntry['sQuery'] == $aQueries[$sParent]['up'][$sRemoteClass]['sQueryUp'])
  1148. {
  1149. $bInherited = true;
  1150. $aQueries[$sClass]['up'][$sRemoteClass] = $aQueries[$sParent]['up'][$sRemoteClass];
  1151. break;
  1152. }
  1153. }
  1154. if (!$bInherited)
  1155. {
  1156. $aQueries[$sClass]['up'][$sRemoteClass] = array(
  1157. '_legacy_' => true,
  1158. 'sDefinedInClass' => $sRemoteClass,
  1159. 'sFromClass' => $sRemoteClass,
  1160. 'sToClass' => $sClass,
  1161. 'sDirection' => 'both',
  1162. 'sQueryDown' => null,
  1163. 'sQueryUp' => $aLegacyEntry['sQuery'],
  1164. 'sNeighbour' => $sClass// Normalize the neighbour id
  1165. );
  1166. }
  1167. }
  1168. }
  1169. else
  1170. {
  1171. // Cannot take the legacy system into account... simply ignore it
  1172. }
  1173. } // foreach class
  1174. // Perform the up/down reconciliation for the legacy definitions
  1175. if ($bHasLegacy)
  1176. {
  1177. foreach (self::GetClasses() as $sClass)
  1178. {
  1179. // Foreach "up" legacy query, update its "down" counterpart
  1180. if (isset($aQueries[$sClass]['up']))
  1181. {
  1182. foreach ($aQueries[$sClass]['up'] as $sNeighbourId => $aNeighbourData)
  1183. {
  1184. if (!array_key_exists('_legacy_', $aNeighbourData))
  1185. {
  1186. continue;
  1187. }
  1188. if (!$aNeighbourData['_legacy_']) continue; // Skip modern definitions
  1189. $sLocalClass = $aNeighbourData['sToClass'];
  1190. foreach (self::EnumChildClasses($aNeighbourData['sFromClass'], ENUM_CHILD_CLASSES_ALL) as $sRemoteClass)
  1191. {
  1192. if (isset($aQueries[$sRemoteClass]['down'][$sLocalClass]))
  1193. {
  1194. $aQueries[$sRemoteClass]['down'][$sLocalClass]['sQueryUp'] = $aNeighbourData['sQueryUp'];
  1195. $aQueries[$sRemoteClass]['down'][$sLocalClass]['sDirection'] = 'both';
  1196. }
  1197. // Be silent in order to transparently support legacy data models where the counterpart query does not always exist
  1198. //else
  1199. //{
  1200. // throw new Exception("Legacy definition of the relation '$sRelCode/$sRevertCode', defined on $sLocalClass (relation: $sRevertCode, inherited to $sClass), missing the counterpart query on class $sRemoteClass ($sRelCode)");
  1201. //}
  1202. }
  1203. }
  1204. }
  1205. // Foreach "down" legacy query, update its "up" counterpart (if any)
  1206. foreach ($aQueries[$sClass]['down'] as $sNeighbourId => $aNeighbourData)
  1207. {
  1208. if (!$aNeighbourData['_legacy_']) continue; // Skip modern definitions
  1209. $sLocalClass = $aNeighbourData['sFromClass'];
  1210. foreach (self::EnumChildClasses($aNeighbourData['sToClass'], ENUM_CHILD_CLASSES_ALL) as $sRemoteClass)
  1211. {
  1212. if (isset($aQueries[$sRemoteClass]['up'][$sLocalClass]))
  1213. {
  1214. $aQueries[$sRemoteClass]['up'][$sLocalClass]['sQueryDown'] = $aNeighbourData['sQueryDown'];
  1215. }
  1216. }
  1217. }
  1218. }
  1219. }
  1220. return $aQueries;
  1221. }
  1222. public static function EnumRelationQueries($sClass, $sRelCode, $bDown = true)
  1223. {
  1224. static $aQueries = array();
  1225. if (!isset($aQueries[$sRelCode]))
  1226. {
  1227. $aQueries[$sRelCode] = self::ComputeRelationQueries($sRelCode);
  1228. }
  1229. $sDirection = $bDown ? 'down' : 'up';
  1230. if (isset($aQueries[$sRelCode][$sClass][$sDirection]))
  1231. {
  1232. return $aQueries[$sRelCode][$sClass][$sDirection];
  1233. }
  1234. else
  1235. {
  1236. return array();
  1237. }
  1238. }
  1239. /**
  1240. * Compute the "RelatedObjects" for a whole set of DBObjects
  1241. *
  1242. * @param string $sRelCode The code of the relation to use for the computation
  1243. * @param array $asourceObjects The objects to start with
  1244. * @param int $iMaxDepth
  1245. * @param boolean $bEnableReduncancy
  1246. * @param array $aUnreachable Array of objects to be considered as 'unreachable'
  1247. *
  1248. * @return RelationGraph The graph of all the related objects
  1249. */
  1250. static public function GetRelatedObjectsDown($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aUnreachable = array(), $aContexts = array())
  1251. {
  1252. $oGraph = new RelationGraph();
  1253. foreach ($aSourceObjects as $oObject)
  1254. {
  1255. $oGraph->AddSourceObject($oObject);
  1256. }
  1257. foreach($aContexts as $key => $sOQL)
  1258. {
  1259. $oGraph->AddContextQuery($key, $sOQL);
  1260. }
  1261. $oGraph->ComputeRelatedObjectsDown($sRelCode, $iMaxDepth, $bEnableRedundancy, $aUnreachable);
  1262. return $oGraph;
  1263. }
  1264. /**
  1265. * Compute the "RelatedObjects" in the reverse way
  1266. *
  1267. * @param string $sRelCode The code of the relation to use for the computation
  1268. * @param array $asourceObjects The objects to start with
  1269. * @param int $iMaxDepth
  1270. * @param boolean $bEnableReduncancy
  1271. *
  1272. * @return RelationGraph The graph of all the related objects
  1273. */
  1274. static public function GetRelatedObjectsUp($sRelCode, $aSourceObjects, $iMaxDepth = 99, $bEnableRedundancy = true, $aContexts = array())
  1275. {
  1276. $oGraph = new RelationGraph();
  1277. foreach ($aSourceObjects as $oObject)
  1278. {
  1279. $oGraph->AddSinkObject($oObject);
  1280. }
  1281. foreach($aContexts as $key => $sOQL)
  1282. {
  1283. $oGraph->AddContextQuery($key, $sOQL);
  1284. }
  1285. $oGraph->ComputeRelatedObjectsUp($sRelCode, $iMaxDepth, $bEnableRedundancy);
  1286. return $oGraph;
  1287. }
  1288. //
  1289. // Object lifecycle model
  1290. //
  1291. private static $m_aStates = array(); // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  1292. private static $m_aStimuli = array(); // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  1293. 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)))
  1294. public static function EnumStates($sClass)
  1295. {
  1296. if (array_key_exists($sClass, self::$m_aStates))
  1297. {
  1298. return self::$m_aStates[$sClass];
  1299. }
  1300. else
  1301. {
  1302. return array();
  1303. }
  1304. }
  1305. /*
  1306. * Enumerate all possible initial states, including the default one
  1307. */
  1308. public static function EnumInitialStates($sClass)
  1309. {
  1310. if (array_key_exists($sClass, self::$m_aStates))
  1311. {
  1312. $aRet = array();
  1313. // Add the states for which the flag 'is_initial_state' is set to <true>
  1314. foreach(self::$m_aStates[$sClass] as $aStateCode => $aProps)
  1315. {
  1316. if (isset($aProps['initial_state_path']))
  1317. {
  1318. $aRet[$aStateCode] = $aProps['initial_state_path'];
  1319. }
  1320. }
  1321. // Add the default initial state
  1322. $sMainInitialState = self::GetDefaultState($sClass);
  1323. if (!isset($aRet[$sMainInitialState]))
  1324. {
  1325. $aRet[$sMainInitialState] = array();
  1326. }
  1327. return $aRet;
  1328. }
  1329. else
  1330. {
  1331. return array();
  1332. }
  1333. }
  1334. public static function EnumStimuli($sClass)
  1335. {
  1336. if (array_key_exists($sClass, self::$m_aStimuli))
  1337. {
  1338. return self::$m_aStimuli[$sClass];
  1339. }
  1340. else
  1341. {
  1342. return array();
  1343. }
  1344. }
  1345. public static function GetStateLabel($sClass, $sStateValue)
  1346. {
  1347. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1348. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1349. return $oAttDef->GetValueLabel($sStateValue);
  1350. }
  1351. public static function GetStateDescription($sClass, $sStateValue)
  1352. {
  1353. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1354. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1355. return $oAttDef->GetValueDescription($sStateValue);
  1356. }
  1357. public static function EnumTransitions($sClass, $sStateCode)
  1358. {
  1359. if (array_key_exists($sClass, self::$m_aTransitions))
  1360. {
  1361. if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
  1362. {
  1363. return self::$m_aTransitions[$sClass][$sStateCode];
  1364. }
  1365. }
  1366. return array();
  1367. }
  1368. public static function GetAttributeFlags($sClass, $sState, $sAttCode)
  1369. {
  1370. $iFlags = 0; // By default (if no life cycle) no flag at all
  1371. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1372. if (!empty($sStateAttCode))
  1373. {
  1374. $aStates = MetaModel::EnumStates($sClass);
  1375. if (!array_key_exists($sState, $aStates))
  1376. {
  1377. throw new CoreException("Invalid state '$sState' for class '$sClass', expecting a value in {".implode(', ', array_keys($aStates))."}");
  1378. }
  1379. $aCurrentState = $aStates[$sState];
  1380. if ( (array_key_exists('attribute_list', $aCurrentState)) && (array_key_exists($sAttCode, $aCurrentState['attribute_list'])) )
  1381. {
  1382. $iFlags = $aCurrentState['attribute_list'][$sAttCode];
  1383. }
  1384. }
  1385. return $iFlags;
  1386. }
  1387. /**
  1388. * Combines the flags from the all states that compose the initial_state_path
  1389. */
  1390. public static function GetInitialStateAttributeFlags($sClass, $sState, $sAttCode)
  1391. {
  1392. $iFlags = self::GetAttributeFlags($sClass, $sState, $sAttCode); // Be default set the same flags as the 'target' state
  1393. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1394. if (!empty($sStateAttCode))
  1395. {
  1396. $aStates = MetaModel::EnumInitialStates($sClass);
  1397. if (array_key_exists($sState, $aStates))
  1398. {
  1399. $bReadOnly = (($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY);
  1400. $bHidden = (($iFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN);
  1401. foreach($aStates[$sState] as $sPrevState)
  1402. {
  1403. $iPrevFlags = self::GetAttributeFlags($sClass, $sPrevState, $sAttCode);
  1404. if (($iPrevFlags & OPT_ATT_HIDDEN) != OPT_ATT_HIDDEN)
  1405. {
  1406. $bReadOnly = $bReadOnly && (($iPrevFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY); // if it is/was not readonly => then it's not
  1407. }
  1408. $bHidden = $bHidden && (($iPrevFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN); // if it is/was not hidden => then it's not
  1409. }
  1410. if ($bReadOnly)
  1411. {
  1412. $iFlags = $iFlags | OPT_ATT_READONLY;
  1413. }
  1414. else
  1415. {
  1416. $iFlags = $iFlags & ~OPT_ATT_READONLY;
  1417. }
  1418. if ($bHidden)
  1419. {
  1420. $iFlags = $iFlags | OPT_ATT_HIDDEN;
  1421. }
  1422. else
  1423. {
  1424. $iFlags = $iFlags & ~OPT_ATT_HIDDEN;
  1425. }
  1426. }
  1427. }
  1428. return $iFlags;
  1429. }
  1430. //
  1431. // Allowed values
  1432. //
  1433. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1434. {
  1435. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1436. return $oAttDef->GetAllowedValues($aArgs, $sContains);
  1437. }
  1438. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sContains = '')
  1439. {
  1440. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  1441. return $oFltDef->GetAllowedValues($aArgs, $sContains);
  1442. }
  1443. public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1444. {
  1445. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1446. return $oAttDef->GetAllowedValuesAsObjectSet($aArgs, $sContains);
  1447. }
  1448. //
  1449. // Businezz model declaration verbs (should be static)
  1450. //
  1451. public static function RegisterZList($sListCode, $aListInfo)
  1452. {
  1453. // Check mandatory params
  1454. $aMandatParams = array(
  1455. "description" => "detailed (though one line) description of the list",
  1456. "type" => "attributes | filters",
  1457. );
  1458. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1459. {
  1460. if (!array_key_exists($sParamName, $aListInfo))
  1461. {
  1462. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  1463. }
  1464. }
  1465. self::$m_aListInfos[$sListCode] = $aListInfo;
  1466. }
  1467. public static function RegisterRelation($sRelCode)
  1468. {
  1469. // Each item used to be an array of properties...
  1470. self::$m_aRelationInfos[$sRelCode] = $sRelCode;
  1471. }
  1472. // Must be called once and only once...
  1473. public static function InitClasses($sTablePrefix)
  1474. {
  1475. if (count(self::GetClasses()) > 0)
  1476. {
  1477. throw new CoreException("InitClasses should not be called more than once -skipped");
  1478. return;
  1479. }
  1480. self::$m_sTablePrefix = $sTablePrefix;
  1481. // Build the list of available extensions
  1482. //
  1483. $aInterfaces = array('iApplicationUIExtension', 'iApplicationObjectExtension', 'iQueryModifier', 'iOnClassInitialization', 'iPopupMenuExtension', 'iPageUIExtension');
  1484. foreach($aInterfaces as $sInterface)
  1485. {
  1486. self::$m_aExtensionClasses[$sInterface] = array();
  1487. }
  1488. foreach(get_declared_classes() as $sPHPClass)
  1489. {
  1490. $oRefClass = new ReflectionClass($sPHPClass);
  1491. $oExtensionInstance = null;
  1492. foreach($aInterfaces as $sInterface)
  1493. {
  1494. if ($oRefClass->implementsInterface($sInterface))
  1495. {
  1496. if (is_null($oExtensionInstance))
  1497. {
  1498. $oExtensionInstance = new $sPHPClass;
  1499. }
  1500. self::$m_aExtensionClasses[$sInterface][$sPHPClass] = $oExtensionInstance;
  1501. }
  1502. }
  1503. }
  1504. // Initialize the classes (declared attributes, etc.)
  1505. //
  1506. foreach(get_declared_classes() as $sPHPClass)
  1507. {
  1508. if (is_subclass_of($sPHPClass, 'DBObject'))
  1509. {
  1510. $sParent = get_parent_class($sPHPClass);
  1511. if (array_key_exists($sParent, self::$m_aIgnoredAttributes))
  1512. {
  1513. // Inherit info about attributes to ignore
  1514. self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent];
  1515. }
  1516. try
  1517. {
  1518. $oMethod = new ReflectionMethod($sPHPClass, 'Init');
  1519. if ($oMethod->getDeclaringClass()->name == $sPHPClass)
  1520. {
  1521. call_user_func(array($sPHPClass, 'Init'));
  1522. foreach (MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit)
  1523. {
  1524. $oClassInit->OnAfterClassInitialization($sPHPClass);
  1525. }
  1526. }
  1527. }
  1528. catch (ReflectionException $e)
  1529. {
  1530. // This class is only implementing methods, ignore it from the MetaModel perspective
  1531. }
  1532. }
  1533. }
  1534. // Add a 'class' attribute/filter to the root classes and their children
  1535. //
  1536. foreach(self::EnumRootClasses() as $sRootClass)
  1537. {
  1538. if (self::IsStandaloneClass($sRootClass)) continue;
  1539. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  1540. if (strlen($sDbFinalClassField) == 0)
  1541. {
  1542. $sDbFinalClassField = 'finalclass';
  1543. self::$m_aClassParams[$sRootClass]["db_finalclass_field"] = 'finalclass';
  1544. }
  1545. $oClassAtt = new AttributeFinalClass('finalclass', array(
  1546. "sql"=>$sDbFinalClassField,
  1547. "default_value"=>$sRootClass,
  1548. "is_null_allowed"=>false,
  1549. "depends_on"=>array()
  1550. ));
  1551. $oClassAtt->SetHostClass($sRootClass);
  1552. self::$m_aAttribDefs[$sRootClass]['finalclass'] = $oClassAtt;
  1553. self::$m_aAttribOrigins[$sRootClass]['finalclass'] = $sRootClass;
  1554. $oClassFlt = new FilterFromAttribute($oClassAtt);
  1555. self::$m_aFilterDefs[$sRootClass]['finalclass'] = $oClassFlt;
  1556. self::$m_aFilterOrigins[$sRootClass]['finalclass'] = $sRootClass;
  1557. foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass)
  1558. {
  1559. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass]))
  1560. {
  1561. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  1562. }
  1563. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sChildClass]))
  1564. {
  1565. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  1566. }
  1567. $oCloned = clone $oClassAtt;
  1568. $oCloned->SetFixedValue($sChildClass);
  1569. self::$m_aAttribDefs[$sChildClass]['finalclass'] = $oCloned;
  1570. self::$m_aAttribOrigins[$sChildClass]['finalclass'] = $sRootClass;
  1571. $oClassFlt = new FilterFromAttribute($oClassAtt);
  1572. self::$m_aFilterDefs[$sChildClass]['finalclass'] = $oClassFlt;
  1573. self::$m_aFilterOrigins[$sChildClass]['finalclass'] = self::GetRootClass($sChildClass);
  1574. }
  1575. }
  1576. // Prepare external fields and filters
  1577. // Add final class to external keys
  1578. //
  1579. foreach (self::GetClasses() as $sClass)
  1580. {
  1581. // Create the friendly name attribute
  1582. $sFriendlyNameAttCode = 'friendlyname';
  1583. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, 'id');
  1584. $oFriendlyName->SetHostClass($sClass);
  1585. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1586. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sClass;
  1587. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1588. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1589. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sClass;
  1590. self::$m_aExtKeyFriends[$sClass] = array();
  1591. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  1592. {
  1593. // Compute the filter codes
  1594. //
  1595. foreach ($oAttDef->GetFilterDefinitions() as $sFilterCode => $oFilterDef)
  1596. {
  1597. self::$m_aFilterDefs[$sClass][$sFilterCode] = $oFilterDef;
  1598. if ($oAttDef->IsExternalField())
  1599. {
  1600. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1601. $oKeyDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1602. self::$m_aFilterOrigins[$sClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  1603. }
  1604. else
  1605. {
  1606. self::$m_aFilterOrigins[$sClass][$sFilterCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  1607. }
  1608. }
  1609. // Compute the fields that will be used to display a pointer to another object
  1610. //
  1611. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  1612. {
  1613. // oAttDef is either
  1614. // - an external KEY / FIELD (direct),
  1615. // - an external field pointing to an external KEY / FIELD
  1616. // - an external field pointing to an external field pointing to....
  1617. $sRemoteClass = $oAttDef->GetTargetClass();
  1618. if ($oAttDef->IsExternalField())
  1619. {
  1620. // This is a key, but the value comes from elsewhere
  1621. // Create an external field pointing to the remote friendly name attribute
  1622. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1623. $sRemoteAttCode = $oAttDef->GetExtAttCode()."_friendlyname";
  1624. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1625. // propagate "is_null_allowed" ?
  1626. $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array("allowed_values"=>null, "extkey_attcode"=>$sKeyAttCode, "target_attcode"=>$sRemoteAttCode, "depends_on"=>array()));
  1627. $oFriendlyName->SetHostClass($sClass);
  1628. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1629. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1630. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1631. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1632. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1633. }
  1634. else
  1635. {
  1636. // Create the friendly name attribute
  1637. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1638. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, $sAttCode);
  1639. $oFriendlyName->SetHostClass($sClass);
  1640. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1641. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1642. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1643. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1644. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1645. if (self::HasChildrenClasses($sRemoteClass))
  1646. {
  1647. // First, create an external field attribute, that gets the final class
  1648. $sClassRecallAttCode = $sAttCode.'_finalclass_recall';
  1649. $oClassRecall = new AttributeExternalField($sClassRecallAttCode, array(
  1650. "allowed_values"=>null,
  1651. "extkey_attcode"=>$sAttCode,
  1652. "target_attcode"=>"finalclass",
  1653. "is_null_allowed"=>true,
  1654. "depends_on"=>array()
  1655. ));
  1656. $oClassRecall->SetHostClass($sClass);
  1657. self::$m_aAttribDefs[$sClass][$sClassRecallAttCode] = $oClassRecall;
  1658. self::$m_aAttribOrigins[$sClass][$sClassRecallAttCode] = $sRemoteClass;
  1659. $oClassFlt = new FilterFromAttribute($oClassRecall);
  1660. self::$m_aFilterDefs[$sClass][$sClassRecallAttCode] = $oClassFlt;
  1661. self::$m_aFilterOrigins[$sClass][$sClassRecallAttCode] = $sRemoteClass;
  1662. // Add it to the ZLists where the external key is present
  1663. //foreach(self::$m_aListData[$sClass] as $sListCode => $aAttributes)
  1664. $sListCode = 'list';
  1665. if (isset(self::$m_aListData[$sClass][$sListCode]))
  1666. {
  1667. $aAttributes = self::$m_aListData[$sClass][$sListCode];
  1668. // temporary.... no loop
  1669. {
  1670. if (in_array($sAttCode, $aAttributes))
  1671. {
  1672. $aNewList = array();
  1673. foreach($aAttributes as $iPos => $sAttToDisplay)
  1674. {
  1675. if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode))
  1676. {
  1677. // Insert the final class right before
  1678. $aNewList[] = $sClassRecallAttCode;
  1679. }
  1680. $aNewList[] = $sAttToDisplay;
  1681. }
  1682. self::$m_aListData[$sClass][$sListCode] = $aNewList;
  1683. }
  1684. }
  1685. }
  1686. }
  1687. }
  1688. // Get the real external key attribute
  1689. // It will be our reference to determine the other ext fields related to the same ext key
  1690. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1691. self::$m_aExtKeyFriends[$sClass][$sAttCode] = array();
  1692. foreach (self::GetExternalFields($sClass, $oAttDef->GetKeyAttCode($sAttCode)) as $oExtField)
  1693. {
  1694. // skip : those extfields will be processed as external keys
  1695. if ($oExtField->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1696. // Note: I could not compare the objects by the mean of '==='
  1697. // because they are copied for the inheritance, and the internal references are NOT updated
  1698. if ($oExtField->GetKeyAttDef(EXTKEY_ABSOLUTE) == $oFinalKeyAttDef)
  1699. {
  1700. self::$m_aExtKeyFriends[$sClass][$sAttCode][$oExtField->GetCode()] = $oExtField;
  1701. }
  1702. }
  1703. }
  1704. if ($oAttDef instanceof AttributeMetaEnum)
  1705. {
  1706. $aMappingData = $oAttDef->GetMapRule($sClass);
  1707. if ($aMappingData != null)
  1708. {
  1709. $sEnumAttCode = $aMappingData['attcode'];
  1710. self::$m_aEnumToMeta[$sClass][$sEnumAttCode][$sAttCode] = $oAttDef;
  1711. }
  1712. }
  1713. }
  1714. // Add a 'id' filter
  1715. //
  1716. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  1717. {
  1718. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  1719. }
  1720. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  1721. {
  1722. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  1723. }
  1724. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  1725. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  1726. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  1727. // Define defaults values for the standard ZLists
  1728. //
  1729. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  1730. //{
  1731. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  1732. // {
  1733. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  1734. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  1735. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  1736. // }
  1737. //}
  1738. }
  1739. }
  1740. // To be overriden, must be called for any object class (optimization)
  1741. public static function Init()
  1742. {
  1743. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1744. }
  1745. // To be overloaded by biz model declarations
  1746. public static function GetRelationQueries($sRelCode)
  1747. {
  1748. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1749. return array();
  1750. }
  1751. public static function Init_Params($aParams)
  1752. {
  1753. // Check mandatory params
  1754. $aMandatParams = array(
  1755. "category" => "group classes by modules defining their visibility in the UI",
  1756. "key_type" => "autoincrement | string",
  1757. "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...'",
  1758. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  1759. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  1760. "db_table" => "database table",
  1761. "db_key_field" => "database field which is the key",
  1762. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  1763. );
  1764. $sClass = self::GetCallersPHPClass("Init", self::$m_bTraceSourceFiles);
  1765. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1766. {
  1767. if (!array_key_exists($sParamName, $aParams))
  1768. {
  1769. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  1770. }
  1771. }
  1772. $aCategories = explode(',', $aParams['category']);
  1773. foreach ($aCategories as $sCategory)
  1774. {
  1775. self::$m_Category2Class[$sCategory][] = $sClass;
  1776. }
  1777. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  1778. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  1779. self::$m_aParentClasses[$sClass] = array();
  1780. self::$m_aChildClasses[$sClass] = array();
  1781. self::$m_aClassParams[$sClass]= $aParams;
  1782. self::$m_aAttribDefs[$sClass] = array();
  1783. self::$m_aAttribOrigins[$sClass] = array();
  1784. self::$m_aExtKeyFriends[$sClass] = array();
  1785. self::$m_aFilterDefs[$sClass] = array();
  1786. self::$m_aFilterOrigins[$sClass] = array();
  1787. }
  1788. protected static function object_array_mergeclone($aSource1, $aSource2)
  1789. {
  1790. $aRes = array();
  1791. foreach ($aSource1 as $key=>$object)
  1792. {
  1793. $aRes[$key] = clone $object;
  1794. }
  1795. foreach ($aSource2 as $key=>$object)
  1796. {
  1797. $aRes[$key] = clone $object;
  1798. }
  1799. return $aRes;
  1800. }
  1801. public static function Init_InheritAttributes($sSourceClass = null)
  1802. {
  1803. $sTargetClass = self::GetCallersPHPClass("Init");
  1804. if (empty($sSourceClass))
  1805. {
  1806. // Default: inherit from parent class
  1807. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1808. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1809. }
  1810. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  1811. {
  1812. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  1813. {
  1814. self::$m_aAttribDefs[$sTargetClass] = array();
  1815. self::$m_aAttribOrigins[$sTargetClass] = array();
  1816. }
  1817. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  1818. foreach(self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef)
  1819. {
  1820. $oAttDef->SetHostClass($sTargetClass);
  1821. }
  1822. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  1823. }
  1824. // Build root class information
  1825. if (array_key_exists($sSourceClass, self::$m_aRootClasses))
  1826. {
  1827. // Inherit...
  1828. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  1829. }
  1830. else
  1831. {
  1832. // This class will be the root class
  1833. self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
  1834. self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
  1835. }
  1836. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  1837. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  1838. // I am the child of each and every parent...
  1839. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  1840. {
  1841. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  1842. }
  1843. }
  1844. protected static function Init_IsKnownClass($sClass)
  1845. {
  1846. // Differs from self::IsValidClass()
  1847. // because it is being called before all the classes have been initialized
  1848. if (!class_exists($sClass)) return false;
  1849. if (!is_subclass_of($sClass, 'DBObject')) return false;
  1850. return true;
  1851. }
  1852. public static function Init_AddAttribute(AttributeDefinition $oAtt, $sTargetClass = null)
  1853. {
  1854. if (!$sTargetClass)
  1855. {
  1856. $sTargetClass = self::GetCallersPHPClass("Init");
  1857. }
  1858. $sAttCode = $oAtt->GetCode();
  1859. if ($sAttCode == 'finalclass')
  1860. {
  1861. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1862. }
  1863. if ($sAttCode == 'friendlyname')
  1864. {
  1865. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1866. }
  1867. if (array_key_exists($sAttCode, self::$m_aAttribDefs[$sTargetClass]))
  1868. {
  1869. throw new Exception("Declaration of $sTargetClass: attempting to redeclare the inherited attribute '$sAttCode', originaly declared in ".self::$m_aAttribOrigins[$sTargetClass][$sAttCode]);
  1870. }
  1871. // Set the "host class" as soon as possible, since HierarchicalKeys use it for their 'target class' as well
  1872. // and this needs to be know early (for Init_IsKnowClass 19 lines below)
  1873. $oAtt->SetHostClass($sTargetClass);
  1874. // Some attributes could refer to a class
  1875. // declared in a module which is currently not installed/active
  1876. // We simply discard those attributes
  1877. //
  1878. if ($oAtt->IsLinkSet())
  1879. {
  1880. $sRemoteClass = $oAtt->GetLinkedClass();
  1881. if (!self::Init_IsKnownClass($sRemoteClass))
  1882. {
  1883. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1884. return;
  1885. }
  1886. }
  1887. elseif($oAtt->IsExternalKey())
  1888. {
  1889. $sRemoteClass = $oAtt->GetTargetClass();
  1890. if (!self::Init_IsKnownClass($sRemoteClass))
  1891. {
  1892. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1893. return;
  1894. }
  1895. }
  1896. elseif($oAtt->IsExternalField())
  1897. {
  1898. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  1899. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
  1900. {
  1901. // The corresponding external key has already been ignored
  1902. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
  1903. return;
  1904. }
  1905. // #@# todo - Check if the target attribute is still there
  1906. // this is not simple to implement because is involves
  1907. // several passes (the load order has a significant influence on that)
  1908. }
  1909. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  1910. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  1911. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  1912. }
  1913. public static function Init_SetZListItems($sListCode, $aItems, $sTargetClass = null)
  1914. {
  1915. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  1916. if (!$sTargetClass)
  1917. {
  1918. $sTargetClass = self::GetCallersPHPClass("Init");
  1919. }
  1920. // Discard attributes that do not make sense
  1921. // (missing classes in the current module combination, resulting in irrelevant ext key or link set)
  1922. //
  1923. self::Init_CheckZListItems($aItems, $sTargetClass);
  1924. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  1925. }
  1926. protected static function Init_CheckZListItems(&$aItems, $sTargetClass)
  1927. {
  1928. foreach($aItems as $iFoo => $attCode)
  1929. {
  1930. if (is_array($attCode))
  1931. {
  1932. // Note: to make sure that the values will be updated recursively,
  1933. // do not pass $attCode, but $aItems[$iFoo] instead
  1934. self::Init_CheckZListItems($aItems[$iFoo], $sTargetClass);
  1935. if (count($aItems[$iFoo]) == 0)
  1936. {
  1937. unset($aItems[$iFoo]);
  1938. }
  1939. }
  1940. else if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode]))
  1941. {
  1942. unset($aItems[$iFoo]);
  1943. }
  1944. }
  1945. }
  1946. public static function FlattenZList($aList)
  1947. {
  1948. $aResult = array();
  1949. foreach($aList as $value)
  1950. {
  1951. if (!is_array($value))
  1952. {
  1953. $aResult[] = $value;
  1954. }
  1955. else
  1956. {
  1957. $aResult = array_merge($aResult, self::FlattenZList($value));
  1958. }
  1959. }
  1960. return $aResult;
  1961. }
  1962. public static function Init_DefineState($sStateCode, $aStateDef)
  1963. {
  1964. $sTargetClass = self::GetCallersPHPClass("Init");
  1965. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  1966. $sParentState = $aStateDef['attribute_inherit'];
  1967. if (!empty($sParentState))
  1968. {
  1969. // Inherit from the given state (must be defined !)
  1970. //
  1971. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  1972. // Reset the constraint when it was mandatory to set the value at the previous state
  1973. //
  1974. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  1975. {
  1976. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  1977. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  1978. $aToInherit['attribute_list'][$sState] = $iFlags;
  1979. }
  1980. // The inherited configuration could be overriden
  1981. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  1982. }
  1983. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  1984. {
  1985. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  1986. {
  1987. unset($aStateDef['attribute_list'][$sAttCode]);
  1988. }
  1989. }
  1990. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  1991. // by default, create an empty set of transitions associated to that state
  1992. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  1993. }
  1994. public static function Init_DefineHighlightScale($aHighlightScale)
  1995. {
  1996. $sTargetClass = self::GetCallersPHPClass("Init");
  1997. self::$m_aHighlightScales[$sTargetClass] = $aHighlightScale;
  1998. }
  1999. public static function GetHighlightScale($sTargetClass)
  2000. {
  2001. $aScale = array();
  2002. $aParentScale = array();
  2003. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2004. if (!empty($sParentClass))
  2005. {
  2006. // inherit the scale from the parent class
  2007. $aParentScale = self::GetHighlightScale($sParentClass);
  2008. }
  2009. if (array_key_exists($sTargetClass, self::$m_aHighlightScales))
  2010. {
  2011. $aScale = self::$m_aHighlightScales[$sTargetClass];
  2012. }
  2013. return array_merge($aParentScale, $aScale); // Merge both arrays, the values from the last one have precedence
  2014. }
  2015. public static function GetHighlightCode($sTargetClass, $sStateCode)
  2016. {
  2017. $sCode = '';
  2018. if ( array_key_exists($sTargetClass, self::$m_aStates)
  2019. && array_key_exists($sStateCode, self::$m_aStates[$sTargetClass])
  2020. && array_key_exists('highlight', self::$m_aStates[$sTargetClass][$sStateCode]) )
  2021. {
  2022. $sCode = self::$m_aStates[$sTargetClass][$sStateCode]['highlight']['code'];
  2023. }
  2024. else
  2025. {
  2026. // Check the parent's definition
  2027. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2028. if (!empty($sParentClass))
  2029. {
  2030. $sCode = self::GetHighlightCode($sParentClass, $sStateCode);
  2031. }
  2032. }
  2033. return $sCode;
  2034. }
  2035. public static function Init_OverloadStateAttribute($sStateCode, $sAttCode, $iFlags)
  2036. {
  2037. // Warning: this is not sufficient: the flags have to be copied to the states that are inheriting from this state
  2038. $sTargetClass = self::GetCallersPHPClass("Init");
  2039. self::$m_aStates[$sTargetClass][$sStateCode]['attribute_list'][$sAttCode] = $iFlags;
  2040. }
  2041. public static function Init_DefineStimulus($oStimulus)
  2042. {
  2043. $sTargetClass = self::GetCallersPHPClass("Init");
  2044. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  2045. // I wanted to simplify the syntax of the declaration of objects in the biz model
  2046. // Therefore, the reference to the host class is set there
  2047. $oStimulus->SetHostClass($sTargetClass);
  2048. }
  2049. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  2050. {
  2051. $sTargetClass = self::GetCallersPHPClass("Init");
  2052. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  2053. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  2054. }
  2055. public static function Init_InheritLifecycle($sSourceClass = '')
  2056. {
  2057. $sTargetClass = self::GetCallersPHPClass("Init");
  2058. if (empty($sSourceClass))
  2059. {
  2060. // Default: inherit from parent class
  2061. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  2062. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  2063. }
  2064. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  2065. self::$m_aStates[$sTargetClass] = self::$m_aStates[$sSourceClass];
  2066. // #@# Note: the aim is to clone the data, could be an issue if the simuli objects are changed
  2067. self::$m_aStimuli[$sTargetClass] = self::$m_aStimuli[$sSourceClass];
  2068. self::$m_aTransitions[$sTargetClass] = self::$m_aTransitions[$sSourceClass];
  2069. }
  2070. //
  2071. // Static API
  2072. //
  2073. public static function GetRootClass($sClass = null)
  2074. {
  2075. self::_check_subclass($sClass);
  2076. return self::$m_aRootClasses[$sClass];
  2077. }
  2078. public static function IsRootClass($sClass)
  2079. {
  2080. self::_check_subclass($sClass);
  2081. return (self::GetRootClass($sClass) == $sClass);
  2082. }
  2083. public static function GetParentClass($sClass)
  2084. {
  2085. if (count(self::$m_aParentClasses[$sClass]) == 0)
  2086. {
  2087. return null;
  2088. }
  2089. else
  2090. {
  2091. return end(self::$m_aParentClasses[$sClass]);
  2092. }
  2093. }
  2094. public static function GetLowestCommonAncestor($aClasses)
  2095. {
  2096. $sAncestor = null;
  2097. foreach($aClasses as $sClass)
  2098. {
  2099. if (is_null($sAncestor))
  2100. {
  2101. // first loop
  2102. $sAncestor = $sClass;
  2103. }
  2104. elseif ($sClass == $sAncestor)
  2105. {
  2106. // remains the same
  2107. }
  2108. elseif (self::GetRootClass($sClass) != self::GetRootClass($sAncestor))
  2109. {
  2110. $sAncestor = null;
  2111. break;
  2112. }
  2113. else
  2114. {
  2115. $sAncestor = self::LowestCommonAncestor($sAncestor, $sClass);
  2116. }
  2117. }
  2118. return $sAncestor;
  2119. }
  2120. /**
  2121. * Note: assumes that class A and B have a common ancestor
  2122. */
  2123. protected static function LowestCommonAncestor($sClassA, $sClassB)
  2124. {
  2125. if ($sClassA == $sClassB)
  2126. {
  2127. $sRet = $sClassA;
  2128. }
  2129. elseif (is_subclass_of($sClassA, $sClassB))
  2130. {
  2131. $sRet = $sClassB;
  2132. }
  2133. elseif (is_subclass_of($sClassB, $sClassA))
  2134. {
  2135. $sRet = $sClassA;
  2136. }
  2137. else
  2138. {
  2139. // Recurse
  2140. $sRet = self::LowestCommonAncestor($sClassA, self::GetParentClass($sClassB));
  2141. }
  2142. return $sRet;
  2143. }
  2144. /**
  2145. * Tells if a class contains a hierarchical key, and if so what is its AttCode
  2146. * @return mixed String = sAttCode or false if the class is not part of a hierarchy
  2147. */
  2148. public static function IsHierarchicalClass($sClass)
  2149. {
  2150. $sHierarchicalKeyCode = false;
  2151. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  2152. {
  2153. if ($oAtt->IsHierarchicalKey())
  2154. {
  2155. $sHierarchicalKeyCode = $sAttCode; // Found the hierarchical key, no need to continue
  2156. break;
  2157. }
  2158. }
  2159. return $sHierarchicalKeyCode;
  2160. }
  2161. public static function EnumRootClasses()
  2162. {
  2163. return array_unique(self::$m_aRootClasses);
  2164. }
  2165. public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF, $bRootFirst = true)
  2166. {
  2167. self::_check_subclass($sClass);
  2168. if ($bRootFirst)
  2169. {
  2170. $aRes = self::$m_aParentClasses[$sClass];
  2171. }
  2172. else
  2173. {
  2174. $aRes = array_reverse(self::$m_aParentClasses[$sClass], true);
  2175. }
  2176. if ($iOption != ENUM_PARENT_CLASSES_EXCLUDELEAF)
  2177. {
  2178. if ($bRootFirst)
  2179. {
  2180. // Leaf class at the end
  2181. $aRes[] = $sClass;
  2182. }
  2183. else
  2184. {
  2185. // Leaf class on top
  2186. array_unshift($aRes, $sClass);
  2187. }
  2188. }
  2189. return $aRes;
  2190. }
  2191. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  2192. {
  2193. self::_check_subclass($sClass);
  2194. $aRes = self::$m_aChildClasses[$sClass];
  2195. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  2196. {
  2197. // Add it to the list
  2198. $aRes[] = $sClass;
  2199. }
  2200. return $aRes;
  2201. }
  2202. public static function HasChildrenClasses($sClass)
  2203. {
  2204. return (count(self::$m_aChildClasses[$sClass]) > 0);
  2205. }
  2206. public static function EnumCategories()
  2207. {
  2208. return array_keys(self::$m_Category2Class);
  2209. }
  2210. // Note: use EnumChildClasses to take the compound objects into account
  2211. public static function GetSubclasses($sClass)
  2212. {
  2213. self::_check_subclass($sClass);
  2214. $aSubClasses = array();
  2215. foreach(self::$m_aClassParams as $sSubClass => $foo)
  2216. {
  2217. if (is_subclass_of($sSubClass, $sClass))
  2218. {
  2219. $aSubClasses[] = $sSubClass;
  2220. }
  2221. }
  2222. return $aSubClasses;
  2223. }
  2224. public static function GetClasses($sCategories = '', $bStrict = false)
  2225. {
  2226. $aCategories = explode(',', $sCategories);
  2227. $aClasses = array();
  2228. foreach($aCategories as $sCategory)
  2229. {
  2230. $sCategory = trim($sCategory);
  2231. if (strlen($sCategory) == 0)
  2232. {
  2233. return array_keys(self::$m_aClassParams);
  2234. }
  2235. if (array_key_exists($sCategory, self::$m_Category2Class))
  2236. {
  2237. $aClasses = array_merge($aClasses, self::$m_Category2Class[$sCategory]);
  2238. }
  2239. elseif ($bStrict)
  2240. {
  2241. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  2242. }
  2243. }
  2244. return array_unique($aClasses);
  2245. }
  2246. public static function HasTable($sClass)
  2247. {
  2248. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  2249. return true;
  2250. }
  2251. public static function IsAbstract($sClass)
  2252. {
  2253. $oReflection = new ReflectionClass($sClass);
  2254. return $oReflection->isAbstract();
  2255. }
  2256. /**
  2257. * Normalizes query arguments and adds magic parameters:
  2258. * - current_contact_id
  2259. * - current_contact (DBObject)
  2260. * - current_user (DBObject)
  2261. *
  2262. * @param array $aArgs Context arguments (some can be persistent objects)
  2263. * @param array $aScalarArgs Other query parameters (only scalars allowed here)
  2264. * @return array
  2265. */
  2266. public static function PrepareQueryArguments($aArgs, $aScalarArgs = array())
  2267. {
  2268. foreach($aArgs as $sArgName => $value)
  2269. {
  2270. if (self::IsValidObject($value))
  2271. {
  2272. if (strpos($sArgName, '->object()') === false)
  2273. {
  2274. // Normalize object arguments
  2275. $aScalarArgs[$sArgName.'->object()'] = $value;
  2276. }
  2277. else
  2278. {
  2279. // Leave as is
  2280. $aScalarArgs[$sArgName] = $value;
  2281. }
  2282. }
  2283. else
  2284. {
  2285. if (is_scalar($value))
  2286. {
  2287. $aScalarArgs[$sArgName] = (string) $value;
  2288. }
  2289. elseif (is_null($value))
  2290. {
  2291. $aScalarArgs[$sArgName] = null;
  2292. }
  2293. // otherwise... could be an array coming from the extra params...
  2294. }
  2295. }
  2296. // Add standard magic arguments
  2297. //
  2298. $aScalarArgs['current_contact_id'] = UserRights::GetContactId(); // legacy
  2299. $oUser = UserRights::GetUserObject();
  2300. if (!is_null($oUser))
  2301. {
  2302. $aScalarArgs['current_user->object()'] = $oUser;
  2303. $oContact = UserRights::GetContactObject();
  2304. if (!is_null($oContact))
  2305. {
  2306. $aScalarArgs['current_contact->object()'] = $oContact;
  2307. }
  2308. }
  2309. return $aScalarArgs;
  2310. }
  2311. public static function MakeModifierProperties($oFilter)
  2312. {
  2313. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2314. //
  2315. $aModifierProperties = array();
  2316. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  2317. {
  2318. // Lowest precedence: the application context
  2319. $aPluginProps = ApplicationContext::GetPluginProperties($sPluginClass);
  2320. // Highest precedence: programmatically specified (or OQL)
  2321. foreach($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value)
  2322. {
  2323. $aPluginProps[$sProp] = $value;
  2324. }
  2325. if (count($aPluginProps) > 0)
  2326. {
  2327. $aModifierProperties[$sPluginClass] = $aPluginProps;
  2328. }
  2329. }
  2330. return $aModifierProperties;
  2331. }
  2332. /**
  2333. * Special processing for the hierarchical keys stored as nested sets
  2334. * @param $iId integer The identifier of the parent
  2335. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2336. * @param $stable string The name of the database table containing the hierarchical key
  2337. */
  2338. public static function HKInsertChildUnder($iId, $oAttDef, $sTable)
  2339. {
  2340. // Get the parent id.right value
  2341. if ($iId == 0)
  2342. {
  2343. // No parent, insert completely at the right of the tree
  2344. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  2345. $aRes = CMDBSource::QueryToArray($sSQL);
  2346. if (count($aRes) == 0)
  2347. {
  2348. $iMyRight = 1;
  2349. }
  2350. else
  2351. {
  2352. $iMyRight = $aRes[0]['max']+1;
  2353. }
  2354. }
  2355. else
  2356. {
  2357. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".$iId;
  2358. $iMyRight = CMDBSource::QueryToScalar($sSQL);
  2359. $sSQLUpdateRight = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + 2 WHERE `".$oAttDef->GetSQLRight()."` >= $iMyRight";
  2360. CMDBSource::Query($sSQLUpdateRight);
  2361. $sSQLUpdateLeft = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + 2 WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2362. CMDBSource::Query($sSQLUpdateLeft);
  2363. }
  2364. return array($oAttDef->GetSQLRight() => $iMyRight+1, $oAttDef->GetSQLLeft() => $iMyRight);
  2365. }
  2366. /**
  2367. * Special processing for the hierarchical keys stored as nested sets: temporary remove the branch
  2368. * @param $iId integer The identifier of the parent
  2369. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2370. * @param $sTable string The name of the database table containing the hierarchical key
  2371. */
  2372. public static function HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable)
  2373. {
  2374. $iDelta = $iMyRight - $iMyLeft + 1;
  2375. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iMyLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iMyLeft - `".$oAttDef->GetSQLLeft();
  2376. $sSQL .= "` WHERE `".$oAttDef->GetSQLLeft()."`> $iMyLeft AND `".$oAttDef->GetSQLRight()."`< $iMyRight";
  2377. CMDBSource::Query($sSQL);
  2378. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` - $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2379. CMDBSource::Query($sSQL);
  2380. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` - $iDelta WHERE `".$oAttDef->GetSQLRight()."` > $iMyRight";
  2381. CMDBSource::Query($sSQL);
  2382. }
  2383. /**
  2384. * Special processing for the hierarchical keys stored as nested sets: replug the temporary removed branch
  2385. * @param $iId integer The identifier of the parent
  2386. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2387. * @param $sTable string The name of the database table containing the hierarchical key
  2388. */
  2389. public static function HKReplugBranch($iNewLeft, $iNewRight, $oAttDef, $sTable)
  2390. {
  2391. $iDelta = $iNewRight - $iNewLeft + 1;
  2392. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iNewLeft";
  2393. CMDBSource::Query($sSQL);
  2394. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + $iDelta WHERE `".$oAttDef->GetSQLRight()."` >= $iNewLeft";
  2395. CMDBSource::Query($sSQL);
  2396. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iNewLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iNewLeft - `".$oAttDef->GetSQLLeft()."` WHERE `".$oAttDef->GetSQLRight()."`< 0";
  2397. CMDBSource::Query($sSQL);
  2398. }
  2399. /**
  2400. * Check (and updates if needed) the hierarchical keys
  2401. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2402. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2403. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2404. */
  2405. public static function CheckHKeys($bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2406. {
  2407. $bChangeNeeded = false;
  2408. foreach (self::GetClasses() as $sClass)
  2409. {
  2410. if (!self::HasTable($sClass)) continue;
  2411. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2412. {
  2413. // Check (once) all the attributes that are hierarchical keys
  2414. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey())
  2415. {
  2416. if ($bVerbose)
  2417. {
  2418. echo "The attribute $sAttCode from $sClass is a hierarchical key.\n";
  2419. }
  2420. $bResult = self::HKInit($sClass, $sAttCode, $bDiagnosticsOnly, $bVerbose, $bForceComputation);
  2421. $bChangeNeeded |= $bResult;
  2422. if ($bVerbose && !$bResult)
  2423. {
  2424. echo "Ok, the attribute $sAttCode from class $sClass seems up to date.\n";
  2425. }
  2426. }
  2427. }
  2428. }
  2429. return $bChangeNeeded;
  2430. }
  2431. /**
  2432. * Initializes (i.e converts) a hierarchy stored using a 'parent_id' external key
  2433. * into a hierarchy stored with a HierarchicalKey, by initializing the _left and _right values
  2434. * to correspond to the existing hierarchy in the database
  2435. * @param $sClass string Name of the class to process
  2436. * @param $sAttCode string Code of the attribute to process
  2437. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2438. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2439. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2440. * @return true if an update is needed (diagnostics only) / was performed
  2441. */
  2442. public static function HKInit($sClass, $sAttCode, $bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2443. {
  2444. $idx = 1;
  2445. $bUpdateNeeded = $bForceComputation;
  2446. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  2447. $sTable = self::DBGetTable($sClass, $sAttCode);
  2448. if ($oAttDef->IsHierarchicalKey())
  2449. {
  2450. // Check if some values already exist in the table for the _right value, if so, do nothing
  2451. $sRight = $oAttDef->GetSQLRight();
  2452. $sSQL = "SELECT MAX(`$sRight`) AS MaxRight FROM `$sTable`";
  2453. $iMaxRight = CMDBSource::QueryToScalar($sSQL);
  2454. $sSQL = "SELECT COUNT(*) AS Count FROM `$sTable`"; // Note: COUNT(field) returns zero if the given field contains only NULLs
  2455. $iCount = CMDBSource::QueryToScalar($sSQL);
  2456. if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0))
  2457. {
  2458. $bUpdateNeeded = true;
  2459. if ($bVerbose)
  2460. {
  2461. echo "The table '$sTable' must be updated to compute the fields $sRight and ".$oAttDef->GetSQLLeft()."\n";
  2462. }
  2463. }
  2464. if ($bForceComputation && !$bDiagnosticsOnly)
  2465. {
  2466. echo "Rebuilding the fields $sRight and ".$oAttDef->GetSQLLeft()." from table '$sTable'...\n";
  2467. }
  2468. if ($bUpdateNeeded && !$bDiagnosticsOnly)
  2469. {
  2470. try
  2471. {
  2472. CMDBSource::Query('START TRANSACTION');
  2473. self::HKInitChildren($sTable, $sAttCode, $oAttDef, 0, $idx);
  2474. CMDBSource::Query('COMMIT');
  2475. if ($bVerbose)
  2476. {
  2477. echo "Ok, table '$sTable' successfully updated.\n";
  2478. }
  2479. }
  2480. catch(Exception $e)
  2481. {
  2482. CMDBSource::Query('ROLLBACK');
  2483. throw new Exception("An error occured (".$e->getMessage().") while initializing the hierarchy for ($sClass, $sAttCode). The database was not modified.");
  2484. }
  2485. }
  2486. }
  2487. return $bUpdateNeeded;
  2488. }
  2489. /**
  2490. * Recursive helper function called by HKInit
  2491. */
  2492. protected static function HKInitChildren($sTable, $sAttCode, $oAttDef, $iId, &$iCurrIndex)
  2493. {
  2494. $sSQL = "SELECT id FROM `$sTable` WHERE `$sAttCode` = $iId";
  2495. $aRes = CMDBSource::QueryToArray($sSQL);
  2496. $aTree = array();
  2497. $sLeft = $oAttDef->GetSQLLeft();
  2498. $sRight = $oAttDef->GetSQLRight();
  2499. foreach($aRes as $aValues)
  2500. {
  2501. $iChildId = $aValues['id'];
  2502. $iLeft = $iCurrIndex++;
  2503. $aChildren = self::HKInitChildren($sTable, $sAttCode, $oAttDef, $iChildId, $iCurrIndex);
  2504. $iRight = $iCurrIndex++;
  2505. $sSQL = "UPDATE `$sTable` SET `$sLeft` = $iLeft, `$sRight` = $iRight WHERE id= $iChildId";
  2506. CMDBSource::Query($sSQL);
  2507. }
  2508. }
  2509. /**
  2510. * Update the meta enums
  2511. * See Also AttributeMetaEnum::MapValue that must be aligned with the above implementation
  2512. *
  2513. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2514. */
  2515. public static function RebuildMetaEnums($bVerbose = false)
  2516. {
  2517. foreach (self::GetClasses() as $sClass)
  2518. {
  2519. if (!self::HasTable($sClass)) continue;
  2520. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2521. {
  2522. // Check (once) all the attributes that are hierarchical keys
  2523. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef instanceof AttributeEnum)
  2524. {
  2525. if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode]))
  2526. {
  2527. foreach (self::$m_aEnumToMeta[$sClass][$sAttCode] as $sMetaAttCode => $oMetaAttDef)
  2528. {
  2529. $aMetaValues = array(); // array of (metavalue => array of values)
  2530. foreach ($oAttDef->GetAllowedValues() as $sCode => $sLabel)
  2531. {
  2532. $aMappingData = $oMetaAttDef->GetMapRule($sClass);
  2533. if ($aMappingData == null)
  2534. {
  2535. $sMetaValue = $oMetaAttDef->GetDefaultValue();
  2536. }
  2537. else
  2538. {
  2539. if (array_key_exists($sCode, $aMappingData['values']))
  2540. {
  2541. $sMetaValue = $aMappingData['values'][$sCode];
  2542. }
  2543. elseif ($oMetaAttDef->GetDefaultValue() != '')
  2544. {
  2545. $sMetaValue = $oMetaAttDef->GetDefaultValue();
  2546. }
  2547. else
  2548. {
  2549. throw new Exception('MetaModel::RebuildMetaEnums(): mapping not found for value "'.$sCode.'"" in '.$sClass.', on attribute '.self::GetAttributeOrigin($sClass, $oMetaAttDef->GetCode()).'::'.$oMetaAttDef->GetCode());
  2550. }
  2551. }
  2552. $aMetaValues[$sMetaValue][] = $sCode;
  2553. }
  2554. foreach ($aMetaValues as $sMetaValue => $aEnumValues)
  2555. {
  2556. $sMetaTable = self::DBGetTable($sClass, $sMetaAttCode);
  2557. $sEnumTable = self::DBGetTable($sClass);
  2558. $aColumns = array_keys($oMetaAttDef->GetSQLColumns());
  2559. $sMetaColumn = reset($aColumns);
  2560. $aColumns = array_keys($oAttDef->GetSQLColumns());
  2561. $sEnumColumn = reset($aColumns);
  2562. $sValueList = implode(', ', CMDBSource::Quote($aEnumValues));
  2563. $sSql = "UPDATE `$sMetaTable` JOIN `$sEnumTable` ON `$sEnumTable`.id = `$sMetaTable`.id SET `$sMetaTable`.`$sMetaColumn` = '$sMetaValue' WHERE `$sEnumTable`.`$sEnumColumn` IN ($sValueList) AND `$sMetaTable`.`$sMetaColumn` != '$sMetaValue'";
  2564. if ($bVerbose)
  2565. {
  2566. echo "Executing query: $sSql\n";
  2567. }
  2568. CMDBSource::Query($sSql);
  2569. }
  2570. }
  2571. }
  2572. }
  2573. }
  2574. }
  2575. }
  2576. public static function CheckDataSources($bDiagnostics, $bVerbose)
  2577. {
  2578. $sOQL = 'SELECT SynchroDataSource';
  2579. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  2580. $bFixNeeded = false;
  2581. if ($bVerbose && $oSet->Count() == 0)
  2582. {
  2583. echo "There are no Data Sources in the database.\n";
  2584. }
  2585. while($oSource = $oSet->Fetch())
  2586. {
  2587. if ($bVerbose)
  2588. {
  2589. echo "Checking Data Source '".$oSource->GetName()."'...\n";
  2590. $bFixNeeded = $bFixNeeded | $oSource->CheckDBConsistency($bDiagnostics, $bVerbose);
  2591. }
  2592. }
  2593. if (!$bFixNeeded && $bVerbose)
  2594. {
  2595. echo "Ok.\n";
  2596. }
  2597. return $bFixNeeded;
  2598. }
  2599. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  2600. {
  2601. if (!array_key_exists($sNewName, $aAliases))
  2602. {
  2603. $aAliases[$sNewName] = $sRealName;
  2604. return $sNewName;
  2605. }
  2606. for ($i = 1 ; $i < 100 ; $i++)
  2607. {
  2608. $sAnAlias = $sNewName.$i;
  2609. if (!array_key_exists($sAnAlias, $aAliases))
  2610. {
  2611. // Create that new alias
  2612. $aAliases[$sAnAlias] = $sRealName;
  2613. return $sAnAlias;
  2614. }
  2615. }
  2616. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  2617. }
  2618. public static function CheckDefinitions($bExitOnError = true)
  2619. {
  2620. if (count(self::GetClasses()) == 0)
  2621. {
  2622. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  2623. }
  2624. $aErrors = array();
  2625. $aSugFix = array();
  2626. foreach (self::GetClasses() as $sClass)
  2627. {
  2628. $sTable = self::DBGetTable($sClass);
  2629. $sTableLowercase = strtolower($sTable);
  2630. if ($sTableLowercase != $sTable)
  2631. {
  2632. $aErrors[$sClass][] = "Table name '".$sTable."' has upper case characters. You might encounter issues when moving your installation between Linux and Windows.";
  2633. $aSugFix[$sClass][] = "Use '$sTableLowercase' instead. Step 1: If already installed, then rename manually in the DB: RENAME TABLE `$sTable` TO `{$sTableLowercase}_tempname`, `{$sTableLowercase}_tempname` TO `$sTableLowercase`; Step 2: Rename the table in the datamodel and compile the application. Note: the MySQL statement provided in step 1 has been designed to be compatible with Windows or Linux.";
  2634. }
  2635. $aNameSpec = self::GetNameSpec($sClass);
  2636. foreach($aNameSpec[1] as $i => $sAttCode)
  2637. {
  2638. if(!self::IsValidAttCode($sClass, $sAttCode))
  2639. {
  2640. $aErrors[$sClass][] = "Unknown attribute code '".$sAttCode."' for the name definition";
  2641. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2642. }
  2643. }
  2644. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  2645. {
  2646. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  2647. {
  2648. $aErrors[$sClass][] = "Unknown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  2649. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2650. }
  2651. }
  2652. $bHasWritableAttribute = false;
  2653. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2654. {
  2655. // It makes no sense to check the attributes again and again in the subclasses
  2656. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2657. if ($oAttDef->IsExternalKey())
  2658. {
  2659. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  2660. {
  2661. $aErrors[$sClass][] = "Unknown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  2662. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  2663. }
  2664. }
  2665. elseif ($oAttDef->IsExternalField())
  2666. {
  2667. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2668. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  2669. {
  2670. $aErrors[$sClass][] = "Unknown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  2671. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  2672. }
  2673. else
  2674. {
  2675. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  2676. $sTargetClass = $oKeyAttDef->GetTargetClass();
  2677. $sExtAttCode = $oAttDef->GetExtAttCode();
  2678. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  2679. {
  2680. $aErrors[$sClass][] = "Unknown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  2681. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  2682. }
  2683. }
  2684. }
  2685. else if ($oAttDef->IsLinkSet())
  2686. {
  2687. // Do nothing...
  2688. }
  2689. else if ($oAttDef instanceof AttributeStopWatch)
  2690. {
  2691. $aThresholds = $oAttDef->ListThresholds();
  2692. if (is_array($aThresholds))
  2693. {
  2694. foreach($aThresholds as $iPercent => $aDef)
  2695. {
  2696. if (array_key_exists('highlight', $aDef))
  2697. {
  2698. if(!array_key_exists('code', $aDef['highlight']))
  2699. {
  2700. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of the $iPercent% threshold in the attribute: '$sAttCode'.";
  2701. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this threshold.";
  2702. }
  2703. else
  2704. {
  2705. $aScale = self::GetHighlightScale($sClass);
  2706. if (!array_key_exists($aDef['highlight']['code'], $aScale))
  2707. {
  2708. $aErrors[$sClass][] = "'{$aDef['highlight']['code']}' is not a valid value for the 'code' element of the $iPercent% threshold in the attribute: '$sAttCode'.";
  2709. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  2710. }
  2711. }
  2712. }
  2713. }
  2714. }
  2715. }
  2716. else // standard attributes
  2717. {
  2718. // Check that the default values definition is a valid object!
  2719. $oValSetDef = $oAttDef->GetValuesDef();
  2720. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  2721. {
  2722. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  2723. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  2724. }
  2725. else
  2726. {
  2727. // Default value must be listed in the allowed values (if defined)
  2728. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2729. if (!is_null($aAllowedValues))
  2730. {
  2731. $sDefaultValue = $oAttDef->GetDefaultValue();
  2732. if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues))
  2733. {
  2734. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  2735. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  2736. }
  2737. }
  2738. }
  2739. }
  2740. // Check dependencies
  2741. if ($oAttDef->IsWritable())
  2742. {
  2743. $bHasWritableAttribute = true;
  2744. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  2745. {
  2746. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  2747. {
  2748. $aErrors[$sClass][] = "Unknown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  2749. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2750. }
  2751. }
  2752. }
  2753. }
  2754. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  2755. {
  2756. if (method_exists($oFilterDef, '__GetRefAttribute'))
  2757. {
  2758. $oAttDef = $oFilterDef->__GetRefAttribute();
  2759. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  2760. {
  2761. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  2762. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2763. }
  2764. }
  2765. }
  2766. // Lifecycle
  2767. //
  2768. $sStateAttCode = self::GetStateAttributeCode($sClass);
  2769. if (strlen($sStateAttCode) > 0)
  2770. {
  2771. // Lifecycle - check that the state attribute does exist as an attribute
  2772. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  2773. {
  2774. $aErrors[$sClass][] = "Unknown attribute code '".$sStateAttCode."' for the state definition";
  2775. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2776. }
  2777. else
  2778. {
  2779. // Lifecycle - check that there is a value set constraint on the state attribute
  2780. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  2781. $aStates = array_keys(self::EnumStates($sClass));
  2782. if (is_null($aAllowedValuesRaw))
  2783. {
  2784. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  2785. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  2786. }
  2787. else
  2788. {
  2789. $aAllowedValues = array_keys($aAllowedValuesRaw);
  2790. // Lifecycle - check the the state attribute allowed values are defined states
  2791. foreach($aAllowedValues as $sValue)
  2792. {
  2793. if (!in_array($sValue, $aStates))
  2794. {
  2795. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  2796. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2797. }
  2798. }
  2799. // Lifecycle - check that defined states are allowed values
  2800. foreach($aStates as $sStateValue)
  2801. {
  2802. if (!in_array($sStateValue, $aAllowedValues))
  2803. {
  2804. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  2805. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2806. }
  2807. }
  2808. }
  2809. // Lifecycle - check that the action handlers are defined
  2810. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  2811. {
  2812. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  2813. {
  2814. foreach ($aTransitionDef['actions'] as $actionHandler)
  2815. {
  2816. if (is_string($actionHandler))
  2817. {
  2818. if (!method_exists($sClass, $actionHandler))
  2819. {
  2820. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2821. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  2822. }
  2823. }
  2824. else // if(is_array($actionHandler))
  2825. {
  2826. $sActionHandler = $actionHandler['verb'];
  2827. if (!method_exists($sClass, $sActionHandler))
  2828. {
  2829. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2830. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(...){return true;}]";
  2831. }
  2832. }
  2833. }
  2834. }
  2835. if (array_key_exists('highlight', $aStateDef))
  2836. {
  2837. if(!array_key_exists('code', $aStateDef['highlight']))
  2838. {
  2839. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of state: '$sStateCode'.";
  2840. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this state.";
  2841. }
  2842. else
  2843. {
  2844. $aScale = self::GetHighlightScale($sClass);
  2845. if (!array_key_exists($aStateDef['highlight']['code'], $aScale))
  2846. {
  2847. $aErrors[$sClass][] = "'{$aStateDef['highlight']['code']}' is not a valid value for the 'code' element in the 'highlight' property of state: '$sStateCode'.";
  2848. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  2849. }
  2850. }
  2851. }
  2852. }
  2853. }
  2854. }
  2855. if ($bHasWritableAttribute)
  2856. {
  2857. if (!self::HasTable($sClass))
  2858. {
  2859. $aErrors[$sClass][] = "No table has been defined for this class";
  2860. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  2861. }
  2862. }
  2863. // ZList
  2864. //
  2865. foreach(self::EnumZLists() as $sListCode)
  2866. {
  2867. foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode)
  2868. {
  2869. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  2870. {
  2871. $aErrors[$sClass][] = "Unknown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  2872. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2873. }
  2874. }
  2875. }
  2876. // Check unicity of the SQL columns
  2877. //
  2878. if (self::HasTable($sClass))
  2879. {
  2880. $aTableColumns = array(); // array of column => attcode (the column is used by this attribute)
  2881. $aTableColumns[self::DBGetKey($sClass)] = 'id';
  2882. // Check that SQL columns are declared only once
  2883. //
  2884. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2885. {
  2886. // Skip this attribute if not originaly defined in this class
  2887. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2888. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  2889. {
  2890. if (array_key_exists($sField, $aTableColumns))
  2891. {
  2892. $aErrors[$sClass][] = "Column '$sField' declared for attribute $sAttCode, but already used for attribute ".$aTableColumns[$sField];
  2893. $aSugFix[$sClass][] = "Please find another name for the SQL column";
  2894. }
  2895. else
  2896. {
  2897. $aTableColumns[$sField] = $sAttCode;
  2898. }
  2899. }
  2900. }
  2901. }
  2902. } // foreach class
  2903. if (count($aErrors) > 0)
  2904. {
  2905. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2906. echo "<h3>Business model inconsistencies have been found</h3>\n";
  2907. // #@# later -> this is the responsibility of the caller to format the output
  2908. foreach ($aErrors as $sClass => $aMessages)
  2909. {
  2910. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  2911. echo "<ul class=\"treeview\">\n";
  2912. $i = 0;
  2913. foreach ($aMessages as $sMsg)
  2914. {
  2915. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  2916. $i++;
  2917. }
  2918. echo "</ul>\n";
  2919. }
  2920. if ($bExitOnError) echo "<p>Aborting...</p>\n";
  2921. echo "</div>\n";
  2922. if ($bExitOnError) exit;
  2923. }
  2924. }
  2925. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  2926. {
  2927. if (empty($sRepairUrl)) return;
  2928. // By design, some queries might be blank, we have to ignore them
  2929. $aCleanFixes = array();
  2930. foreach($aSQLFixes as $sSQLFix)
  2931. {
  2932. if (!empty($sSQLFix))
  2933. {
  2934. $aCleanFixes[] = $sSQLFix;
  2935. }
  2936. }
  2937. if (count($aCleanFixes) == 0) return;
  2938. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  2939. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes), ENT_QUOTES, 'UTF-8')."\">\n";
  2940. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  2941. echo "</form>\n";
  2942. }
  2943. public static function DBExists($bMustBeComplete = true)
  2944. {
  2945. // returns true if at least one table exists
  2946. //
  2947. if (!CMDBSource::IsDB(self::$m_sDBName))
  2948. {
  2949. return false;
  2950. }
  2951. CMDBSource::SelectDB(self::$m_sDBName);
  2952. $aFound = array();
  2953. $aMissing = array();
  2954. foreach (self::DBEnumTables() as $sTable => $aClasses)
  2955. {
  2956. if (CMDBSource::IsTable($sTable))
  2957. {
  2958. $aFound[] = $sTable;
  2959. }
  2960. else
  2961. {
  2962. $aMissing[] = $sTable;
  2963. }
  2964. }
  2965. if (count($aFound) == 0)
  2966. {
  2967. // no expected table has been found
  2968. return false;
  2969. }
  2970. else
  2971. {
  2972. if (count($aMissing) == 0)
  2973. {
  2974. // the database is complete (still, could be some fields missing!)
  2975. return true;
  2976. }
  2977. else
  2978. {
  2979. // not all the tables, could be an older version
  2980. if ($bMustBeComplete)
  2981. {
  2982. return false;
  2983. }
  2984. else
  2985. {
  2986. return true;
  2987. }
  2988. }
  2989. }
  2990. }
  2991. public static function DBDrop()
  2992. {
  2993. $bDropEntireDB = true;
  2994. if (!empty(self::$m_sTablePrefix))
  2995. {
  2996. // Do drop only tables corresponding to the sub-database (table prefix)
  2997. // then possibly drop the DB itself (if no table remain)
  2998. foreach (CMDBSource::EnumTables() as $sTable)
  2999. {
  3000. // perform a case insensitive test because on Windows the table names become lowercase :-(
  3001. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  3002. {
  3003. CMDBSource::DropTable($sTable);
  3004. }
  3005. else
  3006. {
  3007. // There is at least one table which is out of the scope of the current application
  3008. $bDropEntireDB = false;
  3009. }
  3010. }
  3011. }
  3012. if ($bDropEntireDB)
  3013. {
  3014. CMDBSource::DropDB(self::$m_sDBName);
  3015. }
  3016. }
  3017. public static function DBCreate($aCallback = null)
  3018. {
  3019. // Note: we have to check if the DB does exist, because we may share the DB
  3020. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  3021. if (!CMDBSource::IsDB(self::$m_sDBName))
  3022. {
  3023. CMDBSource::CreateDB(self::$m_sDBName);
  3024. }
  3025. self::DBCreateTables($aCallback);
  3026. self::DBCreateViews();
  3027. }
  3028. protected static function DBCreateTables($aCallback = null)
  3029. {
  3030. list($aErrors, $aSugFix, $aCondensedQueries) = self::DBCheckFormat();
  3031. //$sSQL = implode('; ', $aCondensedQueries); Does not work - multiple queries not allowed
  3032. foreach($aCondensedQueries as $sQuery)
  3033. {
  3034. $fStart = microtime(true);
  3035. CMDBSource::CreateTable($sQuery);
  3036. $fDuration = microtime(true) - $fStart;
  3037. if ($aCallback != null)
  3038. {
  3039. call_user_func($aCallback, $sQuery, $fDuration);
  3040. }
  3041. }
  3042. }
  3043. protected static function DBCreateViews()
  3044. {
  3045. list($aErrors, $aSugFix) = self::DBCheckViews();
  3046. $aSQL = array();
  3047. foreach ($aSugFix as $sClass => $aTarget)
  3048. {
  3049. foreach ($aTarget as $aQueries)
  3050. {
  3051. foreach ($aQueries as $sQuery)
  3052. {
  3053. if (!empty($sQuery))
  3054. {
  3055. //$aSQL[] = $sQuery;
  3056. // forces a refresh of cached information
  3057. CMDBSource::CreateTable($sQuery);
  3058. }
  3059. }
  3060. }
  3061. }
  3062. }
  3063. public static function DBDump()
  3064. {
  3065. $aDataDump = array();
  3066. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3067. {
  3068. $aRows = CMDBSource::DumpTable($sTable);
  3069. $aDataDump[$sTable] = $aRows;
  3070. }
  3071. return $aDataDump;
  3072. }
  3073. /*
  3074. * Determines wether the target DB is frozen or not
  3075. */
  3076. public static function DBIsReadOnly()
  3077. {
  3078. // Improvement: check the mySQL variable -> Read-only
  3079. if (UserRights::IsAdministrator())
  3080. {
  3081. return (!self::DBHasAccess(ACCESS_ADMIN_WRITE));
  3082. }
  3083. else
  3084. {
  3085. return (!self::DBHasAccess(ACCESS_USER_WRITE));
  3086. }
  3087. }
  3088. public static function DBHasAccess($iRequested = ACCESS_FULL)
  3089. {
  3090. $iMode = self::$m_oConfig->Get('access_mode');
  3091. if (($iMode & $iRequested) == 0) return false;
  3092. return true;
  3093. }
  3094. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  3095. {
  3096. $sValue = Dict::S($sKey, 'x-no-nothing');
  3097. if ($sValue == 'x-no-nothing')
  3098. {
  3099. $bNotInDico = true;
  3100. $sValue = $sValueFromOldSystem;
  3101. if (strlen($sValue) == 0)
  3102. {
  3103. $sValue = $sDefaultValue;
  3104. }
  3105. }
  3106. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  3107. }
  3108. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  3109. {
  3110. $sRes = '';
  3111. $sRes .= "// Dictionnay conventions\n";
  3112. $sRes .= htmlentities("// Class:<class_name>\n", ENT_QUOTES, 'UTF-8');
  3113. $sRes .= htmlentities("// Class:<class_name>+\n", ENT_QUOTES, 'UTF-8');
  3114. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n", ENT_QUOTES, 'UTF-8');
  3115. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n", ENT_QUOTES, 'UTF-8');
  3116. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n", ENT_QUOTES, 'UTF-8');
  3117. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n", ENT_QUOTES, 'UTF-8');
  3118. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n", ENT_QUOTES, 'UTF-8');
  3119. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n", ENT_QUOTES, 'UTF-8');
  3120. $sRes .= "\n";
  3121. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  3122. // Need to invent the "module", to characterize the origins of a class
  3123. if (strlen($sModules) == 0)
  3124. {
  3125. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  3126. }
  3127. else
  3128. {
  3129. $aModules = explode(', ', $sModules);
  3130. }
  3131. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3132. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  3133. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3134. foreach ($aModules as $sCategory)
  3135. {
  3136. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3137. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  3138. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3139. $sRes .= "//\n";
  3140. $sRes .= "\n";
  3141. foreach (self::GetClasses($sCategory) as $sClass)
  3142. {
  3143. if (!self::HasTable($sClass)) continue;
  3144. $bNotInDico = false;
  3145. $sClassRes = "//\n";
  3146. $sClassRes .= "// Class: $sClass\n";
  3147. $sClassRes .= "//\n";
  3148. $sClassRes .= "\n";
  3149. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  3150. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  3151. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  3152. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  3153. {
  3154. // Skip this attribute if not originaly defined in this class
  3155. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3156. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  3157. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  3158. if ($oAttDef instanceof AttributeEnum)
  3159. {
  3160. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  3161. {
  3162. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  3163. {
  3164. if (array_key_exists('label', $aStateData))
  3165. {
  3166. $sValue = $aStateData['label'];
  3167. }
  3168. else
  3169. {
  3170. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  3171. }
  3172. if (array_key_exists('description', $aStateData))
  3173. {
  3174. $sValuePlus = $aStateData['description'];
  3175. }
  3176. else
  3177. {
  3178. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  3179. }
  3180. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  3181. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  3182. }
  3183. }
  3184. else
  3185. {
  3186. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  3187. {
  3188. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  3189. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  3190. }
  3191. }
  3192. }
  3193. }
  3194. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  3195. {
  3196. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  3197. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  3198. }
  3199. $sClassRes .= "));\n";
  3200. $sClassRes .= "\n";
  3201. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  3202. {
  3203. $sRes .= $sClassRes;
  3204. }
  3205. }
  3206. }
  3207. return $sRes;
  3208. }
  3209. public static function DBCheckFormat()
  3210. {
  3211. $aErrors = array();
  3212. $aSugFix = array();
  3213. // A new way of representing things to be done - quicker to execute !
  3214. $aCreateTable = array(); // array of <table> => <table options>
  3215. $aCreateTableItems = array(); // array of <table> => array of <create definition>
  3216. $aAlterTableItems = array(); // array of <table> => <alter specification>
  3217. foreach (self::GetClasses() as $sClass)
  3218. {
  3219. if (!self::HasTable($sClass)) continue;
  3220. // Check that the table exists
  3221. //
  3222. $sTable = self::DBGetTable($sClass);
  3223. $sKeyField = self::DBGetKey($sClass);
  3224. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  3225. $sKeyFieldDefinition = "`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  3226. if (!CMDBSource::IsTable($sTable))
  3227. {
  3228. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  3229. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` ($sKeyFieldDefinition) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3230. $aCreateTable[$sTable] = "ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3231. $aCreateTableItems[$sTable][$sKeyField] = $sKeyFieldDefinition;
  3232. }
  3233. // Check that the key field exists
  3234. //
  3235. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  3236. {
  3237. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  3238. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD $sKeyFieldDefinition";
  3239. if (!array_key_exists($sTable, $aCreateTable))
  3240. {
  3241. $aAlterTableItems[$sTable][$sKeyField] = "ADD $sKeyFieldDefinition";
  3242. }
  3243. }
  3244. else
  3245. {
  3246. // Check the key field properties
  3247. //
  3248. if (!CMDBSource::IsKey($sTable, $sKeyField))
  3249. {
  3250. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  3251. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  3252. if (!array_key_exists($sTable, $aCreateTable))
  3253. {
  3254. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3255. }
  3256. }
  3257. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  3258. {
  3259. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  3260. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` $sKeyFieldDefinition";
  3261. if (!array_key_exists($sTable, $aCreateTable))
  3262. {
  3263. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3264. }
  3265. }
  3266. }
  3267. // Check that any defined field exists
  3268. //
  3269. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  3270. $aTableInfo['Fields'][$sKeyField]['used'] = true;
  3271. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3272. {
  3273. // Skip this attribute if not originaly defined in this class
  3274. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3275. foreach($oAttDef->GetSQLColumns(true) as $sField => $sDBFieldSpec)
  3276. {
  3277. // Keep track of columns used by iTop
  3278. $aTableInfo['Fields'][$sField]['used'] = true;
  3279. $bIndexNeeded = $oAttDef->RequiresIndex();
  3280. $sFieldDefinition = "`$sField` $sDBFieldSpec";
  3281. if (!CMDBSource::IsField($sTable, $sField))
  3282. {
  3283. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  3284. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD $sFieldDefinition";
  3285. if ($bIndexNeeded)
  3286. {
  3287. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3288. }
  3289. if (array_key_exists($sTable, $aCreateTable))
  3290. {
  3291. $aCreateTableItems[$sTable][$sField] = $sFieldDefinition;
  3292. if ($bIndexNeeded)
  3293. {
  3294. $aCreateTableItems[$sTable][] = "INDEX (`$sField`)";
  3295. }
  3296. }
  3297. else
  3298. {
  3299. $aAlterTableItems[$sTable][$sField] = "ADD $sFieldDefinition";
  3300. if ($bIndexNeeded)
  3301. {
  3302. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3303. }
  3304. }
  3305. }
  3306. else
  3307. {
  3308. // The field already exists, does it have the relevant properties?
  3309. //
  3310. $bToBeChanged = false;
  3311. $sActualFieldSpec = CMDBSource::GetFieldSpec($sTable, $sField);
  3312. if (strcasecmp($sDBFieldSpec, $sActualFieldSpec) != 0)
  3313. {
  3314. $bToBeChanged = true;
  3315. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldSpec' while expecting '$sDBFieldSpec'";
  3316. }
  3317. if ($bToBeChanged)
  3318. {
  3319. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3320. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3321. }
  3322. // Create indexes (external keys only... so far)
  3323. //
  3324. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField, array($sField)))
  3325. {
  3326. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  3327. if (CMDBSource::HasIndex($sTable, $sField))
  3328. {
  3329. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` DROP INDEX `$sField`, ADD INDEX (`$sField`)";
  3330. $aAlterTableItems[$sTable][] = "DROP INDEX `$sField`";
  3331. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3332. }
  3333. else
  3334. {
  3335. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3336. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3337. }
  3338. }
  3339. }
  3340. }
  3341. }
  3342. // Check indexes
  3343. foreach (self::DBGetIndexes($sClass) as $aColumns)
  3344. {
  3345. $sIndexId = implode('_', $aColumns);
  3346. if(!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns))
  3347. {
  3348. $sColumns = "`".implode("`, `", $aColumns)."`";
  3349. if (CMDBSource::HasIndex($sTable, $sIndexId))
  3350. {
  3351. $aErrors[$sClass]['*'][] = "Wrong index '$sIndexId' ($sColumns) in table '$sTable'";
  3352. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`, ADD INDEX `$sIndexId` ($sColumns)";
  3353. }
  3354. else
  3355. {
  3356. $aErrors[$sClass]['*'][] = "Missing index '$sIndexId' ($sColumns) in table '$sTable'";
  3357. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)";
  3358. }
  3359. if (array_key_exists($sTable, $aCreateTable))
  3360. {
  3361. $aCreateTableItems[$sTable][] = "INDEX `$sIndexId` ($sColumns)";
  3362. }
  3363. else
  3364. {
  3365. if (CMDBSource::HasIndex($sTable, $sIndexId))
  3366. {
  3367. $aAlterTableItems[$sTable][] = "DROP INDEX `$sIndexId`";
  3368. }
  3369. $aAlterTableItems[$sTable][] = "ADD INDEX `$sIndexId` ($sColumns)";
  3370. }
  3371. }
  3372. }
  3373. // Find out unused columns
  3374. //
  3375. foreach($aTableInfo['Fields'] as $sField => $aFieldData)
  3376. {
  3377. if (!isset($aFieldData['used']) || !$aFieldData['used'])
  3378. {
  3379. $aErrors[$sClass]['*'][] = "Column '$sField' in table '$sTable' is not used";
  3380. if (!CMDBSource::IsNullAllowed($sTable, $sField))
  3381. {
  3382. // Allow null values so that new record can be inserted
  3383. // without specifying the value of this unknown column
  3384. $sFieldDefinition = "`$sField` ".CMDBSource::GetFieldType($sTable, $sField).' NULL';
  3385. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3386. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3387. }
  3388. }
  3389. }
  3390. }
  3391. $aCondensedQueries = array();
  3392. foreach($aCreateTable as $sTable => $sTableOptions)
  3393. {
  3394. $sTableItems = implode(', ', $aCreateTableItems[$sTable]);
  3395. $aCondensedQueries[] = "CREATE TABLE `$sTable` ($sTableItems) $sTableOptions";
  3396. }
  3397. foreach($aAlterTableItems as $sTable => $aChangeList)
  3398. {
  3399. $sChangeList = implode(', ', $aChangeList);
  3400. $aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList";
  3401. }
  3402. return array($aErrors, $aSugFix, $aCondensedQueries);
  3403. }
  3404. public static function DBCheckViews()
  3405. {
  3406. $aErrors = array();
  3407. $aSugFix = array();
  3408. // Reporting views (must be created after any other table)
  3409. //
  3410. foreach (self::GetClasses('bizmodel') as $sClass)
  3411. {
  3412. $sView = self::DBGetView($sClass);
  3413. if (CMDBSource::IsTable($sView))
  3414. {
  3415. // Check that the view is complete
  3416. //
  3417. // Note: checking the list of attributes is not enough because the columns can be stable while the SELECT is not stable
  3418. // Example: new way to compute the friendly name
  3419. // The correct comparison algorithm is to compare the queries,
  3420. // by using "SHOW CREATE VIEW" (MySQL 5.0.1 required) or to look into INFORMATION_SCHEMA/views
  3421. // both requiring some privileges
  3422. // Decision: to simplify, let's consider the views as being wrong anytime
  3423. if (true)
  3424. {
  3425. // Rework the view
  3426. //
  3427. $oFilter = new DBObjectSearch($sClass, '');
  3428. $oFilter->AllowAllData();
  3429. $sSQL = $oFilter->MakeSelectQuery();
  3430. $aErrors[$sClass]['*'][] = "Redeclare view '$sView' (systematic - to support an eventual change in the friendly name computation)";
  3431. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  3432. }
  3433. }
  3434. else
  3435. {
  3436. // Create the view
  3437. //
  3438. $oFilter = new DBObjectSearch($sClass, '');
  3439. $oFilter->AllowAllData();
  3440. $sSQL = $oFilter->MakeSelectQuery();
  3441. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  3442. $aSugFix[$sClass]['*'][] = "DROP VIEW IF EXISTS `$sView`";
  3443. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  3444. }
  3445. }
  3446. return array($aErrors, $aSugFix);
  3447. }
  3448. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  3449. {
  3450. $sRootClass = self::GetRootClass($sClass);
  3451. $sTable = self::DBGetTable($sClass);
  3452. $sKeyField = self::DBGetKey($sClass);
  3453. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3454. {
  3455. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3456. }
  3457. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3458. if (count($aWrongRecords) == 0) return;
  3459. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3460. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3461. foreach ($aWrongRecords as $iRecordId)
  3462. {
  3463. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3464. {
  3465. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3466. {
  3467. case 'Delete':
  3468. // Already planned for a deletion
  3469. // Let's concatenate the errors description together
  3470. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3471. break;
  3472. case 'Update':
  3473. // Let's plan a deletion
  3474. break;
  3475. }
  3476. }
  3477. else
  3478. {
  3479. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3480. }
  3481. if (!$bProcessingFriends)
  3482. {
  3483. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  3484. {
  3485. // Something new to be deleted...
  3486. $iNewDelCount++;
  3487. }
  3488. }
  3489. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  3490. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  3491. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3492. $aPlannedDel[$sTable][] = $iRecordId;
  3493. }
  3494. // Now make sure that we would delete the records of the other tables for that class
  3495. //
  3496. if (!$bProcessingFriends)
  3497. {
  3498. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  3499. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  3500. {
  3501. $sFriendTable = self::DBGetTable($sFriendClass);
  3502. $sFriendKey = self::DBGetKey($sFriendClass);
  3503. // skip the current table
  3504. if ($sFriendTable == $sTable) continue;
  3505. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  3506. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  3507. }
  3508. }
  3509. }
  3510. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3511. {
  3512. $sRootClass = self::GetRootClass($sClass);
  3513. $sTable = self::DBGetTable($sClass);
  3514. $sKeyField = self::DBGetKey($sClass);
  3515. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3516. {
  3517. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3518. }
  3519. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3520. if (count($aWrongRecords) == 0) return;
  3521. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3522. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3523. foreach ($aWrongRecords as $iRecordId)
  3524. {
  3525. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3526. {
  3527. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3528. {
  3529. case 'Delete':
  3530. // No need to update, the record will be deleted!
  3531. break;
  3532. case 'Update':
  3533. // Already planned for an update
  3534. // Add this new update spec to the list
  3535. $bFoundSameSpec = false;
  3536. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  3537. {
  3538. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  3539. {
  3540. $bFoundSameSpec = true;
  3541. }
  3542. }
  3543. if (!$bFoundSameSpec)
  3544. {
  3545. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  3546. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3547. }
  3548. break;
  3549. }
  3550. }
  3551. else
  3552. {
  3553. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3554. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  3555. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  3556. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3557. }
  3558. }
  3559. }
  3560. // returns the count of records found for deletion
  3561. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3562. {
  3563. foreach (self::GetClasses() as $sClass)
  3564. {
  3565. if (!self::HasTable($sClass)) continue;
  3566. $sRootClass = self::GetRootClass($sClass);
  3567. $sTable = self::DBGetTable($sClass);
  3568. $sKeyField = self::DBGetKey($sClass);
  3569. if (!self::IsStandaloneClass($sClass))
  3570. {
  3571. if (self::IsRootClass($sClass))
  3572. {
  3573. // Check that the final class field contains the name of a class which inherited from the current class
  3574. //
  3575. $sFinalClassField = self::DBGetClassField($sClass);
  3576. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  3577. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  3578. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  3579. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3580. }
  3581. else
  3582. {
  3583. $sRootTable = self::DBGetTable($sRootClass);
  3584. $sRootKey = self::DBGetKey($sRootClass);
  3585. $sFinalClassField = self::DBGetClassField($sRootClass);
  3586. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  3587. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  3588. // Check that any record found here has its counterpart in the root table
  3589. // and which refers to a child class
  3590. //
  3591. $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";
  3592. 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);
  3593. // Check that any record found in the root table and referring to a child class
  3594. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  3595. //
  3596. $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)";
  3597. 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);
  3598. }
  3599. }
  3600. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3601. {
  3602. // Skip this attribute if not defined in this table
  3603. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3604. if ($oAttDef->IsExternalKey())
  3605. {
  3606. // Check that any external field is pointing to an existing object
  3607. //
  3608. $sRemoteClass = $oAttDef->GetTargetClass();
  3609. $sRemoteTable = self::DBGetTable($sRemoteClass);
  3610. $sRemoteKey = self::DBGetKey($sRemoteClass);
  3611. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3612. $sExtKeyField = current($aCols); // get the first column for an external key
  3613. // Note: a class/table may have an external key on itself
  3614. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  3615. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  3616. if ($oAttDef->IsNullAllowed())
  3617. {
  3618. // Exclude the records pointing to 0/null from the errors
  3619. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  3620. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  3621. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3622. }
  3623. else
  3624. {
  3625. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3626. }
  3627. // Do almost the same, taking into account the records planned for deletion
  3628. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  3629. {
  3630. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  3631. // but in that case you won't be able to track the root cause (cascading)
  3632. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  3633. if ($oAttDef->IsNullAllowed())
  3634. {
  3635. // Exclude the records pointing to 0/null from the errors
  3636. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  3637. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  3638. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3639. }
  3640. else
  3641. {
  3642. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3643. }
  3644. }
  3645. }
  3646. else if ($oAttDef->IsDirectField())
  3647. {
  3648. // Check that the values fit the allowed values
  3649. //
  3650. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  3651. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  3652. {
  3653. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  3654. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3655. $sMyAttributeField = current($aCols); // get the first column for the moment
  3656. $sDefaultValue = $oAttDef->GetDefaultValue();
  3657. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  3658. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3659. }
  3660. }
  3661. }
  3662. }
  3663. }
  3664. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  3665. {
  3666. // Records in error, and action to be taken: delete or update
  3667. // by RootClass/Table/Record
  3668. $aErrorsAndFixes = array();
  3669. // Records to be ignored in the current/next pass
  3670. // by Table = array of RecordId
  3671. $aPlannedDel = array();
  3672. // Count of errors in the next pass: no error means that we can leave...
  3673. $iErrorCount = 0;
  3674. // Limit in case of a bug in the algorythm
  3675. $iLoopCount = 0;
  3676. $iNewDelCount = 1; // startup...
  3677. while ($iNewDelCount > 0)
  3678. {
  3679. $iNewDelCount = 0;
  3680. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3681. $iErrorCount += $iNewDelCount;
  3682. // Safety net #1 - limit the planned deletions
  3683. //
  3684. $iMaxDel = 1000;
  3685. $iPlannedDel = 0;
  3686. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  3687. {
  3688. $iPlannedDel += count($aPlannedDelOnTable);
  3689. }
  3690. if ($iPlannedDel > $iMaxDel)
  3691. {
  3692. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  3693. break;
  3694. }
  3695. // Safety net #2 - limit the iterations
  3696. //
  3697. $iLoopCount++;
  3698. $iMaxLoops = 10;
  3699. if ($iLoopCount > $iMaxLoops)
  3700. {
  3701. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  3702. break;
  3703. }
  3704. }
  3705. // Display the results
  3706. //
  3707. $iIssueCount = 0;
  3708. $aFixesDelete = array();
  3709. $aFixesUpdate = array();
  3710. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  3711. {
  3712. foreach ($aTables as $sTable => $aRecords)
  3713. {
  3714. foreach ($aRecords as $iRecord => $aError)
  3715. {
  3716. $sAction = $aError['Action'];
  3717. $sReason = $aError['Reason'];
  3718. $iPass = $aError['Pass'];
  3719. switch ($sAction)
  3720. {
  3721. case 'Delete':
  3722. $sActionDetails = "";
  3723. $aFixesDelete[$sTable][] = $iRecord;
  3724. break;
  3725. case 'Update':
  3726. $aUpdateDesc = array();
  3727. foreach($aError['Action_Details'] as $aUpdateSpec)
  3728. {
  3729. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  3730. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  3731. }
  3732. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  3733. break;
  3734. default:
  3735. $sActionDetails = "bug: unknown action '$sAction'";
  3736. }
  3737. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  3738. $iIssueCount++;
  3739. }
  3740. }
  3741. }
  3742. if ($iIssueCount > 0)
  3743. {
  3744. // Build the queries to fix in the database
  3745. //
  3746. // First step, be able to get class data out of the table name
  3747. // Could be optimized, because we've made the job earlier... but few benefits, so...
  3748. $aTable2ClassProp = array();
  3749. foreach (self::GetClasses() as $sClass)
  3750. {
  3751. if (!self::HasTable($sClass)) continue;
  3752. $sRootClass = self::GetRootClass($sClass);
  3753. $sTable = self::DBGetTable($sClass);
  3754. $sKeyField = self::DBGetKey($sClass);
  3755. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3756. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  3757. }
  3758. // Second step, build a flat list of SQL queries
  3759. $aSQLFixes = array();
  3760. $iPlannedUpdate = 0;
  3761. foreach ($aFixesUpdate as $sTable => $aColumns)
  3762. {
  3763. foreach ($aColumns as $sColumn => $aNewValues)
  3764. {
  3765. foreach ($aNewValues as $sNewValue => $aRecords)
  3766. {
  3767. $iPlannedUpdate += count($aRecords);
  3768. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  3769. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  3770. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  3771. }
  3772. }
  3773. }
  3774. $iPlannedDel = 0;
  3775. foreach ($aFixesDelete as $sTable => $aRecords)
  3776. {
  3777. $iPlannedDel += count($aRecords);
  3778. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  3779. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  3780. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  3781. }
  3782. // Report the results
  3783. //
  3784. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3785. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  3786. // #@# later -> this is the responsibility of the caller to format the output
  3787. echo "<ul class=\"treeview\">\n";
  3788. foreach ($aIssues as $sIssueDesc)
  3789. {
  3790. echo "<li>$sIssueDesc</li>\n";
  3791. }
  3792. echo "</ul>\n";
  3793. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  3794. echo "<p>Aborting...</p>\n";
  3795. echo "</div>\n";
  3796. exit;
  3797. }
  3798. }
  3799. public static function Startup($config, $bModelOnly = false, $bAllowCache = true, $bTraceSourceFiles = false)
  3800. {
  3801. if (!defined('MODULESROOT'))
  3802. {
  3803. define('MODULESROOT', APPROOT.'env-'.utils::GetCurrentEnvironment().'/');
  3804. self::$m_bTraceSourceFiles = $bTraceSourceFiles;
  3805. // $config can be either a filename, or a Configuration object (volatile!)
  3806. if ($config instanceof Config)
  3807. {
  3808. self::LoadConfig($config, $bAllowCache);
  3809. }
  3810. else
  3811. {
  3812. self::LoadConfig(new Config($config), $bAllowCache);
  3813. }
  3814. if ($bModelOnly) return;
  3815. }
  3816. CMDBSource::SelectDB(self::$m_sDBName);
  3817. foreach(get_declared_classes() as $sPHPClass)
  3818. {
  3819. if (is_subclass_of($sPHPClass, 'ModuleHandlerAPI'))
  3820. {
  3821. $aCallSpec = array($sPHPClass, 'OnMetaModelStarted');
  3822. call_user_func_array($aCallSpec, array());
  3823. }
  3824. }
  3825. if (false)
  3826. {
  3827. echo "Debug<br/>\n";
  3828. self::static_var_dump();
  3829. }
  3830. }
  3831. public static function LoadConfig($oConfiguration, $bAllowCache = false)
  3832. {
  3833. self::$m_oConfig = $oConfiguration;
  3834. // Set log ASAP
  3835. if (self::$m_oConfig->GetLogGlobal())
  3836. {
  3837. if (self::$m_oConfig->GetLogIssue())
  3838. {
  3839. self::$m_bLogIssue = true;
  3840. IssueLog::Enable(APPROOT.'log/error.log');
  3841. }
  3842. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  3843. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  3844. ToolsLog::Enable(APPROOT.'log/tools.log');
  3845. }
  3846. else
  3847. {
  3848. self::$m_bLogIssue = false;
  3849. self::$m_bLogNotification = false;
  3850. self::$m_bLogWebService = false;
  3851. }
  3852. ExecutionKPI::EnableDuration(self::$m_oConfig->Get('log_kpi_duration'));
  3853. ExecutionKPI::EnableMemory(self::$m_oConfig->Get('log_kpi_memory'));
  3854. ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id'));
  3855. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  3856. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  3857. self::$m_bUseAPCCache = $bAllowCache
  3858. && self::$m_oConfig->Get('apc_cache.enabled')
  3859. && function_exists('apc_fetch')
  3860. && function_exists('apc_store');
  3861. DBSearch::EnableQueryCache(self::$m_oConfig->GetQueryCacheEnabled(), self::$m_bUseAPCCache, self::$m_oConfig->Get('apc_cache.query_ttl'));
  3862. DBSearch::EnableQueryTrace(self::$m_oConfig->GetLogQueries());
  3863. DBSearch::EnableQueryIndentation(self::$m_oConfig->Get('query_indentation_enabled'));
  3864. DBSearch::EnableOptimizeQuery(self::$m_oConfig->Get('query_optimization_enabled'));
  3865. // PHP timezone first...
  3866. //
  3867. $sPHPTimezone = self::$m_oConfig->Get('timezone');
  3868. if ($sPHPTimezone == '')
  3869. {
  3870. // Leave as is... up to the admin to set a value somewhere...
  3871. //$sPHPTimezone = date_default_timezone_get();
  3872. }
  3873. else
  3874. {
  3875. date_default_timezone_set($sPHPTimezone);
  3876. }
  3877. // Note: load the dictionary as soon as possible, because it might be
  3878. // needed when some error occur
  3879. $sAppIdentity = 'itop-'.MetaModel::GetEnvironmentId();
  3880. $bDictInitializedFromData = false;
  3881. if (!self::$m_bUseAPCCache || !Dict::InCache($sAppIdentity))
  3882. {
  3883. $bDictInitializedFromData = true;
  3884. foreach (self::$m_oConfig->GetDictionaries() as $sModule => $sToInclude)
  3885. {
  3886. self::IncludeModule('dictionaries', $sToInclude);
  3887. }
  3888. }
  3889. // Set the language... after the dictionaries have been loaded!
  3890. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  3891. // Romain: this is the only way I've found to cope with the fact that
  3892. // classes have to be derived from cmdbabstract (to be editable in the UI)
  3893. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  3894. foreach (self::$m_oConfig->GetAppModules() as $sModule => $sToInclude)
  3895. {
  3896. self::IncludeModule('application', $sToInclude);
  3897. }
  3898. foreach (self::$m_oConfig->GetDataModels() as $sModule => $sToInclude)
  3899. {
  3900. self::IncludeModule('business', $sToInclude);
  3901. }
  3902. foreach (self::$m_oConfig->GetWebServiceCategories() as $sModule => $sToInclude)
  3903. {
  3904. self::IncludeModule('webservice', $sToInclude);
  3905. }
  3906. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  3907. {
  3908. self::IncludeModule('addons', $sToInclude);
  3909. }
  3910. $sServer = self::$m_oConfig->GetDBHost();
  3911. $sUser = self::$m_oConfig->GetDBUser();
  3912. $sPwd = self::$m_oConfig->GetDBPwd();
  3913. $sSource = self::$m_oConfig->GetDBName();
  3914. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  3915. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  3916. $sCollation = self::$m_oConfig->GetDBCollation();
  3917. if (self::$m_bUseAPCCache)
  3918. {
  3919. $oKPI = new ExecutionKPI();
  3920. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  3921. //
  3922. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-metamodel';
  3923. $result = apc_fetch($sOqlAPCCacheId);
  3924. if (is_array($result))
  3925. {
  3926. // todo - verifier que toutes les classes mentionnees ici sont chargees dans InitClasses()
  3927. self::$m_aExtensionClasses = $result['m_aExtensionClasses'];
  3928. self::$m_Category2Class = $result['m_Category2Class'];
  3929. self::$m_aRootClasses = $result['m_aRootClasses'];
  3930. self::$m_aParentClasses = $result['m_aParentClasses'];
  3931. self::$m_aChildClasses = $result['m_aChildClasses'];
  3932. self::$m_aClassParams = $result['m_aClassParams'];
  3933. self::$m_aAttribDefs = $result['m_aAttribDefs'];
  3934. self::$m_aAttribOrigins = $result['m_aAttribOrigins'];
  3935. self::$m_aExtKeyFriends = $result['m_aExtKeyFriends'];
  3936. self::$m_aIgnoredAttributes = $result['m_aIgnoredAttributes'];
  3937. self::$m_aFilterDefs = $result['m_aFilterDefs'];
  3938. self::$m_aFilterOrigins = $result['m_aFilterOrigins'];
  3939. self::$m_aListInfos = $result['m_aListInfos'];
  3940. self::$m_aListData = $result['m_aListData'];
  3941. self::$m_aRelationInfos = $result['m_aRelationInfos'];
  3942. self::$m_aStates = $result['m_aStates'];
  3943. self::$m_aStimuli = $result['m_aStimuli'];
  3944. self::$m_aTransitions = $result['m_aTransitions'];
  3945. self::$m_aHighlightScales = $result['m_aHighlightScales'];
  3946. self::$m_aEnumToMeta = $result['m_aEnumToMeta'];
  3947. }
  3948. $oKPI->ComputeAndReport('Metamodel APC (fetch + read)');
  3949. }
  3950. if (count(self::$m_aAttribDefs) == 0)
  3951. {
  3952. // The includes have been included, let's browse the existing classes and
  3953. // develop some data based on the proposed model
  3954. $oKPI = new ExecutionKPI();
  3955. self::InitClasses($sTablePrefix);
  3956. $oKPI->ComputeAndReport('Initialization of Data model structures');
  3957. if (self::$m_bUseAPCCache)
  3958. {
  3959. $oKPI = new ExecutionKPI();
  3960. $aCache = array();
  3961. $aCache['m_aExtensionClasses'] = self::$m_aExtensionClasses;
  3962. $aCache['m_Category2Class'] = self::$m_Category2Class;
  3963. $aCache['m_aRootClasses'] = self::$m_aRootClasses; // array of "classname" => "rootclass"
  3964. $aCache['m_aParentClasses'] = self::$m_aParentClasses; // array of ("classname" => array of "parentclass")
  3965. $aCache['m_aChildClasses'] = self::$m_aChildClasses; // array of ("classname" => array of "childclass")
  3966. $aCache['m_aClassParams'] = self::$m_aClassParams; // array of ("classname" => array of class information)
  3967. $aCache['m_aAttribDefs'] = self::$m_aAttribDefs; // array of ("classname" => array of attributes)
  3968. $aCache['m_aAttribOrigins'] = self::$m_aAttribOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  3969. $aCache['m_aExtKeyFriends'] = self::$m_aExtKeyFriends; // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  3970. $aCache['m_aIgnoredAttributes'] = self::$m_aIgnoredAttributes; //array of ("classname" => array of ("attcode")
  3971. $aCache['m_aFilterDefs'] = self::$m_aFilterDefs; // array of ("classname" => array filterdef)
  3972. $aCache['m_aFilterOrigins'] = self::$m_aFilterOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  3973. $aCache['m_aListInfos'] = self::$m_aListInfos; // array of ("listcode" => various info on the list, common to every classes)
  3974. $aCache['m_aListData'] = self::$m_aListData; // array of ("classname" => array of "listcode" => list)
  3975. $aCache['m_aRelationInfos'] = self::$m_aRelationInfos; // array of ("relcode" => various info on the list, common to every classes)
  3976. $aCache['m_aStates'] = self::$m_aStates; // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  3977. $aCache['m_aStimuli'] = self::$m_aStimuli; // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  3978. $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)))
  3979. $aCache['m_aHighlightScales'] = self::$m_aHighlightScales; // array of ("classname" => array of higlightcodes)))
  3980. $aCache['m_aEnumToMeta'] = self::$m_aEnumToMeta;
  3981. apc_store($sOqlAPCCacheId, $aCache);
  3982. $oKPI->ComputeAndReport('Metamodel APC (store)');
  3983. }
  3984. }
  3985. if (self::$m_bUseAPCCache && $bDictInitializedFromData)
  3986. {
  3987. Dict::InitCache($sAppIdentity);
  3988. }
  3989. self::$m_sDBName = $sSource;
  3990. self::$m_sTablePrefix = $sTablePrefix;
  3991. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  3992. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  3993. // Later when timezone implementation is correctly done: CMDBSource::SetTimezone($sDBTimezone);
  3994. }
  3995. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  3996. {
  3997. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  3998. }
  3999. public static function GetModuleParameter($sModule, $sProperty, $defaultvalue = null)
  4000. {
  4001. $value = $defaultvalue;
  4002. if (!array_key_exists($sModule, self::$m_aModulesParameters))
  4003. {
  4004. }
  4005. if (!self::$m_aModulesParameters[$sModule] == null)
  4006. {
  4007. $value = self::$m_aModulesParameters[$sModule]->Get($sProperty, $defaultvalue);
  4008. }
  4009. return $value;
  4010. }
  4011. public static function GetConfig()
  4012. {
  4013. return self::$m_oConfig;
  4014. }
  4015. public static function GetEnvironmentId()
  4016. {
  4017. return md5(APPROOT).'-'.utils::GetCurrentEnvironment();
  4018. }
  4019. protected static $m_aExtensionClasses = array();
  4020. protected static function IncludeModule($sModuleType, $sToInclude)
  4021. {
  4022. $sFirstChar = substr($sToInclude, 0, 1);
  4023. $sSecondChar = substr($sToInclude, 1, 1);
  4024. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  4025. {
  4026. // It is a relative path, prepend APPROOT
  4027. if (substr($sToInclude, 0, 3) == '../')
  4028. {
  4029. // Preserve compatibility with config files written before 1.0.1
  4030. // Replace '../' by '<root>/'
  4031. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  4032. }
  4033. else
  4034. {
  4035. $sFile = APPROOT.'/'.$sToInclude;
  4036. }
  4037. }
  4038. else
  4039. {
  4040. // Leave as is - should be an absolute path
  4041. $sFile = $sToInclude;
  4042. }
  4043. if (!file_exists($sFile))
  4044. {
  4045. $sConfigFile = self::$m_oConfig->GetLoadedFile();
  4046. if (strlen($sConfigFile) > 0)
  4047. {
  4048. throw new CoreException('Include: wrong file name in configuration file', array('config file' => $sConfigFile, 'section' => $sModuleType, 'filename' => $sFile));
  4049. }
  4050. else
  4051. {
  4052. // The configuration is in memory only
  4053. throw new CoreException('Include: wrong file name in configuration file (in memory)', array('section' => $sModuleType, 'filename' => $sFile));
  4054. }
  4055. }
  4056. // Note: We do not expect the modules to output characters while loading them.
  4057. // Therefore, and because unexpected characters can corrupt the output,
  4058. // they must be trashed here.
  4059. // Additionnaly, pages aiming at delivering data in their output can call WebPage::TrashUnexpectedOutput()
  4060. // to get rid of chars that could be generated during the execution of the code
  4061. ob_start();
  4062. require_once($sFile);
  4063. $sPreviousContent = ob_get_clean();
  4064. if (self::$m_oConfig->Get('debug_report_spurious_chars'))
  4065. {
  4066. if ($sPreviousContent != '')
  4067. {
  4068. IssueLog::Error("Spurious characters injected by $sModuleType/$sToInclude");
  4069. }
  4070. }
  4071. }
  4072. // Building an object
  4073. //
  4074. //
  4075. private static $aQueryCacheGetObject = array();
  4076. private static $aQueryCacheGetObjectHits = array();
  4077. public static function GetQueryCacheStatus()
  4078. {
  4079. $aRes = array();
  4080. $iTotalHits = 0;
  4081. foreach(self::$aQueryCacheGetObjectHits as $sClassSign => $iHits)
  4082. {
  4083. $aRes[] = "$sClassSign: $iHits";
  4084. $iTotalHits += $iHits;
  4085. }
  4086. return $iTotalHits.' ('.implode(', ', $aRes).')';
  4087. }
  4088. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4089. {
  4090. // Build the query cache signature
  4091. //
  4092. $sQuerySign = $sClass;
  4093. if($bAllowAllData)
  4094. {
  4095. $sQuerySign .= '_all_';
  4096. }
  4097. if (count($aModifierProperties))
  4098. {
  4099. array_multisort($aModifierProperties);
  4100. $sModifierProperties = json_encode($aModifierProperties);
  4101. $sQuerySign .= '_all_'.md5($sModifierProperties);
  4102. }
  4103. if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject))
  4104. {
  4105. // NOTE: Quick and VERY dirty caching mechanism which relies on
  4106. // the fact that the string '987654321' will never appear in the
  4107. // standard query
  4108. // This could be simplified a little, relying solely on the query cache,
  4109. // but this would slow down -by how much time?- the application
  4110. $oFilter = new DBObjectSearch($sClass);
  4111. $oFilter->AddCondition('id', 987654321, '=');
  4112. if ($aModifierProperties)
  4113. {
  4114. foreach ($aModifierProperties as $sPluginClass => $aProperties)
  4115. {
  4116. foreach ($aProperties as $sProperty => $value)
  4117. {
  4118. $oFilter->SetModifierProperty($sPluginClass, $sProperty, $value);
  4119. }
  4120. }
  4121. }
  4122. if ($bAllowAllData)
  4123. {
  4124. $oFilter->AllowAllData();
  4125. }
  4126. $oFilter->NoContextParameters();
  4127. $sSQL = $oFilter->MakeSelectQuery();
  4128. self::$aQueryCacheGetObject[$sQuerySign] = $sSQL;
  4129. self::$aQueryCacheGetObjectHits[$sQuerySign] = 0;
  4130. }
  4131. else
  4132. {
  4133. $sSQL = self::$aQueryCacheGetObject[$sQuerySign];
  4134. self::$aQueryCacheGetObjectHits[$sQuerySign] += 1;
  4135. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sQuerySign]."<br/>\n";
  4136. }
  4137. $sSQL = str_replace(CMDBSource::Quote(987654321), CMDBSource::Quote($iKey), $sSQL);
  4138. $res = CMDBSource::Query($sSQL);
  4139. $aRow = CMDBSource::FetchArray($res);
  4140. CMDBSource::FreeResult($res);
  4141. if ($bMustBeFound && empty($aRow))
  4142. {
  4143. throw new CoreException("No result for the single row query: '$sSQL'");
  4144. }
  4145. return $aRow;
  4146. }
  4147. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  4148. {
  4149. self::_check_subclass($sClass);
  4150. if (strlen($sClassAlias) == 0)
  4151. {
  4152. $sClassAlias = $sClass;
  4153. }
  4154. // Compound objects: if available, get the final object class
  4155. //
  4156. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  4157. {
  4158. // Either this is a bug (forgot to specify a root class with a finalclass field
  4159. // Or this is the expected behavior, because the object is not made of several tables
  4160. }
  4161. elseif (empty($aRow[$sClassAlias."finalclass"]))
  4162. {
  4163. // The data is missing in the DB
  4164. // @#@ possible improvement: check that the class is valid !
  4165. $sRootClass = self::GetRootClass($sClass);
  4166. $sFinalClassField = self::DBGetClassField($sRootClass);
  4167. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  4168. }
  4169. else
  4170. {
  4171. // do the job for the real target class
  4172. $sClass = $aRow[$sClassAlias."finalclass"];
  4173. }
  4174. return new $sClass($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  4175. }
  4176. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4177. {
  4178. self::_check_subclass($sClass);
  4179. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
  4180. if (empty($aRow))
  4181. {
  4182. return null;
  4183. }
  4184. return self::GetObjectByRow($sClass, $aRow);
  4185. }
  4186. public static function GetObjectByName($sClass, $sName, $bMustBeFound = true)
  4187. {
  4188. self::_check_subclass($sClass);
  4189. $oObjSearch = new DBObjectSearch($sClass);
  4190. $oObjSearch->AddNameCondition($sName);
  4191. $oSet = new DBObjectSet($oObjSearch);
  4192. if ($oSet->Count() != 1)
  4193. {
  4194. if ($bMustBeFound) throw new CoreException('Failed to get an object by its name', array('class'=>$sClass, 'name'=>$sName));
  4195. return null;
  4196. }
  4197. $oObj = $oSet->fetch();
  4198. return $oObj;
  4199. }
  4200. static protected $m_aCacheObjectByColumn = array();
  4201. public static function GetObjectByColumn($sClass, $sAttCode, $value, $bMustBeFoundUnique = true)
  4202. {
  4203. if (!isset(self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value]))
  4204. {
  4205. self::_check_subclass($sClass);
  4206. $oObjSearch = new DBObjectSearch($sClass);
  4207. $oObjSearch->AddCondition($sAttCode, $value, '=');
  4208. $oSet = new DBObjectSet($oObjSearch);
  4209. if ($oSet->Count() == 1)
  4210. {
  4211. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch();
  4212. }
  4213. else
  4214. {
  4215. if ($bMustBeFoundUnique) throw new CoreException('Failed to get an object by column', array('class'=>$sClass, 'attcode'=>$sAttCode, 'value'=>$value, 'matches' => $oSet->Count()));
  4216. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null;
  4217. }
  4218. }
  4219. return self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value];
  4220. }
  4221. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  4222. {
  4223. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  4224. if ($bAllowAllData)
  4225. {
  4226. $oFilter->AllowAllData();
  4227. }
  4228. $oSet = new DBObjectSet($oFilter);
  4229. $oObject = $oSet->Fetch();
  4230. return $oObject;
  4231. }
  4232. public static function GetHyperLink($sTargetClass, $iKey)
  4233. {
  4234. if ($iKey < 0)
  4235. {
  4236. return "$sTargetClass: $iKey (invalid value)";
  4237. }
  4238. $oObj = self::GetObject($sTargetClass, $iKey, false);
  4239. if (is_null($oObj))
  4240. {
  4241. // Whatever we are looking for, the root class is the key to search for
  4242. $sRootClass = self::GetRootClass($sTargetClass);
  4243. $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', array('objclass' => $sRootClass, 'objkey' => $iKey));
  4244. $oSet = new DBObjectSet($oSearch);
  4245. $oRecord = $oSet->Fetch();
  4246. // An empty fname is obtained with iTop < 2.0
  4247. if (is_null($oRecord) || (strlen(trim($oRecord->Get('fname'))) == 0))
  4248. {
  4249. $sName = Dict::Format('Core:UnknownObjectLabel', $sTargetClass, $iKey);
  4250. $sTitle = Dict::S('Core:UnknownObjectTip');
  4251. }
  4252. else
  4253. {
  4254. $sName = $oRecord->Get('fname');
  4255. $sTitle = Dict::Format('Core:DeletedObjectTip', $oRecord->Get('date'), $oRecord->Get('userinfo'));
  4256. }
  4257. return '<span class="itop-deleted-object" title="'.htmlentities($sTitle, ENT_QUOTES, 'UTF-8').'">'.htmlentities($sName, ENT_QUOTES, 'UTF-8').'</span>';
  4258. }
  4259. return $oObj->GetHyperLink();
  4260. }
  4261. public static function NewObject($sClass)
  4262. {
  4263. self::_check_subclass($sClass);
  4264. return new $sClass();
  4265. }
  4266. public static function GetNextKey($sClass)
  4267. {
  4268. $sRootClass = MetaModel::GetRootClass($sClass);
  4269. $sRootTable = MetaModel::DBGetTable($sRootClass);
  4270. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  4271. return $iNextKey;
  4272. }
  4273. /**
  4274. * Deletion of records, bypassing DBObject::DBDelete !!!
  4275. * It is NOT recommended to use this shortcut
  4276. * In particular, it will not work
  4277. * - if the class is not a final class
  4278. * - if the class has a hierarchical key (need to rebuild the indexes)
  4279. * - if the class overload DBDelete !
  4280. * Todo: protect it against forbidden usages (in such a case, delete objects one by one)
  4281. */
  4282. public static function BulkDelete(DBObjectSearch $oFilter)
  4283. {
  4284. $sSQL = $oFilter->MakeDeleteQuery();
  4285. if (!self::DBIsReadOnly())
  4286. {
  4287. CMDBSource::Query($sSQL);
  4288. }
  4289. }
  4290. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  4291. {
  4292. // $aValues is an array of $sAttCode => $value
  4293. $sSQL = $oFilter->MakeUpdateQuery($aValues);
  4294. if (!self::DBIsReadOnly())
  4295. {
  4296. CMDBSource::Query($sSQL);
  4297. }
  4298. }
  4299. /**
  4300. * Helper to remove selected objects without calling any handler
  4301. * Surpasses BulkDelete as it can handle abstract classes, but has the other limitation as it bypasses standard objects handlers
  4302. *
  4303. * @param string $oFilter Scope of objects to wipe out
  4304. * @return The count of deleted objects
  4305. */
  4306. public static function PurgeData($oFilter)
  4307. {
  4308. $sTargetClass = $oFilter->GetClass();
  4309. $oSet = new DBObjectSet($oFilter);
  4310. $oSet->OptimizeColumnLoad(array($sTargetClass => array('finalclass')));
  4311. $aIdToClass = $oSet->GetColumnAsArray('finalclass', true);
  4312. $aIds = array_keys($aIdToClass);
  4313. if (count($aIds) > 0)
  4314. {
  4315. $aQuotedIds = CMDBSource::Quote($aIds);
  4316. $sIdList = implode(',', $aQuotedIds);
  4317. $aTargetClasses = array_merge(
  4318. self::EnumChildClasses($sTargetClass, ENUM_CHILD_CLASSES_ALL),
  4319. self::EnumParentClasses($sTargetClass, ENUM_PARENT_CLASSES_EXCLUDELEAF)
  4320. );
  4321. foreach ($aTargetClasses as $sSomeClass)
  4322. {
  4323. $sTable = MetaModel::DBGetTable($sSomeClass);
  4324. $sPKField = MetaModel::DBGetKey($sSomeClass);
  4325. $sDeleteSQL = "DELETE FROM `$sTable` WHERE `$sPKField` IN ($sIdList)";
  4326. CMDBSource::DeleteFrom($sDeleteSQL);
  4327. }
  4328. }
  4329. return count($aIds);
  4330. }
  4331. // Links
  4332. //
  4333. //
  4334. public static function EnumReferencedClasses($sClass)
  4335. {
  4336. self::_check_subclass($sClass);
  4337. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  4338. $aResult = array();
  4339. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  4340. {
  4341. if ($oAttDef->IsExternalKey())
  4342. {
  4343. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  4344. }
  4345. }
  4346. return $aResult;
  4347. }
  4348. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  4349. {
  4350. self::_check_subclass($sClass);
  4351. if ($bSkipLinkingClasses)
  4352. {
  4353. $aLinksClasses = self::EnumLinksClasses();
  4354. }
  4355. // 1-N links (referencing my class), array of sClass => array of sAttcode
  4356. $aResult = array();
  4357. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4358. {
  4359. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  4360. $aExtKeys = array();
  4361. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4362. {
  4363. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4364. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  4365. {
  4366. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  4367. // Ok, I want this one
  4368. $aExtKeys[$sAttCode] = $oAttDef;
  4369. }
  4370. }
  4371. if (count($aExtKeys) != 0)
  4372. {
  4373. $aResult[$sSomeClass] = $aExtKeys;
  4374. }
  4375. }
  4376. return $aResult;
  4377. }
  4378. /**
  4379. * It is not recommended to use this function: call GetLinkClasses instead
  4380. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  4381. * The only difference with EnumLinkingClasses is the output format
  4382. */
  4383. public static function EnumLinksClasses()
  4384. {
  4385. // Returns a flat array of classes having at least two external keys
  4386. $aResult = array();
  4387. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4388. {
  4389. $iExtKeyCount = 0;
  4390. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4391. {
  4392. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4393. if ($oAttDef->IsExternalKey())
  4394. {
  4395. $iExtKeyCount++;
  4396. }
  4397. }
  4398. if ($iExtKeyCount >= 2)
  4399. {
  4400. $aResult[] = $sSomeClass;
  4401. }
  4402. }
  4403. return $aResult;
  4404. }
  4405. /**
  4406. * It is not recommended to use this function: call GetLinkClasses instead
  4407. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  4408. * The only difference with EnumLinksClasses is the output format
  4409. */
  4410. public static function EnumLinkingClasses($sClass = "")
  4411. {
  4412. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  4413. $aResult = array();
  4414. foreach (self::EnumLinksClasses() as $sSomeClass)
  4415. {
  4416. $aTargets = array();
  4417. $bFoundClass = false;
  4418. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  4419. {
  4420. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4421. if ($oAttDef->IsExternalKey())
  4422. {
  4423. $sRemoteClass = $oAttDef->GetTargetClass();
  4424. if (empty($sClass))
  4425. {
  4426. $aTargets[$sAttCode] = $sRemoteClass;
  4427. }
  4428. elseif ($sClass == $sRemoteClass)
  4429. {
  4430. $bFoundClass = true;
  4431. }
  4432. else
  4433. {
  4434. $aTargets[$sAttCode] = $sRemoteClass;
  4435. }
  4436. }
  4437. }
  4438. if (empty($sClass) || $bFoundClass)
  4439. {
  4440. $aResult[$sSomeClass] = $aTargets;
  4441. }
  4442. }
  4443. return $aResult;
  4444. }
  4445. /**
  4446. * This function has two siblings that will be soon deprecated:
  4447. * EnumLinkingClasses and EnumLinkClasses
  4448. *
  4449. * Using GetLinkClasses is the recommended way to determine if a class is
  4450. * actually an N-N relation because it is based on the decision made by the
  4451. * designer the data model
  4452. */
  4453. public static function GetLinkClasses()
  4454. {
  4455. $aRet = array();
  4456. foreach(self::GetClasses() as $sClass)
  4457. {
  4458. if (isset(self::$m_aClassParams[$sClass]["is_link"]))
  4459. {
  4460. if (self::$m_aClassParams[$sClass]["is_link"])
  4461. {
  4462. $aExtKeys = array();
  4463. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  4464. {
  4465. if ($oAttDef->IsExternalKey())
  4466. {
  4467. $aExtKeys[$sAttCode] = $oAttDef->GetTargetClass();
  4468. }
  4469. }
  4470. $aRet[$sClass] = $aExtKeys;
  4471. }
  4472. }
  4473. }
  4474. return $aRet;
  4475. }
  4476. public static function GetLinkLabel($sLinkClass, $sAttCode)
  4477. {
  4478. self::_check_subclass($sLinkClass);
  4479. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  4480. return self::GetLabel($sLinkClass, $sAttCode);
  4481. }
  4482. /**
  4483. * Replaces all the parameters by the values passed in the hash array
  4484. */
  4485. static public function ApplyParams($sInput, $aParams)
  4486. {
  4487. // Declare magic parameters
  4488. $aParams['APP_URL'] = utils::GetAbsoluteUrlAppRoot();
  4489. $aParams['MODULES_URL'] = utils::GetAbsoluteUrlModulesRoot();
  4490. $aSearches = array();
  4491. $aReplacements = array();
  4492. foreach($aParams as $sSearch => $replace)
  4493. {
  4494. // Some environment parameters are objects, we just need scalars
  4495. if (is_object($replace))
  4496. {
  4497. $iPos = strpos($sSearch, '->object()');
  4498. if ($iPos !== false)
  4499. {
  4500. // Expand the parameters for the object
  4501. $sName = substr($sSearch, 0, $iPos);
  4502. if (preg_match_all('/\\$'.$sName.'-(>|&gt;)([^\\$]+)\\$/', $sInput, $aMatches)) // Support both syntaxes: $this->xxx$ or $this-&gt;xxx$ for HTML compatibility
  4503. {
  4504. foreach($aMatches[2] as $idx => $sPlaceholderAttCode)
  4505. {
  4506. try
  4507. {
  4508. $sReplacement = $replace->GetForTemplate($sPlaceholderAttCode);
  4509. if ($sReplacement !== null)
  4510. {
  4511. $aReplacements[] = $sReplacement;
  4512. $aSearches[] = '$'.$sName.'-'.$aMatches[1][$idx].$sPlaceholderAttCode.'$';
  4513. }
  4514. }
  4515. catch(Exception $e)
  4516. {
  4517. // No replacement will occur
  4518. }
  4519. }
  4520. }
  4521. }
  4522. else
  4523. {
  4524. continue; // Ignore this non-scalar value
  4525. }
  4526. }
  4527. $aSearches[] = '$'.$sSearch.'$';
  4528. $aReplacements[] = (string) $replace;
  4529. }
  4530. return str_replace($aSearches, $aReplacements, $sInput);
  4531. }
  4532. /**
  4533. * Returns an array of classes=>instance implementing the given interface
  4534. */
  4535. public static function EnumPlugins($sInterface)
  4536. {
  4537. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4538. {
  4539. return self::$m_aExtensionClasses[$sInterface];
  4540. }
  4541. else
  4542. {
  4543. return array();
  4544. }
  4545. }
  4546. /**
  4547. * Returns the instance of the specified plug-ins for the given interface
  4548. */
  4549. public static function GetPlugins($sInterface, $sClassName)
  4550. {
  4551. $oInstance = null;
  4552. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4553. {
  4554. if (array_key_exists($sClassName, self::$m_aExtensionClasses[$sInterface]))
  4555. {
  4556. return self::$m_aExtensionClasses[$sInterface][$sClassName];
  4557. }
  4558. }
  4559. return $oInstance;
  4560. }
  4561. public static function GetCacheEntries($sEnvironment = null)
  4562. {
  4563. if (!function_exists('apc_cache_info')) return array();
  4564. if (is_null($sEnvironment))
  4565. {
  4566. $sEnvironment = MetaModel::GetEnvironmentId();
  4567. }
  4568. $aEntries = array();
  4569. if (extension_loaded('apcu'))
  4570. {
  4571. // Beware: APCu behaves slightly differently from APC !!
  4572. $aCacheUserData = @apc_cache_info();
  4573. }
  4574. else
  4575. {
  4576. $aCacheUserData = @apc_cache_info('user');
  4577. }
  4578. if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list']))
  4579. {
  4580. $sPrefix = 'itop-'.$sEnvironment.'-';
  4581. foreach($aCacheUserData['cache_list'] as $i => $aEntry)
  4582. {
  4583. $sEntryKey = array_key_exists('info', $aEntry) ? $aEntry['info'] : $aEntry['key'];
  4584. if (strpos($sEntryKey, $sPrefix) === 0)
  4585. {
  4586. $sCleanKey = substr($sEntryKey, strlen($sPrefix));
  4587. $aEntries[$sCleanKey] = $aEntry;
  4588. $aEntries[$sCleanKey]['info'] = $sEntryKey;
  4589. }
  4590. }
  4591. }
  4592. return $aEntries;
  4593. }
  4594. public static function ResetCache($sEnvironmentId = null)
  4595. {
  4596. if (!function_exists('apc_delete')) return;
  4597. if (is_null($sEnvironmentId))
  4598. {
  4599. $sEnvironmentId = MetaModel::GetEnvironmentId();
  4600. }
  4601. $sAppIdentity = 'itop-'.$sEnvironmentId;
  4602. Dict::ResetCache($sAppIdentity);
  4603. foreach(self::GetCacheEntries($sEnvironmentId) as $sKey => $aAPCInfo)
  4604. {
  4605. $sAPCKey = $aAPCInfo['info'];
  4606. apc_delete($sAPCKey);
  4607. }
  4608. }
  4609. /**
  4610. * Given a field spec, get the most relevant (unique) representation
  4611. * Examples for a user request:
  4612. * - friendlyname => ref
  4613. * - org_name => org_id->name
  4614. * - org_id_friendlyname => org_id=>name
  4615. * - caller_name => caller_id->name
  4616. * - caller_id_friendlyname => caller_id->friendlyname
  4617. * @param string $sClass
  4618. * @param string $sField
  4619. * @return string
  4620. */
  4621. public static function NormalizeFieldSpec($sClass, $sField)
  4622. {
  4623. $sRet = $sField;
  4624. if ($sField == 'id')
  4625. {
  4626. $sRet = 'id';
  4627. }
  4628. elseif ($sField == 'friendlyname')
  4629. {
  4630. $sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sClass);
  4631. if (!is_null($sFriendlyNameAttCode))
  4632. {
  4633. // The friendly name is made of a single attribute
  4634. $sRet = $sFriendlyNameAttCode;
  4635. }
  4636. }
  4637. else
  4638. {
  4639. $oAttDef = static::GetAttributeDef($sClass, $sField);
  4640. if ($oAttDef instanceof AttributeFriendlyName)
  4641. {
  4642. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $oAttDef->GetKeyAttCode());
  4643. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  4644. $sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sRemoteClass);
  4645. if (is_null($sFriendlyNameAttCode))
  4646. {
  4647. // The friendly name is made of several attributes
  4648. $sRet = $oAttDef->GetKeyAttCode().'->friendlyname';
  4649. }
  4650. else
  4651. {
  4652. // The friendly name is made of a single attribute
  4653. $sRet = $oAttDef->GetKeyAttCode().'->'.$sFriendlyNameAttCode;
  4654. }
  4655. }
  4656. elseif ($oAttDef->IsExternalField())
  4657. {
  4658. $sRet = $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode();
  4659. }
  4660. }
  4661. return $sRet;
  4662. }
  4663. } // class MetaModel
  4664. // Standard attribute lists
  4665. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  4666. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  4667. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  4668. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  4669. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  4670. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));