metamodel.class.php 172 KB

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