metamodel.class.php 168 KB

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