metamodel.class.php 176 KB

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