metamodel.class.php 175 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284
  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
  1444. $aAttributes = $aTargetStateAttributes;
  1445. // Retrieving attributes from transition
  1446. $aTransitionAttributes = $aTransition['attribute_list'];
  1447. // - Merging with results
  1448. foreach($aTransitionAttributes as $sAttCode => $iAttributeFlags)
  1449. {
  1450. if(array_key_exists($sAttCode, $aAttributes))
  1451. {
  1452. $aAttributes[$sAttCode] = $aAttributes[$sAttCode] | $iAttributeFlags;
  1453. }
  1454. else
  1455. {
  1456. $aAttributes[$sAttCode] = $iAttributeFlags;
  1457. }
  1458. }
  1459. return $aAttributes;
  1460. }
  1461. /**
  1462. * Combines the flags from the all states that compose the initial_state_path
  1463. */
  1464. public static function GetInitialStateAttributeFlags($sClass, $sState, $sAttCode)
  1465. {
  1466. $iFlags = self::GetAttributeFlags($sClass, $sState, $sAttCode); // Be default set the same flags as the 'target' state
  1467. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1468. if (!empty($sStateAttCode))
  1469. {
  1470. $aStates = MetaModel::EnumInitialStates($sClass);
  1471. if (array_key_exists($sState, $aStates))
  1472. {
  1473. $bReadOnly = (($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY);
  1474. $bHidden = (($iFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN);
  1475. foreach($aStates[$sState] as $sPrevState)
  1476. {
  1477. $iPrevFlags = self::GetAttributeFlags($sClass, $sPrevState, $sAttCode);
  1478. if (($iPrevFlags & OPT_ATT_HIDDEN) != OPT_ATT_HIDDEN)
  1479. {
  1480. $bReadOnly = $bReadOnly && (($iPrevFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY); // if it is/was not readonly => then it's not
  1481. }
  1482. $bHidden = $bHidden && (($iPrevFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN); // if it is/was not hidden => then it's not
  1483. }
  1484. if ($bReadOnly)
  1485. {
  1486. $iFlags = $iFlags | OPT_ATT_READONLY;
  1487. }
  1488. else
  1489. {
  1490. $iFlags = $iFlags & ~OPT_ATT_READONLY;
  1491. }
  1492. if ($bHidden)
  1493. {
  1494. $iFlags = $iFlags | OPT_ATT_HIDDEN;
  1495. }
  1496. else
  1497. {
  1498. $iFlags = $iFlags & ~OPT_ATT_HIDDEN;
  1499. }
  1500. }
  1501. }
  1502. return $iFlags;
  1503. }
  1504. //
  1505. // Allowed values
  1506. //
  1507. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1508. {
  1509. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1510. return $oAttDef->GetAllowedValues($aArgs, $sContains);
  1511. }
  1512. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sContains = '')
  1513. {
  1514. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  1515. return $oFltDef->GetAllowedValues($aArgs, $sContains);
  1516. }
  1517. public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = array(), $sContains = '', $iAdditionalValue = null)
  1518. {
  1519. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1520. return $oAttDef->GetAllowedValuesAsObjectSet($aArgs, $sContains, $iAdditionalValue);
  1521. }
  1522. //
  1523. // Businezz model declaration verbs (should be static)
  1524. //
  1525. public static function RegisterZList($sListCode, $aListInfo)
  1526. {
  1527. // Check mandatory params
  1528. $aMandatParams = array(
  1529. "description" => "detailed (though one line) description of the list",
  1530. "type" => "attributes | filters",
  1531. );
  1532. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1533. {
  1534. if (!array_key_exists($sParamName, $aListInfo))
  1535. {
  1536. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  1537. }
  1538. }
  1539. self::$m_aListInfos[$sListCode] = $aListInfo;
  1540. }
  1541. public static function RegisterRelation($sRelCode)
  1542. {
  1543. // Each item used to be an array of properties...
  1544. self::$m_aRelationInfos[$sRelCode] = $sRelCode;
  1545. }
  1546. /*
  1547. * Helper to correctly add a magic attribute (called from InitClasses)
  1548. */
  1549. private static function AddMagicAttribute(AttributeDefinition $oAttribute, $sTargetClass, $sOriginClass = null)
  1550. {
  1551. $sCode = $oAttribute->GetCode();
  1552. if (is_null($sOriginClass))
  1553. {
  1554. $sOriginClass = $sTargetClass;
  1555. }
  1556. $oAttribute->SetHostClass($sTargetClass);
  1557. self::$m_aAttribDefs[$sTargetClass][$sCode] = $oAttribute;
  1558. self::$m_aAttribOrigins[$sTargetClass][$sCode] = $sOriginClass;
  1559. $oFlt = new FilterFromAttribute($oAttribute);
  1560. self::$m_aFilterDefs[$sTargetClass][$sCode] = $oFlt;
  1561. self::$m_aFilterOrigins[$sTargetClass][$sCode] = $sOriginClass;
  1562. }
  1563. // Must be called once and only once...
  1564. public static function InitClasses($sTablePrefix)
  1565. {
  1566. if (count(self::GetClasses()) > 0)
  1567. {
  1568. throw new CoreException("InitClasses should not be called more than once -skipped");
  1569. return;
  1570. }
  1571. self::$m_sTablePrefix = $sTablePrefix;
  1572. // Build the list of available extensions
  1573. //
  1574. $aInterfaces = array('iApplicationUIExtension', 'iApplicationObjectExtension', 'iQueryModifier', 'iOnClassInitialization', 'iPopupMenuExtension', 'iPageUIExtension');
  1575. foreach($aInterfaces as $sInterface)
  1576. {
  1577. self::$m_aExtensionClasses[$sInterface] = array();
  1578. }
  1579. foreach(get_declared_classes() as $sPHPClass)
  1580. {
  1581. $oRefClass = new ReflectionClass($sPHPClass);
  1582. $oExtensionInstance = null;
  1583. foreach($aInterfaces as $sInterface)
  1584. {
  1585. if ($oRefClass->implementsInterface($sInterface) && $oRefClass->isInstantiable())
  1586. {
  1587. if (is_null($oExtensionInstance))
  1588. {
  1589. $oExtensionInstance = new $sPHPClass;
  1590. }
  1591. self::$m_aExtensionClasses[$sInterface][$sPHPClass] = $oExtensionInstance;
  1592. }
  1593. }
  1594. }
  1595. // Initialize the classes (declared attributes, etc.)
  1596. //
  1597. $aObsoletableRootClasses = array();
  1598. foreach(get_declared_classes() as $sPHPClass)
  1599. {
  1600. if (is_subclass_of($sPHPClass, 'DBObject'))
  1601. {
  1602. $sParent = get_parent_class($sPHPClass);
  1603. if (array_key_exists($sParent, self::$m_aIgnoredAttributes))
  1604. {
  1605. // Inherit info about attributes to ignore
  1606. self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent];
  1607. }
  1608. try
  1609. {
  1610. $oMethod = new ReflectionMethod($sPHPClass, 'Init');
  1611. if ($oMethod->getDeclaringClass()->name == $sPHPClass)
  1612. {
  1613. call_user_func(array($sPHPClass, 'Init'));
  1614. // Inherit archive flag
  1615. $bParentArchivable = isset(self::$m_aClassParams[$sParent]['archive']) ? self::$m_aClassParams[$sParent]['archive'] : false;
  1616. $bArchivable = isset(self::$m_aClassParams[$sPHPClass]['archive']) ? self::$m_aClassParams[$sPHPClass]['archive'] : null;
  1617. if (!$bParentArchivable && $bArchivable && !self::IsRootClass($sPHPClass))
  1618. {
  1619. throw new Exception("Archivability must be declared on top of the class hierarchy above $sPHPClass (consistency throughout the whole class tree is a must)");
  1620. }
  1621. if ($bParentArchivable && ($bArchivable === false))
  1622. {
  1623. throw new Exception("$sPHPClass must be archivable (consistency throughout the whole class tree is a must)");
  1624. }
  1625. $bReallyArchivable = $bParentArchivable || $bArchivable;
  1626. self::$m_aClassParams[$sPHPClass]['archive'] = $bReallyArchivable;
  1627. $bArchiveRoot = $bReallyArchivable && !$bParentArchivable;
  1628. self::$m_aClassParams[$sPHPClass]['archive_root'] = $bArchiveRoot;
  1629. if ($bReallyArchivable)
  1630. {
  1631. self::$m_aClassParams[$sPHPClass]['archive_root_class'] = $bArchiveRoot ? $sPHPClass : self::$m_aClassParams[$sParent]['archive_root_class'];
  1632. }
  1633. // Inherit obsolescence expression
  1634. $sObsolescence = null;
  1635. if (isset(self::$m_aClassParams[$sPHPClass]['obsolescence_expression']))
  1636. {
  1637. // Defined or overloaded
  1638. $sObsolescence = self::$m_aClassParams[$sPHPClass]['obsolescence_expression'];
  1639. $aObsoletableRootClasses[self::$m_aRootClasses[$sPHPClass]] = true;
  1640. }
  1641. elseif (isset(self::$m_aClassParams[$sParent]['obsolescence_expression']))
  1642. {
  1643. // Inherited
  1644. $sObsolescence = self::$m_aClassParams[$sParent]['obsolescence_expression'];
  1645. }
  1646. self::$m_aClassParams[$sPHPClass]['obsolescence_expression'] = $sObsolescence;
  1647. foreach (MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit)
  1648. {
  1649. $oClassInit->OnAfterClassInitialization($sPHPClass);
  1650. }
  1651. }
  1652. }
  1653. catch (ReflectionException $e)
  1654. {
  1655. // This class is only implementing methods, ignore it from the MetaModel perspective
  1656. }
  1657. }
  1658. }
  1659. // Add a 'class' attribute/filter to the root classes and their children
  1660. //
  1661. foreach(self::EnumRootClasses() as $sRootClass)
  1662. {
  1663. if (self::IsStandaloneClass($sRootClass)) continue;
  1664. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  1665. if (strlen($sDbFinalClassField) == 0)
  1666. {
  1667. $sDbFinalClassField = 'finalclass';
  1668. self::$m_aClassParams[$sRootClass]["db_finalclass_field"] = 'finalclass';
  1669. }
  1670. $oClassAtt = new AttributeFinalClass('finalclass', array(
  1671. "sql"=>$sDbFinalClassField,
  1672. "default_value"=>$sRootClass,
  1673. "is_null_allowed"=>false,
  1674. "depends_on"=>array()
  1675. ));
  1676. self::AddMagicAttribute($oClassAtt, $sRootClass);
  1677. $bObsoletable = array_key_exists($sRootClass, $aObsoletableRootClasses);
  1678. if ($bObsoletable && is_null(self::$m_aClassParams[$sRootClass]['obsolescence_expression']))
  1679. {
  1680. self::$m_aClassParams[$sRootClass]['obsolescence_expression'] = '0';
  1681. }
  1682. foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass)
  1683. {
  1684. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass]))
  1685. {
  1686. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  1687. }
  1688. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sChildClass]))
  1689. {
  1690. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  1691. }
  1692. $oCloned = clone $oClassAtt;
  1693. $oCloned->SetFixedValue($sChildClass);
  1694. self::AddMagicAttribute($oCloned, $sChildClass, $sRootClass);
  1695. if ($bObsoletable && is_null(self::$m_aClassParams[$sChildClass]['obsolescence_expression']))
  1696. {
  1697. self::$m_aClassParams[$sChildClass]['obsolescence_expression'] = '0';
  1698. }
  1699. }
  1700. }
  1701. // Prepare external fields and filters
  1702. // Add final class to external keys
  1703. //
  1704. foreach (self::GetClasses() as $sClass)
  1705. {
  1706. $sRootClass = self::$m_aRootClasses[$sClass];
  1707. // Create the friendly name attribute
  1708. $sFriendlyNameAttCode = 'friendlyname';
  1709. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode);
  1710. self::AddMagicAttribute($oFriendlyName, $sClass);
  1711. if (self::$m_aClassParams[$sClass]["archive_root"])
  1712. {
  1713. // Create archive attributes on top the archivable hierarchy
  1714. $oArchiveFlag = new AttributeArchiveFlag('archive_flag');
  1715. self::AddMagicAttribute($oArchiveFlag, $sClass);
  1716. $oArchiveDate = new AttributeDate('archive_date', array('magic' => true, "allowed_values"=>null, "sql"=>'archive_date', "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array()));
  1717. self::AddMagicAttribute($oArchiveDate, $sClass);
  1718. }
  1719. elseif (self::$m_aClassParams[$sClass]["archive"])
  1720. {
  1721. $sArchiveRoot = self::$m_aClassParams[$sClass]['archive_root_class'];
  1722. // Inherit archive attributes
  1723. $oArchiveFlag = clone self::$m_aAttribDefs[$sArchiveRoot]['archive_flag'];
  1724. $oArchiveFlag->SetHostClass($sClass);
  1725. self::$m_aAttribDefs[$sClass]['archive_flag'] = $oArchiveFlag;
  1726. self::$m_aAttribOrigins[$sClass]['archive_flag'] = $sArchiveRoot;
  1727. $oArchiveDate = clone self::$m_aAttribDefs[$sArchiveRoot]['archive_date'];
  1728. $oArchiveDate->SetHostClass($sClass);
  1729. self::$m_aAttribDefs[$sClass]['archive_date'] = $oArchiveDate;
  1730. self::$m_aAttribOrigins[$sClass]['archive_date'] = $sArchiveRoot;
  1731. }
  1732. if (!is_null(self::$m_aClassParams[$sClass]['obsolescence_expression']))
  1733. {
  1734. $oObsolescenceFlag = new AttributeObsolescenceFlag('obsolescence_flag');
  1735. self::AddMagicAttribute($oObsolescenceFlag, $sClass);
  1736. if (self::$m_aRootClasses[$sClass] == $sClass)
  1737. {
  1738. $oObsolescenceDate = new AttributeDate('obsolescence_date', array('magic' => true, "allowed_values" => null, "sql" => 'obsolescence_date', "default_value" => '', "is_null_allowed" => true, "depends_on" => array()));
  1739. self::AddMagicAttribute($oObsolescenceDate, $sClass);
  1740. }
  1741. else
  1742. {
  1743. $oObsolescenceDate = clone self::$m_aAttribDefs[$sRootClass]['obsolescence_date'];
  1744. $oObsolescenceDate->SetHostClass($sClass);
  1745. self::$m_aAttribDefs[$sClass]['obsolescence_date'] = $oObsolescenceDate;
  1746. self::$m_aAttribOrigins[$sClass]['obsolescence_date'] = $sRootClass;
  1747. }
  1748. }
  1749. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  1750. {
  1751. // Compute the filter codes
  1752. //
  1753. foreach ($oAttDef->GetFilterDefinitions() as $sFilterCode => $oFilterDef)
  1754. {
  1755. self::$m_aFilterDefs[$sClass][$sFilterCode] = $oFilterDef;
  1756. if ($oAttDef->IsExternalField())
  1757. {
  1758. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1759. $oKeyDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1760. self::$m_aFilterOrigins[$sClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  1761. }
  1762. else
  1763. {
  1764. self::$m_aFilterOrigins[$sClass][$sFilterCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  1765. }
  1766. }
  1767. // Compute the fields that will be used to display a pointer to another object
  1768. //
  1769. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  1770. {
  1771. // oAttDef is either
  1772. // - an external KEY / FIELD (direct),
  1773. // - an external field pointing to an external KEY / FIELD
  1774. // - an external field pointing to an external field pointing to....
  1775. $sRemoteClass = $oAttDef->GetTargetClass();
  1776. if ($oAttDef->IsExternalField())
  1777. {
  1778. // This is a key, but the value comes from elsewhere
  1779. // Create an external field pointing to the remote friendly name attribute
  1780. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1781. $sRemoteAttCode = $oAttDef->GetExtAttCode()."_friendlyname";
  1782. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1783. $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array("allowed_values"=>null, "extkey_attcode"=>$sKeyAttCode, "target_attcode"=>$sRemoteAttCode, "depends_on"=>array()));
  1784. self::AddMagicAttribute($oFriendlyName, $sClass, self::$m_aAttribOrigins[$sClass][$sKeyAttCode]);
  1785. }
  1786. else
  1787. {
  1788. // Create the friendly name attribute
  1789. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1790. $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array('magic' => true, 'allowed_values'=>null, 'extkey_attcode'=>$sAttCode, "target_attcode"=>'friendlyname', 'depends_on'=>array()));
  1791. self::AddMagicAttribute($oFriendlyName, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]);
  1792. if (self::HasChildrenClasses($sRemoteClass))
  1793. {
  1794. // First, create an external field attribute, that gets the final class
  1795. $sClassRecallAttCode = $sAttCode.'_finalclass_recall';
  1796. $oClassRecall = new AttributeExternalField($sClassRecallAttCode, array(
  1797. "allowed_values"=>null,
  1798. "extkey_attcode"=>$sAttCode,
  1799. "target_attcode"=>"finalclass",
  1800. "is_null_allowed"=>true,
  1801. "depends_on"=>array()
  1802. ));
  1803. self::AddMagicAttribute($oClassRecall, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]);
  1804. // Add it to the ZLists where the external key is present
  1805. //foreach(self::$m_aListData[$sClass] as $sListCode => $aAttributes)
  1806. $sListCode = 'list';
  1807. if (isset(self::$m_aListData[$sClass][$sListCode]))
  1808. {
  1809. $aAttributes = self::$m_aListData[$sClass][$sListCode];
  1810. // temporary.... no loop
  1811. {
  1812. if (in_array($sAttCode, $aAttributes))
  1813. {
  1814. $aNewList = array();
  1815. foreach($aAttributes as $iPos => $sAttToDisplay)
  1816. {
  1817. if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode))
  1818. {
  1819. // Insert the final class right before
  1820. $aNewList[] = $sClassRecallAttCode;
  1821. }
  1822. $aNewList[] = $sAttToDisplay;
  1823. }
  1824. self::$m_aListData[$sClass][$sListCode] = $aNewList;
  1825. }
  1826. }
  1827. }
  1828. }
  1829. }
  1830. // Get the real external key attribute
  1831. // It will be our reference to determine the other ext fields related to the same ext key
  1832. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1833. if (self::IsArchivable($sRemoteClass))
  1834. {
  1835. $sArchiveRemote = $sAttCode.'_archive_flag';
  1836. $oArchiveRemote = new AttributeExternalField($sArchiveRemote, array("allowed_values"=>null, "extkey_attcode"=>$sAttCode, "target_attcode"=>'archive_flag', "depends_on"=>array()));
  1837. self::AddMagicAttribute($oArchiveRemote, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]);
  1838. }
  1839. if (self::IsObsoletable($sRemoteClass))
  1840. {
  1841. $sObsoleteRemote = $sAttCode.'_obsolescence_flag';
  1842. $oObsoleteRemote = new AttributeExternalField($sObsoleteRemote, array("allowed_values"=>null, "extkey_attcode"=>$sAttCode, "target_attcode"=>'obsolescence_flag', "depends_on"=>array()));
  1843. self::AddMagicAttribute($oObsoleteRemote, $sClass, self::$m_aAttribOrigins[$sClass][$sAttCode]);
  1844. }
  1845. }
  1846. if ($oAttDef instanceof AttributeMetaEnum)
  1847. {
  1848. $aMappingData = $oAttDef->GetMapRule($sClass);
  1849. if ($aMappingData != null)
  1850. {
  1851. $sEnumAttCode = $aMappingData['attcode'];
  1852. self::$m_aEnumToMeta[$sClass][$sEnumAttCode][$sAttCode] = $oAttDef;
  1853. }
  1854. }
  1855. }
  1856. // Add a 'id' filter
  1857. //
  1858. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  1859. {
  1860. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  1861. }
  1862. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  1863. {
  1864. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  1865. }
  1866. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  1867. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  1868. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  1869. // Define defaults values for the standard ZLists
  1870. //
  1871. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  1872. //{
  1873. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  1874. // {
  1875. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  1876. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  1877. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  1878. // }
  1879. //}
  1880. }
  1881. }
  1882. // To be overriden, must be called for any object class (optimization)
  1883. public static function Init()
  1884. {
  1885. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1886. }
  1887. // To be overloaded by biz model declarations
  1888. public static function GetRelationQueries($sRelCode)
  1889. {
  1890. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1891. return array();
  1892. }
  1893. public static function Init_Params($aParams)
  1894. {
  1895. // Check mandatory params
  1896. $aMandatParams = array(
  1897. "category" => "group classes by modules defining their visibility in the UI",
  1898. "key_type" => "autoincrement | string",
  1899. "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...'",
  1900. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  1901. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  1902. "db_table" => "database table",
  1903. "db_key_field" => "database field which is the key",
  1904. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  1905. );
  1906. $sClass = self::GetCallersPHPClass("Init", self::$m_bTraceSourceFiles);
  1907. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1908. {
  1909. if (!array_key_exists($sParamName, $aParams))
  1910. {
  1911. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  1912. }
  1913. }
  1914. $aCategories = explode(',', $aParams['category']);
  1915. foreach ($aCategories as $sCategory)
  1916. {
  1917. self::$m_Category2Class[$sCategory][] = $sClass;
  1918. }
  1919. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  1920. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  1921. self::$m_aParentClasses[$sClass] = array();
  1922. self::$m_aChildClasses[$sClass] = array();
  1923. self::$m_aClassParams[$sClass]= $aParams;
  1924. self::$m_aAttribDefs[$sClass] = array();
  1925. self::$m_aAttribOrigins[$sClass] = array();
  1926. self::$m_aFilterDefs[$sClass] = array();
  1927. self::$m_aFilterOrigins[$sClass] = array();
  1928. }
  1929. protected static function object_array_mergeclone($aSource1, $aSource2)
  1930. {
  1931. $aRes = array();
  1932. foreach ($aSource1 as $key=>$object)
  1933. {
  1934. $aRes[$key] = clone $object;
  1935. }
  1936. foreach ($aSource2 as $key=>$object)
  1937. {
  1938. $aRes[$key] = clone $object;
  1939. }
  1940. return $aRes;
  1941. }
  1942. public static function Init_InheritAttributes($sSourceClass = null)
  1943. {
  1944. $sTargetClass = self::GetCallersPHPClass("Init");
  1945. if (empty($sSourceClass))
  1946. {
  1947. // Default: inherit from parent class
  1948. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1949. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1950. }
  1951. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  1952. {
  1953. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  1954. {
  1955. self::$m_aAttribDefs[$sTargetClass] = array();
  1956. self::$m_aAttribOrigins[$sTargetClass] = array();
  1957. }
  1958. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  1959. foreach(self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef)
  1960. {
  1961. $oAttDef->SetHostClass($sTargetClass);
  1962. }
  1963. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  1964. }
  1965. // Build root class information
  1966. if (array_key_exists($sSourceClass, self::$m_aRootClasses))
  1967. {
  1968. // Inherit...
  1969. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  1970. }
  1971. else
  1972. {
  1973. // This class will be the root class
  1974. self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
  1975. self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
  1976. }
  1977. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  1978. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  1979. // I am the child of each and every parent...
  1980. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  1981. {
  1982. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  1983. }
  1984. }
  1985. protected static function Init_IsKnownClass($sClass)
  1986. {
  1987. // Differs from self::IsValidClass()
  1988. // because it is being called before all the classes have been initialized
  1989. if (!class_exists($sClass)) return false;
  1990. if (!is_subclass_of($sClass, 'DBObject')) return false;
  1991. return true;
  1992. }
  1993. public static function Init_AddAttribute(AttributeDefinition $oAtt, $sTargetClass = null)
  1994. {
  1995. if (!$sTargetClass)
  1996. {
  1997. $sTargetClass = self::GetCallersPHPClass("Init");
  1998. }
  1999. $sAttCode = $oAtt->GetCode();
  2000. if ($sAttCode == 'finalclass')
  2001. {
  2002. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  2003. }
  2004. if ($sAttCode == 'friendlyname')
  2005. {
  2006. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  2007. }
  2008. if (array_key_exists($sAttCode, self::$m_aAttribDefs[$sTargetClass]))
  2009. {
  2010. throw new Exception("Declaration of $sTargetClass: attempting to redeclare the inherited attribute '$sAttCode', originaly declared in ".self::$m_aAttribOrigins[$sTargetClass][$sAttCode]);
  2011. }
  2012. // Set the "host class" as soon as possible, since HierarchicalKeys use it for their 'target class' as well
  2013. // and this needs to be know early (for Init_IsKnowClass 19 lines below)
  2014. $oAtt->SetHostClass($sTargetClass);
  2015. // Some attributes could refer to a class
  2016. // declared in a module which is currently not installed/active
  2017. // We simply discard those attributes
  2018. //
  2019. if ($oAtt->IsLinkSet())
  2020. {
  2021. $sRemoteClass = $oAtt->GetLinkedClass();
  2022. if (!self::Init_IsKnownClass($sRemoteClass))
  2023. {
  2024. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  2025. return;
  2026. }
  2027. }
  2028. elseif($oAtt->IsExternalKey())
  2029. {
  2030. $sRemoteClass = $oAtt->GetTargetClass();
  2031. if (!self::Init_IsKnownClass($sRemoteClass))
  2032. {
  2033. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  2034. return;
  2035. }
  2036. }
  2037. elseif($oAtt->IsExternalField())
  2038. {
  2039. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  2040. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
  2041. {
  2042. // The corresponding external key has already been ignored
  2043. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
  2044. return;
  2045. }
  2046. // #@# todo - Check if the target attribute is still there
  2047. // this is not simple to implement because is involves
  2048. // several passes (the load order has a significant influence on that)
  2049. }
  2050. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  2051. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  2052. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  2053. }
  2054. public static function Init_SetZListItems($sListCode, $aItems, $sTargetClass = null)
  2055. {
  2056. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  2057. if (!$sTargetClass)
  2058. {
  2059. $sTargetClass = self::GetCallersPHPClass("Init");
  2060. }
  2061. // Discard attributes that do not make sense
  2062. // (missing classes in the current module combination, resulting in irrelevant ext key or link set)
  2063. //
  2064. self::Init_CheckZListItems($aItems, $sTargetClass);
  2065. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  2066. }
  2067. protected static function Init_CheckZListItems(&$aItems, $sTargetClass)
  2068. {
  2069. foreach($aItems as $iFoo => $attCode)
  2070. {
  2071. if (is_array($attCode))
  2072. {
  2073. // Note: to make sure that the values will be updated recursively,
  2074. // do not pass $attCode, but $aItems[$iFoo] instead
  2075. self::Init_CheckZListItems($aItems[$iFoo], $sTargetClass);
  2076. if (count($aItems[$iFoo]) == 0)
  2077. {
  2078. unset($aItems[$iFoo]);
  2079. }
  2080. }
  2081. else if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode]))
  2082. {
  2083. unset($aItems[$iFoo]);
  2084. }
  2085. }
  2086. }
  2087. public static function FlattenZList($aList)
  2088. {
  2089. $aResult = array();
  2090. foreach($aList as $value)
  2091. {
  2092. if (!is_array($value))
  2093. {
  2094. $aResult[] = $value;
  2095. }
  2096. else
  2097. {
  2098. $aResult = array_merge($aResult, self::FlattenZList($value));
  2099. }
  2100. }
  2101. return $aResult;
  2102. }
  2103. public static function Init_DefineState($sStateCode, $aStateDef)
  2104. {
  2105. $sTargetClass = self::GetCallersPHPClass("Init");
  2106. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  2107. $sParentState = $aStateDef['attribute_inherit'];
  2108. if (!empty($sParentState))
  2109. {
  2110. // Inherit from the given state (must be defined !)
  2111. //
  2112. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  2113. // Reset the constraint when it was mandatory to set the value at the previous state
  2114. //
  2115. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  2116. {
  2117. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  2118. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  2119. $aToInherit['attribute_list'][$sState] = $iFlags;
  2120. }
  2121. // The inherited configuration could be overriden
  2122. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  2123. }
  2124. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  2125. {
  2126. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  2127. {
  2128. unset($aStateDef['attribute_list'][$sAttCode]);
  2129. }
  2130. }
  2131. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  2132. // by default, create an empty set of transitions associated to that state
  2133. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  2134. }
  2135. public static function Init_DefineHighlightScale($aHighlightScale)
  2136. {
  2137. $sTargetClass = self::GetCallersPHPClass("Init");
  2138. self::$m_aHighlightScales[$sTargetClass] = $aHighlightScale;
  2139. }
  2140. public static function GetHighlightScale($sTargetClass)
  2141. {
  2142. $aScale = array();
  2143. $aParentScale = array();
  2144. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2145. if (!empty($sParentClass))
  2146. {
  2147. // inherit the scale from the parent class
  2148. $aParentScale = self::GetHighlightScale($sParentClass);
  2149. }
  2150. if (array_key_exists($sTargetClass, self::$m_aHighlightScales))
  2151. {
  2152. $aScale = self::$m_aHighlightScales[$sTargetClass];
  2153. }
  2154. return array_merge($aParentScale, $aScale); // Merge both arrays, the values from the last one have precedence
  2155. }
  2156. public static function GetHighlightCode($sTargetClass, $sStateCode)
  2157. {
  2158. $sCode = '';
  2159. if ( array_key_exists($sTargetClass, self::$m_aStates)
  2160. && array_key_exists($sStateCode, self::$m_aStates[$sTargetClass])
  2161. && array_key_exists('highlight', self::$m_aStates[$sTargetClass][$sStateCode]) )
  2162. {
  2163. $sCode = self::$m_aStates[$sTargetClass][$sStateCode]['highlight']['code'];
  2164. }
  2165. else
  2166. {
  2167. // Check the parent's definition
  2168. $sParentClass = self::GetParentPersistentClass($sTargetClass);
  2169. if (!empty($sParentClass))
  2170. {
  2171. $sCode = self::GetHighlightCode($sParentClass, $sStateCode);
  2172. }
  2173. }
  2174. return $sCode;
  2175. }
  2176. public static function Init_OverloadStateAttribute($sStateCode, $sAttCode, $iFlags)
  2177. {
  2178. // Warning: this is not sufficient: the flags have to be copied to the states that are inheriting from this state
  2179. $sTargetClass = self::GetCallersPHPClass("Init");
  2180. self::$m_aStates[$sTargetClass][$sStateCode]['attribute_list'][$sAttCode] = $iFlags;
  2181. }
  2182. public static function Init_DefineStimulus($oStimulus)
  2183. {
  2184. $sTargetClass = self::GetCallersPHPClass("Init");
  2185. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  2186. // I wanted to simplify the syntax of the declaration of objects in the biz model
  2187. // Therefore, the reference to the host class is set there
  2188. $oStimulus->SetHostClass($sTargetClass);
  2189. }
  2190. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  2191. {
  2192. $sTargetClass = self::GetCallersPHPClass("Init");
  2193. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  2194. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  2195. }
  2196. public static function Init_InheritLifecycle($sSourceClass = '')
  2197. {
  2198. $sTargetClass = self::GetCallersPHPClass("Init");
  2199. if (empty($sSourceClass))
  2200. {
  2201. // Default: inherit from parent class
  2202. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  2203. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  2204. }
  2205. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  2206. self::$m_aStates[$sTargetClass] = self::$m_aStates[$sSourceClass];
  2207. // #@# Note: the aim is to clone the data, could be an issue if the simuli objects are changed
  2208. self::$m_aStimuli[$sTargetClass] = self::$m_aStimuli[$sSourceClass];
  2209. self::$m_aTransitions[$sTargetClass] = self::$m_aTransitions[$sSourceClass];
  2210. }
  2211. //
  2212. // Static API
  2213. //
  2214. public static function GetRootClass($sClass = null)
  2215. {
  2216. self::_check_subclass($sClass);
  2217. return self::$m_aRootClasses[$sClass];
  2218. }
  2219. public static function IsRootClass($sClass)
  2220. {
  2221. self::_check_subclass($sClass);
  2222. return (self::GetRootClass($sClass) == $sClass);
  2223. }
  2224. public static function GetParentClass($sClass)
  2225. {
  2226. if (count(self::$m_aParentClasses[$sClass]) == 0)
  2227. {
  2228. return null;
  2229. }
  2230. else
  2231. {
  2232. return end(self::$m_aParentClasses[$sClass]);
  2233. }
  2234. }
  2235. public static function GetLowestCommonAncestor($aClasses)
  2236. {
  2237. $sAncestor = null;
  2238. foreach($aClasses as $sClass)
  2239. {
  2240. if (is_null($sAncestor))
  2241. {
  2242. // first loop
  2243. $sAncestor = $sClass;
  2244. }
  2245. elseif ($sClass == $sAncestor)
  2246. {
  2247. // remains the same
  2248. }
  2249. elseif (self::GetRootClass($sClass) != self::GetRootClass($sAncestor))
  2250. {
  2251. $sAncestor = null;
  2252. break;
  2253. }
  2254. else
  2255. {
  2256. $sAncestor = self::LowestCommonAncestor($sAncestor, $sClass);
  2257. }
  2258. }
  2259. return $sAncestor;
  2260. }
  2261. /**
  2262. * Note: assumes that class A and B have a common ancestor
  2263. */
  2264. protected static function LowestCommonAncestor($sClassA, $sClassB)
  2265. {
  2266. if ($sClassA == $sClassB)
  2267. {
  2268. $sRet = $sClassA;
  2269. }
  2270. elseif (is_subclass_of($sClassA, $sClassB))
  2271. {
  2272. $sRet = $sClassB;
  2273. }
  2274. elseif (is_subclass_of($sClassB, $sClassA))
  2275. {
  2276. $sRet = $sClassA;
  2277. }
  2278. else
  2279. {
  2280. // Recurse
  2281. $sRet = self::LowestCommonAncestor($sClassA, self::GetParentClass($sClassB));
  2282. }
  2283. return $sRet;
  2284. }
  2285. /**
  2286. * Tells if a class contains a hierarchical key, and if so what is its AttCode
  2287. * @return mixed String = sAttCode or false if the class is not part of a hierarchy
  2288. */
  2289. public static function IsHierarchicalClass($sClass)
  2290. {
  2291. $sHierarchicalKeyCode = false;
  2292. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  2293. {
  2294. if ($oAtt->IsHierarchicalKey())
  2295. {
  2296. $sHierarchicalKeyCode = $sAttCode; // Found the hierarchical key, no need to continue
  2297. break;
  2298. }
  2299. }
  2300. return $sHierarchicalKeyCode;
  2301. }
  2302. public static function EnumRootClasses()
  2303. {
  2304. return array_unique(self::$m_aRootClasses);
  2305. }
  2306. public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF, $bRootFirst = true)
  2307. {
  2308. self::_check_subclass($sClass);
  2309. if ($bRootFirst)
  2310. {
  2311. $aRes = self::$m_aParentClasses[$sClass];
  2312. }
  2313. else
  2314. {
  2315. $aRes = array_reverse(self::$m_aParentClasses[$sClass], true);
  2316. }
  2317. if ($iOption != ENUM_PARENT_CLASSES_EXCLUDELEAF)
  2318. {
  2319. if ($bRootFirst)
  2320. {
  2321. // Leaf class at the end
  2322. $aRes[] = $sClass;
  2323. }
  2324. else
  2325. {
  2326. // Leaf class on top
  2327. array_unshift($aRes, $sClass);
  2328. }
  2329. }
  2330. return $aRes;
  2331. }
  2332. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  2333. {
  2334. self::_check_subclass($sClass);
  2335. $aRes = self::$m_aChildClasses[$sClass];
  2336. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  2337. {
  2338. // Add it to the list
  2339. $aRes[] = $sClass;
  2340. }
  2341. return $aRes;
  2342. }
  2343. public static function EnumArchivableClasses()
  2344. {
  2345. $aRes = array();
  2346. foreach (self::GetClasses() as $sClass)
  2347. {
  2348. if (self::IsArchivable($sClass))
  2349. {
  2350. $aRes[] = $sClass;
  2351. }
  2352. }
  2353. return $aRes;
  2354. }
  2355. public static function EnumObsoletableClasses()
  2356. {
  2357. $aRes = array();
  2358. foreach (self::GetClasses() as $sClass)
  2359. {
  2360. if (self::IsObsoletable($sClass))
  2361. {
  2362. $aRes[] = $sClass;
  2363. }
  2364. }
  2365. return $aRes;
  2366. }
  2367. public static function HasChildrenClasses($sClass)
  2368. {
  2369. return (count(self::$m_aChildClasses[$sClass]) > 0);
  2370. }
  2371. public static function EnumCategories()
  2372. {
  2373. return array_keys(self::$m_Category2Class);
  2374. }
  2375. // Note: use EnumChildClasses to take the compound objects into account
  2376. public static function GetSubclasses($sClass)
  2377. {
  2378. self::_check_subclass($sClass);
  2379. $aSubClasses = array();
  2380. foreach(self::$m_aClassParams as $sSubClass => $foo)
  2381. {
  2382. if (is_subclass_of($sSubClass, $sClass))
  2383. {
  2384. $aSubClasses[] = $sSubClass;
  2385. }
  2386. }
  2387. return $aSubClasses;
  2388. }
  2389. public static function GetClasses($sCategories = '', $bStrict = false)
  2390. {
  2391. $aCategories = explode(',', $sCategories);
  2392. $aClasses = array();
  2393. foreach($aCategories as $sCategory)
  2394. {
  2395. $sCategory = trim($sCategory);
  2396. if (strlen($sCategory) == 0)
  2397. {
  2398. return array_keys(self::$m_aClassParams);
  2399. }
  2400. if (array_key_exists($sCategory, self::$m_Category2Class))
  2401. {
  2402. $aClasses = array_merge($aClasses, self::$m_Category2Class[$sCategory]);
  2403. }
  2404. elseif ($bStrict)
  2405. {
  2406. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  2407. }
  2408. }
  2409. return array_unique($aClasses);
  2410. }
  2411. public static function HasTable($sClass)
  2412. {
  2413. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  2414. return true;
  2415. }
  2416. public static function IsAbstract($sClass)
  2417. {
  2418. $oReflection = new ReflectionClass($sClass);
  2419. return $oReflection->isAbstract();
  2420. }
  2421. /**
  2422. * Normalizes query arguments and adds magic parameters:
  2423. * - current_contact_id
  2424. * - current_contact (DBObject)
  2425. * - current_user (DBObject)
  2426. *
  2427. * @param array $aArgs Context arguments (some can be persistent objects)
  2428. * @param array $aMoreArgs Other query parameters
  2429. * @return array
  2430. */
  2431. public static function PrepareQueryArguments($aArgs, $aMoreArgs = array())
  2432. {
  2433. $aScalarArgs = array();
  2434. foreach(array_merge($aArgs, $aMoreArgs) as $sArgName => $value)
  2435. {
  2436. if (self::IsValidObject($value))
  2437. {
  2438. if (strpos($sArgName, '->object()') === false)
  2439. {
  2440. // Normalize object arguments
  2441. $aScalarArgs[$sArgName.'->object()'] = $value;
  2442. }
  2443. else
  2444. {
  2445. // Leave as is
  2446. $aScalarArgs[$sArgName] = $value;
  2447. }
  2448. }
  2449. else
  2450. {
  2451. if (is_scalar($value))
  2452. {
  2453. $aScalarArgs[$sArgName] = (string) $value;
  2454. }
  2455. elseif (is_null($value))
  2456. {
  2457. $aScalarArgs[$sArgName] = null;
  2458. }
  2459. elseif (is_array($value))
  2460. {
  2461. $aScalarArgs[$sArgName] = $value;
  2462. }
  2463. }
  2464. }
  2465. // Add standard magic arguments
  2466. //
  2467. $aScalarArgs['current_contact_id'] = UserRights::GetContactId(); // legacy
  2468. $oUser = UserRights::GetUserObject();
  2469. if (!is_null($oUser))
  2470. {
  2471. $aScalarArgs['current_user->object()'] = $oUser;
  2472. $oContact = UserRights::GetContactObject();
  2473. if (!is_null($oContact))
  2474. {
  2475. $aScalarArgs['current_contact->object()'] = $oContact;
  2476. }
  2477. }
  2478. return $aScalarArgs;
  2479. }
  2480. public static function MakeModifierProperties($oFilter)
  2481. {
  2482. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2483. //
  2484. $aModifierProperties = array();
  2485. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  2486. {
  2487. // Lowest precedence: the application context
  2488. $aPluginProps = ApplicationContext::GetPluginProperties($sPluginClass);
  2489. // Highest precedence: programmatically specified (or OQL)
  2490. foreach($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value)
  2491. {
  2492. $aPluginProps[$sProp] = $value;
  2493. }
  2494. if (count($aPluginProps) > 0)
  2495. {
  2496. $aModifierProperties[$sPluginClass] = $aPluginProps;
  2497. }
  2498. }
  2499. return $aModifierProperties;
  2500. }
  2501. /**
  2502. * Special processing for the hierarchical keys stored as nested sets
  2503. * @param $iId integer The identifier of the parent
  2504. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2505. * @param $stable string The name of the database table containing the hierarchical key
  2506. */
  2507. public static function HKInsertChildUnder($iId, $oAttDef, $sTable)
  2508. {
  2509. // Get the parent id.right value
  2510. if ($iId == 0)
  2511. {
  2512. // No parent, insert completely at the right of the tree
  2513. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  2514. $aRes = CMDBSource::QueryToArray($sSQL);
  2515. if (count($aRes) == 0)
  2516. {
  2517. $iMyRight = 1;
  2518. }
  2519. else
  2520. {
  2521. $iMyRight = $aRes[0]['max']+1;
  2522. }
  2523. }
  2524. else
  2525. {
  2526. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".$iId;
  2527. $iMyRight = CMDBSource::QueryToScalar($sSQL);
  2528. $sSQLUpdateRight = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + 2 WHERE `".$oAttDef->GetSQLRight()."` >= $iMyRight";
  2529. CMDBSource::Query($sSQLUpdateRight);
  2530. $sSQLUpdateLeft = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + 2 WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2531. CMDBSource::Query($sSQLUpdateLeft);
  2532. }
  2533. return array($oAttDef->GetSQLRight() => $iMyRight+1, $oAttDef->GetSQLLeft() => $iMyRight);
  2534. }
  2535. /**
  2536. * Special processing for the hierarchical keys stored as nested sets: temporary remove the branch
  2537. * @param $iId integer The identifier of the parent
  2538. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2539. * @param $sTable string The name of the database table containing the hierarchical key
  2540. */
  2541. public static function HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable)
  2542. {
  2543. $iDelta = $iMyRight - $iMyLeft + 1;
  2544. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iMyLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iMyLeft - `".$oAttDef->GetSQLLeft();
  2545. $sSQL .= "` WHERE `".$oAttDef->GetSQLLeft()."`> $iMyLeft AND `".$oAttDef->GetSQLRight()."`< $iMyRight";
  2546. CMDBSource::Query($sSQL);
  2547. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` - $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2548. CMDBSource::Query($sSQL);
  2549. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` - $iDelta WHERE `".$oAttDef->GetSQLRight()."` > $iMyRight";
  2550. CMDBSource::Query($sSQL);
  2551. }
  2552. /**
  2553. * Special processing for the hierarchical keys stored as nested sets: replug the temporary removed 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 HKReplugBranch($iNewLeft, $iNewRight, $oAttDef, $sTable)
  2559. {
  2560. $iDelta = $iNewRight - $iNewLeft + 1;
  2561. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iNewLeft";
  2562. CMDBSource::Query($sSQL);
  2563. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + $iDelta WHERE `".$oAttDef->GetSQLRight()."` >= $iNewLeft";
  2564. CMDBSource::Query($sSQL);
  2565. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iNewLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iNewLeft - `".$oAttDef->GetSQLLeft()."` WHERE `".$oAttDef->GetSQLRight()."`< 0";
  2566. CMDBSource::Query($sSQL);
  2567. }
  2568. /**
  2569. * Check (and updates if needed) the hierarchical keys
  2570. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2571. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2572. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2573. */
  2574. public static function CheckHKeys($bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2575. {
  2576. $bChangeNeeded = false;
  2577. foreach (self::GetClasses() as $sClass)
  2578. {
  2579. if (!self::HasTable($sClass)) continue;
  2580. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2581. {
  2582. // Check (once) all the attributes that are hierarchical keys
  2583. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey())
  2584. {
  2585. if ($bVerbose)
  2586. {
  2587. echo "The attribute $sAttCode from $sClass is a hierarchical key.\n";
  2588. }
  2589. $bResult = self::HKInit($sClass, $sAttCode, $bDiagnosticsOnly, $bVerbose, $bForceComputation);
  2590. $bChangeNeeded |= $bResult;
  2591. if ($bVerbose && !$bResult)
  2592. {
  2593. echo "Ok, the attribute $sAttCode from class $sClass seems up to date.\n";
  2594. }
  2595. }
  2596. }
  2597. }
  2598. return $bChangeNeeded;
  2599. }
  2600. /**
  2601. * Initializes (i.e converts) a hierarchy stored using a 'parent_id' external key
  2602. * into a hierarchy stored with a HierarchicalKey, by initializing the _left and _right values
  2603. * to correspond to the existing hierarchy in the database
  2604. * @param $sClass string Name of the class to process
  2605. * @param $sAttCode string Code of the attribute to process
  2606. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2607. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2608. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2609. * @return true if an update is needed (diagnostics only) / was performed
  2610. */
  2611. public static function HKInit($sClass, $sAttCode, $bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2612. {
  2613. $idx = 1;
  2614. $bUpdateNeeded = $bForceComputation;
  2615. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  2616. $sTable = self::DBGetTable($sClass, $sAttCode);
  2617. if ($oAttDef->IsHierarchicalKey())
  2618. {
  2619. // Check if some values already exist in the table for the _right value, if so, do nothing
  2620. $sRight = $oAttDef->GetSQLRight();
  2621. $sSQL = "SELECT MAX(`$sRight`) AS MaxRight FROM `$sTable`";
  2622. $iMaxRight = CMDBSource::QueryToScalar($sSQL);
  2623. $sSQL = "SELECT COUNT(*) AS Count FROM `$sTable`"; // Note: COUNT(field) returns zero if the given field contains only NULLs
  2624. $iCount = CMDBSource::QueryToScalar($sSQL);
  2625. if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0))
  2626. {
  2627. $bUpdateNeeded = true;
  2628. if ($bVerbose)
  2629. {
  2630. echo "The table '$sTable' must be updated to compute the fields $sRight and ".$oAttDef->GetSQLLeft()."\n";
  2631. }
  2632. }
  2633. if ($bForceComputation && !$bDiagnosticsOnly)
  2634. {
  2635. echo "Rebuilding the fields $sRight and ".$oAttDef->GetSQLLeft()." from table '$sTable'...\n";
  2636. }
  2637. if ($bUpdateNeeded && !$bDiagnosticsOnly)
  2638. {
  2639. try
  2640. {
  2641. CMDBSource::Query('START TRANSACTION');
  2642. self::HKInitChildren($sTable, $sAttCode, $oAttDef, 0, $idx);
  2643. CMDBSource::Query('COMMIT');
  2644. if ($bVerbose)
  2645. {
  2646. echo "Ok, table '$sTable' successfully updated.\n";
  2647. }
  2648. }
  2649. catch(Exception $e)
  2650. {
  2651. CMDBSource::Query('ROLLBACK');
  2652. throw new Exception("An error occured (".$e->getMessage().") while initializing the hierarchy for ($sClass, $sAttCode). The database was not modified.");
  2653. }
  2654. }
  2655. }
  2656. return $bUpdateNeeded;
  2657. }
  2658. /**
  2659. * Recursive helper function called by HKInit
  2660. */
  2661. protected static function HKInitChildren($sTable, $sAttCode, $oAttDef, $iId, &$iCurrIndex)
  2662. {
  2663. $sSQL = "SELECT id FROM `$sTable` WHERE `$sAttCode` = $iId";
  2664. $aRes = CMDBSource::QueryToArray($sSQL);
  2665. $aTree = array();
  2666. $sLeft = $oAttDef->GetSQLLeft();
  2667. $sRight = $oAttDef->GetSQLRight();
  2668. foreach($aRes as $aValues)
  2669. {
  2670. $iChildId = $aValues['id'];
  2671. $iLeft = $iCurrIndex++;
  2672. $aChildren = self::HKInitChildren($sTable, $sAttCode, $oAttDef, $iChildId, $iCurrIndex);
  2673. $iRight = $iCurrIndex++;
  2674. $sSQL = "UPDATE `$sTable` SET `$sLeft` = $iLeft, `$sRight` = $iRight WHERE id= $iChildId";
  2675. CMDBSource::Query($sSQL);
  2676. }
  2677. }
  2678. /**
  2679. * Update the meta enums
  2680. * See Also AttributeMetaEnum::MapValue that must be aligned with the above implementation
  2681. *
  2682. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2683. */
  2684. public static function RebuildMetaEnums($bVerbose = false)
  2685. {
  2686. foreach (self::GetClasses() as $sClass)
  2687. {
  2688. if (!self::HasTable($sClass)) continue;
  2689. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2690. {
  2691. // Check (once) all the attributes that are hierarchical keys
  2692. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef instanceof AttributeEnum)
  2693. {
  2694. if (isset(self::$m_aEnumToMeta[$sClass][$sAttCode]))
  2695. {
  2696. foreach (self::$m_aEnumToMeta[$sClass][$sAttCode] as $sMetaAttCode => $oMetaAttDef)
  2697. {
  2698. $aMetaValues = array(); // array of (metavalue => array of values)
  2699. foreach ($oAttDef->GetAllowedValues() as $sCode => $sLabel)
  2700. {
  2701. $aMappingData = $oMetaAttDef->GetMapRule($sClass);
  2702. if ($aMappingData == null)
  2703. {
  2704. $sMetaValue = $oMetaAttDef->GetDefaultValue();
  2705. }
  2706. else
  2707. {
  2708. if (array_key_exists($sCode, $aMappingData['values']))
  2709. {
  2710. $sMetaValue = $aMappingData['values'][$sCode];
  2711. }
  2712. elseif ($oMetaAttDef->GetDefaultValue() != '')
  2713. {
  2714. $sMetaValue = $oMetaAttDef->GetDefaultValue();
  2715. }
  2716. else
  2717. {
  2718. throw new Exception('MetaModel::RebuildMetaEnums(): mapping not found for value "'.$sCode.'"" in '.$sClass.', on attribute '.self::GetAttributeOrigin($sClass, $oMetaAttDef->GetCode()).'::'.$oMetaAttDef->GetCode());
  2719. }
  2720. }
  2721. $aMetaValues[$sMetaValue][] = $sCode;
  2722. }
  2723. foreach ($aMetaValues as $sMetaValue => $aEnumValues)
  2724. {
  2725. $sMetaTable = self::DBGetTable($sClass, $sMetaAttCode);
  2726. $sEnumTable = self::DBGetTable($sClass);
  2727. $aColumns = array_keys($oMetaAttDef->GetSQLColumns());
  2728. $sMetaColumn = reset($aColumns);
  2729. $aColumns = array_keys($oAttDef->GetSQLColumns());
  2730. $sEnumColumn = reset($aColumns);
  2731. $sValueList = implode(', ', CMDBSource::Quote($aEnumValues));
  2732. $sSql = "UPDATE `$sMetaTable` JOIN `$sEnumTable` ON `$sEnumTable`.id = `$sMetaTable`.id SET `$sMetaTable`.`$sMetaColumn` = '$sMetaValue' WHERE `$sEnumTable`.`$sEnumColumn` IN ($sValueList) AND `$sMetaTable`.`$sMetaColumn` != '$sMetaValue'";
  2733. if ($bVerbose)
  2734. {
  2735. echo "Executing query: $sSql\n";
  2736. }
  2737. CMDBSource::Query($sSql);
  2738. }
  2739. }
  2740. }
  2741. }
  2742. }
  2743. }
  2744. }
  2745. public static function CheckDataSources($bDiagnostics, $bVerbose)
  2746. {
  2747. $sOQL = 'SELECT SynchroDataSource';
  2748. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  2749. $bFixNeeded = false;
  2750. if ($bVerbose && $oSet->Count() == 0)
  2751. {
  2752. echo "There are no Data Sources in the database.\n";
  2753. }
  2754. while($oSource = $oSet->Fetch())
  2755. {
  2756. if ($bVerbose)
  2757. {
  2758. echo "Checking Data Source '".$oSource->GetName()."'...\n";
  2759. $bFixNeeded = $bFixNeeded | $oSource->CheckDBConsistency($bDiagnostics, $bVerbose);
  2760. }
  2761. }
  2762. if (!$bFixNeeded && $bVerbose)
  2763. {
  2764. echo "Ok.\n";
  2765. }
  2766. return $bFixNeeded;
  2767. }
  2768. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  2769. {
  2770. if (!array_key_exists($sNewName, $aAliases))
  2771. {
  2772. $aAliases[$sNewName] = $sRealName;
  2773. return $sNewName;
  2774. }
  2775. for ($i = 1 ; $i < 100 ; $i++)
  2776. {
  2777. $sAnAlias = $sNewName.$i;
  2778. if (!array_key_exists($sAnAlias, $aAliases))
  2779. {
  2780. // Create that new alias
  2781. $aAliases[$sAnAlias] = $sRealName;
  2782. return $sAnAlias;
  2783. }
  2784. }
  2785. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  2786. }
  2787. public static function CheckDefinitions($bExitOnError = true)
  2788. {
  2789. if (count(self::GetClasses()) == 0)
  2790. {
  2791. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  2792. }
  2793. $aErrors = array();
  2794. $aSugFix = array();
  2795. foreach (self::GetClasses() as $sClass)
  2796. {
  2797. $sTable = self::DBGetTable($sClass);
  2798. $sTableLowercase = strtolower($sTable);
  2799. if ($sTableLowercase != $sTable)
  2800. {
  2801. $aErrors[$sClass][] = "Table name '".$sTable."' has upper case characters. You might encounter issues when moving your installation between Linux and Windows.";
  2802. $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.";
  2803. }
  2804. $aNameSpec = self::GetNameSpec($sClass);
  2805. foreach($aNameSpec[1] as $i => $sAttCode)
  2806. {
  2807. if(!self::IsValidAttCode($sClass, $sAttCode))
  2808. {
  2809. $aErrors[$sClass][] = "Unknown attribute code '".$sAttCode."' for the name definition";
  2810. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2811. }
  2812. }
  2813. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  2814. {
  2815. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  2816. {
  2817. $aErrors[$sClass][] = "Unknown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  2818. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2819. }
  2820. }
  2821. $bHasWritableAttribute = false;
  2822. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2823. {
  2824. // It makes no sense to check the attributes again and again in the subclasses
  2825. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2826. if ($oAttDef->IsExternalKey())
  2827. {
  2828. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  2829. {
  2830. $aErrors[$sClass][] = "Unknown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  2831. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  2832. }
  2833. }
  2834. elseif ($oAttDef->IsExternalField())
  2835. {
  2836. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2837. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  2838. {
  2839. $aErrors[$sClass][] = "Unknown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  2840. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  2841. }
  2842. else
  2843. {
  2844. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  2845. $sTargetClass = $oKeyAttDef->GetTargetClass();
  2846. $sExtAttCode = $oAttDef->GetExtAttCode();
  2847. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  2848. {
  2849. $aErrors[$sClass][] = "Unknown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  2850. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  2851. }
  2852. }
  2853. }
  2854. else if ($oAttDef->IsLinkSet())
  2855. {
  2856. // Do nothing...
  2857. }
  2858. else if ($oAttDef instanceof AttributeStopWatch)
  2859. {
  2860. $aThresholds = $oAttDef->ListThresholds();
  2861. if (is_array($aThresholds))
  2862. {
  2863. foreach($aThresholds as $iPercent => $aDef)
  2864. {
  2865. if (array_key_exists('highlight', $aDef))
  2866. {
  2867. if(!array_key_exists('code', $aDef['highlight']))
  2868. {
  2869. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of the $iPercent% threshold in the attribute: '$sAttCode'.";
  2870. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this threshold.";
  2871. }
  2872. else
  2873. {
  2874. $aScale = self::GetHighlightScale($sClass);
  2875. if (!array_key_exists($aDef['highlight']['code'], $aScale))
  2876. {
  2877. $aErrors[$sClass][] = "'{$aDef['highlight']['code']}' is not a valid value for the 'code' element of the $iPercent% threshold in the attribute: '$sAttCode'.";
  2878. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  2879. }
  2880. }
  2881. }
  2882. }
  2883. }
  2884. }
  2885. else // standard attributes
  2886. {
  2887. // Check that the default values definition is a valid object!
  2888. $oValSetDef = $oAttDef->GetValuesDef();
  2889. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  2890. {
  2891. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  2892. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  2893. }
  2894. else
  2895. {
  2896. // Default value must be listed in the allowed values (if defined)
  2897. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2898. if (!is_null($aAllowedValues))
  2899. {
  2900. $sDefaultValue = $oAttDef->GetDefaultValue();
  2901. if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues))
  2902. {
  2903. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  2904. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  2905. }
  2906. }
  2907. }
  2908. }
  2909. // Check dependencies
  2910. if ($oAttDef->IsWritable())
  2911. {
  2912. $bHasWritableAttribute = true;
  2913. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  2914. {
  2915. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  2916. {
  2917. $aErrors[$sClass][] = "Unknown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  2918. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2919. }
  2920. }
  2921. }
  2922. }
  2923. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  2924. {
  2925. if (method_exists($oFilterDef, '__GetRefAttribute'))
  2926. {
  2927. $oAttDef = $oFilterDef->__GetRefAttribute();
  2928. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  2929. {
  2930. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  2931. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2932. }
  2933. }
  2934. }
  2935. // Lifecycle
  2936. //
  2937. $sStateAttCode = self::GetStateAttributeCode($sClass);
  2938. if (strlen($sStateAttCode) > 0)
  2939. {
  2940. // Lifecycle - check that the state attribute does exist as an attribute
  2941. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  2942. {
  2943. $aErrors[$sClass][] = "Unknown attribute code '".$sStateAttCode."' for the state definition";
  2944. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2945. }
  2946. else
  2947. {
  2948. // Lifecycle - check that there is a value set constraint on the state attribute
  2949. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  2950. $aStates = array_keys(self::EnumStates($sClass));
  2951. if (is_null($aAllowedValuesRaw))
  2952. {
  2953. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  2954. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  2955. }
  2956. else
  2957. {
  2958. $aAllowedValues = array_keys($aAllowedValuesRaw);
  2959. // Lifecycle - check the the state attribute allowed values are defined states
  2960. foreach($aAllowedValues as $sValue)
  2961. {
  2962. if (!in_array($sValue, $aStates))
  2963. {
  2964. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  2965. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2966. }
  2967. }
  2968. // Lifecycle - check that defined states are allowed values
  2969. foreach($aStates as $sStateValue)
  2970. {
  2971. if (!in_array($sStateValue, $aAllowedValues))
  2972. {
  2973. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  2974. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2975. }
  2976. }
  2977. }
  2978. // Lifecycle - check that the action handlers are defined
  2979. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  2980. {
  2981. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  2982. {
  2983. foreach ($aTransitionDef['actions'] as $actionHandler)
  2984. {
  2985. if (is_string($actionHandler))
  2986. {
  2987. if (!method_exists($sClass, $actionHandler))
  2988. {
  2989. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2990. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  2991. }
  2992. }
  2993. else // if(is_array($actionHandler))
  2994. {
  2995. $sActionHandler = $actionHandler['verb'];
  2996. if (!method_exists($sClass, $sActionHandler))
  2997. {
  2998. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2999. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(...){return true;}]";
  3000. }
  3001. }
  3002. }
  3003. }
  3004. if (array_key_exists('highlight', $aStateDef))
  3005. {
  3006. if(!array_key_exists('code', $aStateDef['highlight']))
  3007. {
  3008. $aErrors[$sClass][] = "The 'code' element is missing for the 'highlight' property of state: '$sStateCode'.";
  3009. $aSugFix[$sClass][] = "Add a 'code' entry specifying the value of the highlight code for this state.";
  3010. }
  3011. else
  3012. {
  3013. $aScale = self::GetHighlightScale($sClass);
  3014. if (!array_key_exists($aStateDef['highlight']['code'], $aScale))
  3015. {
  3016. $aErrors[$sClass][] = "'{$aStateDef['highlight']['code']}' is not a valid value for the 'code' element in the 'highlight' property of state: '$sStateCode'.";
  3017. $aSugFix[$sClass][] = "The possible highlight codes for this class are: ".implode(', ', array_keys($aScale)).".";
  3018. }
  3019. }
  3020. }
  3021. }
  3022. }
  3023. }
  3024. if ($bHasWritableAttribute)
  3025. {
  3026. if (!self::HasTable($sClass))
  3027. {
  3028. $aErrors[$sClass][] = "No table has been defined for this class";
  3029. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  3030. }
  3031. }
  3032. // ZList
  3033. //
  3034. foreach(self::EnumZLists() as $sListCode)
  3035. {
  3036. foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode)
  3037. {
  3038. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  3039. {
  3040. $aErrors[$sClass][] = "Unknown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  3041. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3042. }
  3043. }
  3044. }
  3045. // Check unicity of the SQL columns
  3046. //
  3047. if (self::HasTable($sClass))
  3048. {
  3049. $aTableColumns = array(); // array of column => attcode (the column is used by this attribute)
  3050. $aTableColumns[self::DBGetKey($sClass)] = 'id';
  3051. // Check that SQL columns are declared only once
  3052. //
  3053. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3054. {
  3055. // Skip this attribute if not originaly defined in this class
  3056. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3057. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  3058. {
  3059. if (array_key_exists($sField, $aTableColumns))
  3060. {
  3061. $aErrors[$sClass][] = "Column '$sField' declared for attribute $sAttCode, but already used for attribute ".$aTableColumns[$sField];
  3062. $aSugFix[$sClass][] = "Please find another name for the SQL column";
  3063. }
  3064. else
  3065. {
  3066. $aTableColumns[$sField] = $sAttCode;
  3067. }
  3068. }
  3069. }
  3070. }
  3071. } // foreach class
  3072. if (count($aErrors) > 0)
  3073. {
  3074. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3075. echo "<h3>Business model inconsistencies have been found</h3>\n";
  3076. // #@# later -> this is the responsibility of the caller to format the output
  3077. foreach ($aErrors as $sClass => $aMessages)
  3078. {
  3079. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  3080. echo "<ul class=\"treeview\">\n";
  3081. $i = 0;
  3082. foreach ($aMessages as $sMsg)
  3083. {
  3084. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  3085. $i++;
  3086. }
  3087. echo "</ul>\n";
  3088. }
  3089. if ($bExitOnError) echo "<p>Aborting...</p>\n";
  3090. echo "</div>\n";
  3091. if ($bExitOnError) exit;
  3092. }
  3093. }
  3094. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  3095. {
  3096. if (empty($sRepairUrl)) return;
  3097. // By design, some queries might be blank, we have to ignore them
  3098. $aCleanFixes = array();
  3099. foreach($aSQLFixes as $sSQLFix)
  3100. {
  3101. if (!empty($sSQLFix))
  3102. {
  3103. $aCleanFixes[] = $sSQLFix;
  3104. }
  3105. }
  3106. if (count($aCleanFixes) == 0) return;
  3107. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  3108. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes), ENT_QUOTES, 'UTF-8')."\">\n";
  3109. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  3110. echo "</form>\n";
  3111. }
  3112. public static function DBExists($bMustBeComplete = true)
  3113. {
  3114. // returns true if at least one table exists
  3115. //
  3116. if (!CMDBSource::IsDB(self::$m_sDBName))
  3117. {
  3118. return false;
  3119. }
  3120. CMDBSource::SelectDB(self::$m_sDBName);
  3121. $aFound = array();
  3122. $aMissing = array();
  3123. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3124. {
  3125. if (CMDBSource::IsTable($sTable))
  3126. {
  3127. $aFound[] = $sTable;
  3128. }
  3129. else
  3130. {
  3131. $aMissing[] = $sTable;
  3132. }
  3133. }
  3134. if (count($aFound) == 0)
  3135. {
  3136. // no expected table has been found
  3137. return false;
  3138. }
  3139. else
  3140. {
  3141. if (count($aMissing) == 0)
  3142. {
  3143. // the database is complete (still, could be some fields missing!)
  3144. return true;
  3145. }
  3146. else
  3147. {
  3148. // not all the tables, could be an older version
  3149. if ($bMustBeComplete)
  3150. {
  3151. return false;
  3152. }
  3153. else
  3154. {
  3155. return true;
  3156. }
  3157. }
  3158. }
  3159. }
  3160. public static function DBDrop()
  3161. {
  3162. $bDropEntireDB = true;
  3163. if (!empty(self::$m_sTablePrefix))
  3164. {
  3165. // Do drop only tables corresponding to the sub-database (table prefix)
  3166. // then possibly drop the DB itself (if no table remain)
  3167. foreach (CMDBSource::EnumTables() as $sTable)
  3168. {
  3169. // perform a case insensitive test because on Windows the table names become lowercase :-(
  3170. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  3171. {
  3172. CMDBSource::DropTable($sTable);
  3173. }
  3174. else
  3175. {
  3176. // There is at least one table which is out of the scope of the current application
  3177. $bDropEntireDB = false;
  3178. }
  3179. }
  3180. }
  3181. if ($bDropEntireDB)
  3182. {
  3183. CMDBSource::DropDB(self::$m_sDBName);
  3184. }
  3185. }
  3186. public static function DBCreate($aCallback = null)
  3187. {
  3188. // Note: we have to check if the DB does exist, because we may share the DB
  3189. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  3190. if (!CMDBSource::IsDB(self::$m_sDBName))
  3191. {
  3192. CMDBSource::CreateDB(self::$m_sDBName);
  3193. }
  3194. self::DBCreateTables($aCallback);
  3195. self::DBCreateViews();
  3196. }
  3197. protected static function DBCreateTables($aCallback = null)
  3198. {
  3199. list($aErrors, $aSugFix, $aCondensedQueries) = self::DBCheckFormat();
  3200. //$sSQL = implode('; ', $aCondensedQueries); Does not work - multiple queries not allowed
  3201. foreach($aCondensedQueries as $sQuery)
  3202. {
  3203. $fStart = microtime(true);
  3204. CMDBSource::CreateTable($sQuery);
  3205. $fDuration = microtime(true) - $fStart;
  3206. if ($aCallback != null)
  3207. {
  3208. call_user_func($aCallback, $sQuery, $fDuration);
  3209. }
  3210. }
  3211. }
  3212. protected static function DBCreateViews()
  3213. {
  3214. list($aErrors, $aSugFix) = self::DBCheckViews();
  3215. $aSQL = array();
  3216. foreach ($aSugFix as $sClass => $aTarget)
  3217. {
  3218. foreach ($aTarget as $aQueries)
  3219. {
  3220. foreach ($aQueries as $sQuery)
  3221. {
  3222. if (!empty($sQuery))
  3223. {
  3224. //$aSQL[] = $sQuery;
  3225. // forces a refresh of cached information
  3226. CMDBSource::CreateTable($sQuery);
  3227. }
  3228. }
  3229. }
  3230. }
  3231. }
  3232. public static function DBDump()
  3233. {
  3234. $aDataDump = array();
  3235. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3236. {
  3237. $aRows = CMDBSource::DumpTable($sTable);
  3238. $aDataDump[$sTable] = $aRows;
  3239. }
  3240. return $aDataDump;
  3241. }
  3242. /*
  3243. * Determines wether the target DB is frozen or not
  3244. */
  3245. public static function DBIsReadOnly()
  3246. {
  3247. // Improvement: check the mySQL variable -> Read-only
  3248. if (utils::IsArchiveMode())
  3249. {
  3250. return true;
  3251. }
  3252. if (UserRights::IsAdministrator())
  3253. {
  3254. return (!self::DBHasAccess(ACCESS_ADMIN_WRITE));
  3255. }
  3256. else
  3257. {
  3258. return (!self::DBHasAccess(ACCESS_USER_WRITE));
  3259. }
  3260. }
  3261. public static function DBHasAccess($iRequested = ACCESS_FULL)
  3262. {
  3263. $iMode = self::$m_oConfig->Get('access_mode');
  3264. if (($iMode & $iRequested) == 0) return false;
  3265. return true;
  3266. }
  3267. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  3268. {
  3269. $sValue = Dict::S($sKey, 'x-no-nothing');
  3270. if ($sValue == 'x-no-nothing')
  3271. {
  3272. $bNotInDico = true;
  3273. $sValue = $sValueFromOldSystem;
  3274. if (strlen($sValue) == 0)
  3275. {
  3276. $sValue = $sDefaultValue;
  3277. }
  3278. }
  3279. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  3280. }
  3281. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  3282. {
  3283. $sRes = '';
  3284. $sRes .= "// Dictionnay conventions\n";
  3285. $sRes .= htmlentities("// Class:<class_name>\n", ENT_QUOTES, 'UTF-8');
  3286. $sRes .= htmlentities("// Class:<class_name>+\n", ENT_QUOTES, 'UTF-8');
  3287. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n", ENT_QUOTES, 'UTF-8');
  3288. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n", ENT_QUOTES, 'UTF-8');
  3289. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n", ENT_QUOTES, 'UTF-8');
  3290. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n", ENT_QUOTES, 'UTF-8');
  3291. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n", ENT_QUOTES, 'UTF-8');
  3292. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n", ENT_QUOTES, 'UTF-8');
  3293. $sRes .= "\n";
  3294. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  3295. // Need to invent the "module", to characterize the origins of a class
  3296. if (strlen($sModules) == 0)
  3297. {
  3298. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  3299. }
  3300. else
  3301. {
  3302. $aModules = explode(', ', $sModules);
  3303. }
  3304. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3305. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  3306. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3307. foreach ($aModules as $sCategory)
  3308. {
  3309. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3310. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  3311. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3312. $sRes .= "//\n";
  3313. $sRes .= "\n";
  3314. foreach (self::GetClasses($sCategory) as $sClass)
  3315. {
  3316. if (!self::HasTable($sClass)) continue;
  3317. $bNotInDico = false;
  3318. $sClassRes = "//\n";
  3319. $sClassRes .= "// Class: $sClass\n";
  3320. $sClassRes .= "//\n";
  3321. $sClassRes .= "\n";
  3322. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  3323. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  3324. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  3325. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  3326. {
  3327. // Skip this attribute if not originaly defined in this class
  3328. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3329. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  3330. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  3331. if ($oAttDef instanceof AttributeEnum)
  3332. {
  3333. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  3334. {
  3335. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  3336. {
  3337. if (array_key_exists('label', $aStateData))
  3338. {
  3339. $sValue = $aStateData['label'];
  3340. }
  3341. else
  3342. {
  3343. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  3344. }
  3345. if (array_key_exists('description', $aStateData))
  3346. {
  3347. $sValuePlus = $aStateData['description'];
  3348. }
  3349. else
  3350. {
  3351. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  3352. }
  3353. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  3354. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  3355. }
  3356. }
  3357. else
  3358. {
  3359. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  3360. {
  3361. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  3362. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  3363. }
  3364. }
  3365. }
  3366. }
  3367. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  3368. {
  3369. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  3370. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  3371. }
  3372. $sClassRes .= "));\n";
  3373. $sClassRes .= "\n";
  3374. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  3375. {
  3376. $sRes .= $sClassRes;
  3377. }
  3378. }
  3379. }
  3380. return $sRes;
  3381. }
  3382. public static function DBCheckFormat()
  3383. {
  3384. $aErrors = array();
  3385. $aSugFix = array();
  3386. // A new way of representing things to be done - quicker to execute !
  3387. $aCreateTable = array(); // array of <table> => <table options>
  3388. $aCreateTableItems = array(); // array of <table> => array of <create definition>
  3389. $aAlterTableItems = array(); // array of <table> => <alter specification>
  3390. foreach (self::GetClasses() as $sClass)
  3391. {
  3392. if (!self::HasTable($sClass)) continue;
  3393. // Check that the table exists
  3394. //
  3395. $sTable = self::DBGetTable($sClass);
  3396. $sKeyField = self::DBGetKey($sClass);
  3397. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  3398. $sKeyFieldDefinition = "`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  3399. if (!CMDBSource::IsTable($sTable))
  3400. {
  3401. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  3402. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` ($sKeyFieldDefinition) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3403. $aCreateTable[$sTable] = "ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3404. $aCreateTableItems[$sTable][$sKeyField] = $sKeyFieldDefinition;
  3405. }
  3406. // Check that the key field exists
  3407. //
  3408. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  3409. {
  3410. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  3411. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD $sKeyFieldDefinition";
  3412. if (!array_key_exists($sTable, $aCreateTable))
  3413. {
  3414. $aAlterTableItems[$sTable][$sKeyField] = "ADD $sKeyFieldDefinition";
  3415. }
  3416. }
  3417. else
  3418. {
  3419. // Check the key field properties
  3420. //
  3421. if (!CMDBSource::IsKey($sTable, $sKeyField))
  3422. {
  3423. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  3424. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  3425. if (!array_key_exists($sTable, $aCreateTable))
  3426. {
  3427. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3428. }
  3429. }
  3430. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  3431. {
  3432. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  3433. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` $sKeyFieldDefinition";
  3434. if (!array_key_exists($sTable, $aCreateTable))
  3435. {
  3436. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3437. }
  3438. }
  3439. }
  3440. // Check that any defined field exists
  3441. //
  3442. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  3443. $aTableInfo['Fields'][$sKeyField]['used'] = true;
  3444. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3445. {
  3446. if (!$oAttDef->CopyOnAllTables())
  3447. {
  3448. // Skip this attribute if not originaly defined in this class
  3449. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3450. }
  3451. foreach($oAttDef->GetSQLColumns(true) as $sField => $sDBFieldSpec)
  3452. {
  3453. // Keep track of columns used by iTop
  3454. $aTableInfo['Fields'][$sField]['used'] = true;
  3455. $bIndexNeeded = $oAttDef->RequiresIndex();
  3456. $sFieldDefinition = "`$sField` $sDBFieldSpec";
  3457. if (!CMDBSource::IsField($sTable, $sField))
  3458. {
  3459. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  3460. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD $sFieldDefinition";
  3461. if ($bIndexNeeded)
  3462. {
  3463. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3464. }
  3465. if (array_key_exists($sTable, $aCreateTable))
  3466. {
  3467. $aCreateTableItems[$sTable][$sField] = $sFieldDefinition;
  3468. if ($bIndexNeeded)
  3469. {
  3470. $aCreateTableItems[$sTable][] = "INDEX (`$sField`)";
  3471. }
  3472. }
  3473. else
  3474. {
  3475. $aAlterTableItems[$sTable][$sField] = "ADD $sFieldDefinition";
  3476. if ($bIndexNeeded)
  3477. {
  3478. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3479. }
  3480. }
  3481. }
  3482. else
  3483. {
  3484. // The field already exists, does it have the relevant properties?
  3485. //
  3486. $bToBeChanged = false;
  3487. $sActualFieldSpec = CMDBSource::GetFieldSpec($sTable, $sField);
  3488. if (strcasecmp($sDBFieldSpec, $sActualFieldSpec) != 0)
  3489. {
  3490. $bToBeChanged = true;
  3491. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldSpec' while expecting '$sDBFieldSpec'";
  3492. }
  3493. if ($bToBeChanged)
  3494. {
  3495. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3496. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3497. }
  3498. // Create indexes (external keys only... so far)
  3499. //
  3500. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField, array($sField)))
  3501. {
  3502. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  3503. if (CMDBSource::HasIndex($sTable, $sField))
  3504. {
  3505. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` DROP INDEX `$sField`, ADD INDEX (`$sField`)";
  3506. $aAlterTableItems[$sTable][] = "DROP INDEX `$sField`";
  3507. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3508. }
  3509. else
  3510. {
  3511. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3512. $aAlterTableItems[$sTable][] = "ADD INDEX (`$sField`)";
  3513. }
  3514. }
  3515. }
  3516. }
  3517. }
  3518. // Check indexes
  3519. foreach (self::DBGetIndexes($sClass) as $aColumns)
  3520. {
  3521. $sIndexId = implode('_', $aColumns);
  3522. if(!CMDBSource::HasIndex($sTable, $sIndexId, $aColumns))
  3523. {
  3524. $sColumns = "`".implode("`, `", $aColumns)."`";
  3525. if (CMDBSource::HasIndex($sTable, $sIndexId))
  3526. {
  3527. $aErrors[$sClass]['*'][] = "Wrong index '$sIndexId' ($sColumns) in table '$sTable'";
  3528. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` DROP INDEX `$sIndexId`, ADD INDEX `$sIndexId` ($sColumns)";
  3529. }
  3530. else
  3531. {
  3532. $aErrors[$sClass]['*'][] = "Missing index '$sIndexId' ($sColumns) in table '$sTable'";
  3533. $aSugFix[$sClass]['*'][] = "ALTER TABLE `$sTable` ADD INDEX `$sIndexId` ($sColumns)";
  3534. }
  3535. if (array_key_exists($sTable, $aCreateTable))
  3536. {
  3537. $aCreateTableItems[$sTable][] = "INDEX `$sIndexId` ($sColumns)";
  3538. }
  3539. else
  3540. {
  3541. if (CMDBSource::HasIndex($sTable, $sIndexId))
  3542. {
  3543. $aAlterTableItems[$sTable][] = "DROP INDEX `$sIndexId`";
  3544. }
  3545. $aAlterTableItems[$sTable][] = "ADD INDEX `$sIndexId` ($sColumns)";
  3546. }
  3547. }
  3548. }
  3549. // Find out unused columns
  3550. //
  3551. foreach($aTableInfo['Fields'] as $sField => $aFieldData)
  3552. {
  3553. if (!isset($aFieldData['used']) || !$aFieldData['used'])
  3554. {
  3555. $aErrors[$sClass]['*'][] = "Column '$sField' in table '$sTable' is not used";
  3556. if (!CMDBSource::IsNullAllowed($sTable, $sField))
  3557. {
  3558. // Allow null values so that new record can be inserted
  3559. // without specifying the value of this unknown column
  3560. $sFieldDefinition = "`$sField` ".CMDBSource::GetFieldType($sTable, $sField).' NULL';
  3561. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3562. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3563. }
  3564. }
  3565. }
  3566. }
  3567. $aCondensedQueries = array();
  3568. foreach($aCreateTable as $sTable => $sTableOptions)
  3569. {
  3570. $sTableItems = implode(', ', $aCreateTableItems[$sTable]);
  3571. $aCondensedQueries[] = "CREATE TABLE `$sTable` ($sTableItems) $sTableOptions";
  3572. }
  3573. foreach($aAlterTableItems as $sTable => $aChangeList)
  3574. {
  3575. $sChangeList = implode(', ', $aChangeList);
  3576. $aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList";
  3577. }
  3578. return array($aErrors, $aSugFix, $aCondensedQueries);
  3579. }
  3580. public static function DBCheckViews()
  3581. {
  3582. $aErrors = array();
  3583. $aSugFix = array();
  3584. // Reporting views (must be created after any other table)
  3585. //
  3586. foreach (self::GetClasses('bizmodel') as $sClass)
  3587. {
  3588. $sView = self::DBGetView($sClass);
  3589. if (CMDBSource::IsTable($sView))
  3590. {
  3591. // Check that the view is complete
  3592. //
  3593. // Note: checking the list of attributes is not enough because the columns can be stable while the SELECT is not stable
  3594. // Example: new way to compute the friendly name
  3595. // The correct comparison algorithm is to compare the queries,
  3596. // by using "SHOW CREATE VIEW" (MySQL 5.0.1 required) or to look into INFORMATION_SCHEMA/views
  3597. // both requiring some privileges
  3598. // Decision: to simplify, let's consider the views as being wrong anytime
  3599. if (true)
  3600. {
  3601. // Rework the view
  3602. //
  3603. $oFilter = new DBObjectSearch($sClass, '');
  3604. $oFilter->AllowAllData();
  3605. $sSQL = $oFilter->MakeSelectQuery();
  3606. $aErrors[$sClass]['*'][] = "Redeclare view '$sView' (systematic - to support an eventual change in the friendly name computation)";
  3607. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  3608. }
  3609. }
  3610. else
  3611. {
  3612. // Create the view
  3613. //
  3614. $oFilter = new DBObjectSearch($sClass, '');
  3615. $oFilter->AllowAllData();
  3616. $sSQL = $oFilter->MakeSelectQuery();
  3617. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  3618. $aSugFix[$sClass]['*'][] = "DROP VIEW IF EXISTS `$sView`";
  3619. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  3620. }
  3621. }
  3622. return array($aErrors, $aSugFix);
  3623. }
  3624. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  3625. {
  3626. $sRootClass = self::GetRootClass($sClass);
  3627. $sTable = self::DBGetTable($sClass);
  3628. $sKeyField = self::DBGetKey($sClass);
  3629. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3630. {
  3631. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3632. }
  3633. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3634. if (count($aWrongRecords) == 0) return;
  3635. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3636. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3637. foreach ($aWrongRecords as $iRecordId)
  3638. {
  3639. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3640. {
  3641. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3642. {
  3643. case 'Delete':
  3644. // Already planned for a deletion
  3645. // Let's concatenate the errors description together
  3646. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3647. break;
  3648. case 'Update':
  3649. // Let's plan a deletion
  3650. break;
  3651. }
  3652. }
  3653. else
  3654. {
  3655. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3656. }
  3657. if (!$bProcessingFriends)
  3658. {
  3659. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  3660. {
  3661. // Something new to be deleted...
  3662. $iNewDelCount++;
  3663. }
  3664. }
  3665. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  3666. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  3667. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3668. $aPlannedDel[$sTable][] = $iRecordId;
  3669. }
  3670. // Now make sure that we would delete the records of the other tables for that class
  3671. //
  3672. if (!$bProcessingFriends)
  3673. {
  3674. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  3675. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  3676. {
  3677. $sFriendTable = self::DBGetTable($sFriendClass);
  3678. $sFriendKey = self::DBGetKey($sFriendClass);
  3679. // skip the current table
  3680. if ($sFriendTable == $sTable) continue;
  3681. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  3682. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  3683. }
  3684. }
  3685. }
  3686. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3687. {
  3688. $sRootClass = self::GetRootClass($sClass);
  3689. $sTable = self::DBGetTable($sClass);
  3690. $sKeyField = self::DBGetKey($sClass);
  3691. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3692. {
  3693. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3694. }
  3695. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3696. if (count($aWrongRecords) == 0) return;
  3697. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3698. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3699. foreach ($aWrongRecords as $iRecordId)
  3700. {
  3701. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3702. {
  3703. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3704. {
  3705. case 'Delete':
  3706. // No need to update, the record will be deleted!
  3707. break;
  3708. case 'Update':
  3709. // Already planned for an update
  3710. // Add this new update spec to the list
  3711. $bFoundSameSpec = false;
  3712. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  3713. {
  3714. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  3715. {
  3716. $bFoundSameSpec = true;
  3717. }
  3718. }
  3719. if (!$bFoundSameSpec)
  3720. {
  3721. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  3722. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3723. }
  3724. break;
  3725. }
  3726. }
  3727. else
  3728. {
  3729. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3730. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  3731. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  3732. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3733. }
  3734. }
  3735. }
  3736. // returns the count of records found for deletion
  3737. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3738. {
  3739. foreach (self::GetClasses() as $sClass)
  3740. {
  3741. if (!self::HasTable($sClass)) continue;
  3742. $sRootClass = self::GetRootClass($sClass);
  3743. $sTable = self::DBGetTable($sClass);
  3744. $sKeyField = self::DBGetKey($sClass);
  3745. if (!self::IsStandaloneClass($sClass))
  3746. {
  3747. if (self::IsRootClass($sClass))
  3748. {
  3749. // Check that the final class field contains the name of a class which inherited from the current class
  3750. //
  3751. $sFinalClassField = self::DBGetClassField($sClass);
  3752. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  3753. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  3754. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  3755. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3756. }
  3757. else
  3758. {
  3759. $sRootTable = self::DBGetTable($sRootClass);
  3760. $sRootKey = self::DBGetKey($sRootClass);
  3761. $sFinalClassField = self::DBGetClassField($sRootClass);
  3762. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  3763. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  3764. // Check that any record found here has its counterpart in the root table
  3765. // and which refers to a child class
  3766. //
  3767. $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";
  3768. 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);
  3769. // Check that any record found in the root table and referring to a child class
  3770. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  3771. //
  3772. $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)";
  3773. 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);
  3774. }
  3775. }
  3776. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3777. {
  3778. // Skip this attribute if not defined in this table
  3779. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3780. if ($oAttDef->IsExternalKey())
  3781. {
  3782. // Check that any external field is pointing to an existing object
  3783. //
  3784. $sRemoteClass = $oAttDef->GetTargetClass();
  3785. $sRemoteTable = self::DBGetTable($sRemoteClass);
  3786. $sRemoteKey = self::DBGetKey($sRemoteClass);
  3787. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3788. $sExtKeyField = current($aCols); // get the first column for an external key
  3789. // Note: a class/table may have an external key on itself
  3790. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  3791. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  3792. if ($oAttDef->IsNullAllowed())
  3793. {
  3794. // Exclude the records pointing to 0/null from the errors
  3795. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  3796. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  3797. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3798. }
  3799. else
  3800. {
  3801. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3802. }
  3803. // Do almost the same, taking into account the records planned for deletion
  3804. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  3805. {
  3806. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  3807. // but in that case you won't be able to track the root cause (cascading)
  3808. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  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>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3815. }
  3816. else
  3817. {
  3818. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3819. }
  3820. }
  3821. }
  3822. else if ($oAttDef->IsBasedOnDBColumns())
  3823. {
  3824. // Check that the values fit the allowed values
  3825. //
  3826. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  3827. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  3828. {
  3829. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  3830. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3831. $sMyAttributeField = current($aCols); // get the first column for the moment
  3832. $sDefaultValue = $oAttDef->GetDefaultValue();
  3833. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  3834. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3835. }
  3836. }
  3837. }
  3838. }
  3839. }
  3840. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  3841. {
  3842. // Records in error, and action to be taken: delete or update
  3843. // by RootClass/Table/Record
  3844. $aErrorsAndFixes = array();
  3845. // Records to be ignored in the current/next pass
  3846. // by Table = array of RecordId
  3847. $aPlannedDel = array();
  3848. // Count of errors in the next pass: no error means that we can leave...
  3849. $iErrorCount = 0;
  3850. // Limit in case of a bug in the algorythm
  3851. $iLoopCount = 0;
  3852. $iNewDelCount = 1; // startup...
  3853. while ($iNewDelCount > 0)
  3854. {
  3855. $iNewDelCount = 0;
  3856. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3857. $iErrorCount += $iNewDelCount;
  3858. // Safety net #1 - limit the planned deletions
  3859. //
  3860. $iMaxDel = 1000;
  3861. $iPlannedDel = 0;
  3862. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  3863. {
  3864. $iPlannedDel += count($aPlannedDelOnTable);
  3865. }
  3866. if ($iPlannedDel > $iMaxDel)
  3867. {
  3868. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  3869. break;
  3870. }
  3871. // Safety net #2 - limit the iterations
  3872. //
  3873. $iLoopCount++;
  3874. $iMaxLoops = 10;
  3875. if ($iLoopCount > $iMaxLoops)
  3876. {
  3877. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  3878. break;
  3879. }
  3880. }
  3881. // Display the results
  3882. //
  3883. $iIssueCount = 0;
  3884. $aFixesDelete = array();
  3885. $aFixesUpdate = array();
  3886. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  3887. {
  3888. foreach ($aTables as $sTable => $aRecords)
  3889. {
  3890. foreach ($aRecords as $iRecord => $aError)
  3891. {
  3892. $sAction = $aError['Action'];
  3893. $sReason = $aError['Reason'];
  3894. $iPass = $aError['Pass'];
  3895. switch ($sAction)
  3896. {
  3897. case 'Delete':
  3898. $sActionDetails = "";
  3899. $aFixesDelete[$sTable][] = $iRecord;
  3900. break;
  3901. case 'Update':
  3902. $aUpdateDesc = array();
  3903. foreach($aError['Action_Details'] as $aUpdateSpec)
  3904. {
  3905. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  3906. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  3907. }
  3908. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  3909. break;
  3910. default:
  3911. $sActionDetails = "bug: unknown action '$sAction'";
  3912. }
  3913. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  3914. $iIssueCount++;
  3915. }
  3916. }
  3917. }
  3918. if ($iIssueCount > 0)
  3919. {
  3920. // Build the queries to fix in the database
  3921. //
  3922. // First step, be able to get class data out of the table name
  3923. // Could be optimized, because we've made the job earlier... but few benefits, so...
  3924. $aTable2ClassProp = array();
  3925. foreach (self::GetClasses() as $sClass)
  3926. {
  3927. if (!self::HasTable($sClass)) continue;
  3928. $sRootClass = self::GetRootClass($sClass);
  3929. $sTable = self::DBGetTable($sClass);
  3930. $sKeyField = self::DBGetKey($sClass);
  3931. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3932. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  3933. }
  3934. // Second step, build a flat list of SQL queries
  3935. $aSQLFixes = array();
  3936. $iPlannedUpdate = 0;
  3937. foreach ($aFixesUpdate as $sTable => $aColumns)
  3938. {
  3939. foreach ($aColumns as $sColumn => $aNewValues)
  3940. {
  3941. foreach ($aNewValues as $sNewValue => $aRecords)
  3942. {
  3943. $iPlannedUpdate += count($aRecords);
  3944. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  3945. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  3946. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  3947. }
  3948. }
  3949. }
  3950. $iPlannedDel = 0;
  3951. foreach ($aFixesDelete as $sTable => $aRecords)
  3952. {
  3953. $iPlannedDel += count($aRecords);
  3954. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  3955. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  3956. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  3957. }
  3958. // Report the results
  3959. //
  3960. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3961. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  3962. // #@# later -> this is the responsibility of the caller to format the output
  3963. echo "<ul class=\"treeview\">\n";
  3964. foreach ($aIssues as $sIssueDesc)
  3965. {
  3966. echo "<li>$sIssueDesc</li>\n";
  3967. }
  3968. echo "</ul>\n";
  3969. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  3970. echo "<p>Aborting...</p>\n";
  3971. echo "</div>\n";
  3972. exit;
  3973. }
  3974. }
  3975. public static function Startup($config, $bModelOnly = false, $bAllowCache = true, $bTraceSourceFiles = false, $sEnvironment = 'production')
  3976. {
  3977. self::$m_sEnvironment = $sEnvironment;
  3978. if (!defined('MODULESROOT'))
  3979. {
  3980. define('MODULESROOT', APPROOT.'env-'.self::$m_sEnvironment.'/');
  3981. self::$m_bTraceSourceFiles = $bTraceSourceFiles;
  3982. // $config can be either a filename, or a Configuration object (volatile!)
  3983. if ($config instanceof Config)
  3984. {
  3985. self::LoadConfig($config, $bAllowCache);
  3986. }
  3987. else
  3988. {
  3989. self::LoadConfig(new Config($config), $bAllowCache);
  3990. }
  3991. if ($bModelOnly) return;
  3992. }
  3993. CMDBSource::SelectDB(self::$m_sDBName);
  3994. foreach(get_declared_classes() as $sPHPClass)
  3995. {
  3996. if (is_subclass_of($sPHPClass, 'ModuleHandlerAPI'))
  3997. {
  3998. $aCallSpec = array($sPHPClass, 'OnMetaModelStarted');
  3999. call_user_func_array($aCallSpec, array());
  4000. }
  4001. }
  4002. if (false)
  4003. {
  4004. echo "Debug<br/>\n";
  4005. self::static_var_dump();
  4006. }
  4007. }
  4008. public static function LoadConfig($oConfiguration, $bAllowCache = false)
  4009. {
  4010. self::$m_oConfig = $oConfiguration;
  4011. // Set log ASAP
  4012. if (self::$m_oConfig->GetLogGlobal())
  4013. {
  4014. if (self::$m_oConfig->GetLogIssue())
  4015. {
  4016. self::$m_bLogIssue = true;
  4017. IssueLog::Enable(APPROOT.'log/error.log');
  4018. }
  4019. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  4020. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  4021. ToolsLog::Enable(APPROOT.'log/tools.log');
  4022. }
  4023. else
  4024. {
  4025. self::$m_bLogIssue = false;
  4026. self::$m_bLogNotification = false;
  4027. self::$m_bLogWebService = false;
  4028. }
  4029. ExecutionKPI::EnableDuration(self::$m_oConfig->Get('log_kpi_duration'));
  4030. ExecutionKPI::EnableMemory(self::$m_oConfig->Get('log_kpi_memory'));
  4031. ExecutionKPI::SetAllowedUser(self::$m_oConfig->Get('log_kpi_user_id'));
  4032. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  4033. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  4034. self::$m_bUseAPCCache = $bAllowCache
  4035. && self::$m_oConfig->Get('apc_cache.enabled')
  4036. && function_exists('apc_fetch')
  4037. && function_exists('apc_store');
  4038. DBSearch::EnableQueryCache(self::$m_oConfig->GetQueryCacheEnabled(), self::$m_bUseAPCCache, self::$m_oConfig->Get('apc_cache.query_ttl'));
  4039. DBSearch::EnableQueryTrace(self::$m_oConfig->GetLogQueries());
  4040. DBSearch::EnableQueryIndentation(self::$m_oConfig->Get('query_indentation_enabled'));
  4041. DBSearch::EnableOptimizeQuery(self::$m_oConfig->Get('query_optimization_enabled'));
  4042. // PHP timezone first...
  4043. //
  4044. $sPHPTimezone = self::$m_oConfig->Get('timezone');
  4045. if ($sPHPTimezone == '')
  4046. {
  4047. // Leave as is... up to the admin to set a value somewhere...
  4048. //$sPHPTimezone = date_default_timezone_get();
  4049. }
  4050. else
  4051. {
  4052. date_default_timezone_set($sPHPTimezone);
  4053. }
  4054. // Note: load the dictionary as soon as possible, because it might be
  4055. // needed when some error occur
  4056. $sAppIdentity = 'itop-'.MetaModel::GetEnvironmentId();
  4057. $bDictInitializedFromData = false;
  4058. if (self::$m_bUseAPCCache)
  4059. {
  4060. Dict::EnableCache($sAppIdentity);
  4061. }
  4062. require_once(APPROOT.'env-'.self::$m_sEnvironment.'/dictionaries/languages.php');
  4063. // Set the default language...
  4064. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  4065. // Romain: this is the only way I've found to cope with the fact that
  4066. // classes have to be derived from cmdbabstract (to be editable in the UI)
  4067. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  4068. require_once(APPROOT.'core/autoload.php');
  4069. require_once(APPROOT.'env-'.self::$m_sEnvironment.'/autoload.php');
  4070. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  4071. {
  4072. self::IncludeModule($sToInclude, 'addons');
  4073. }
  4074. $sServer = self::$m_oConfig->GetDBHost();
  4075. $sUser = self::$m_oConfig->GetDBUser();
  4076. $sPwd = self::$m_oConfig->GetDBPwd();
  4077. $sSource = self::$m_oConfig->GetDBName();
  4078. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  4079. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  4080. $sCollation = self::$m_oConfig->GetDBCollation();
  4081. if (self::$m_bUseAPCCache)
  4082. {
  4083. $oKPI = new ExecutionKPI();
  4084. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  4085. //
  4086. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-metamodel';
  4087. $result = apc_fetch($sOqlAPCCacheId);
  4088. if (is_array($result))
  4089. {
  4090. // todo - verifier que toutes les classes mentionnees ici sont chargees dans InitClasses()
  4091. self::$m_aExtensionClasses = $result['m_aExtensionClasses'];
  4092. self::$m_Category2Class = $result['m_Category2Class'];
  4093. self::$m_aRootClasses = $result['m_aRootClasses'];
  4094. self::$m_aParentClasses = $result['m_aParentClasses'];
  4095. self::$m_aChildClasses = $result['m_aChildClasses'];
  4096. self::$m_aClassParams = $result['m_aClassParams'];
  4097. self::$m_aAttribDefs = $result['m_aAttribDefs'];
  4098. self::$m_aAttribOrigins = $result['m_aAttribOrigins'];
  4099. self::$m_aIgnoredAttributes = $result['m_aIgnoredAttributes'];
  4100. self::$m_aFilterDefs = $result['m_aFilterDefs'];
  4101. self::$m_aFilterOrigins = $result['m_aFilterOrigins'];
  4102. self::$m_aListInfos = $result['m_aListInfos'];
  4103. self::$m_aListData = $result['m_aListData'];
  4104. self::$m_aRelationInfos = $result['m_aRelationInfos'];
  4105. self::$m_aStates = $result['m_aStates'];
  4106. self::$m_aStimuli = $result['m_aStimuli'];
  4107. self::$m_aTransitions = $result['m_aTransitions'];
  4108. self::$m_aHighlightScales = $result['m_aHighlightScales'];
  4109. self::$m_aEnumToMeta = $result['m_aEnumToMeta'];
  4110. }
  4111. $oKPI->ComputeAndReport('Metamodel APC (fetch + read)');
  4112. }
  4113. if (count(self::$m_aAttribDefs) == 0)
  4114. {
  4115. // The includes have been included, let's browse the existing classes and
  4116. // develop some data based on the proposed model
  4117. $oKPI = new ExecutionKPI();
  4118. self::InitClasses($sTablePrefix);
  4119. $oKPI->ComputeAndReport('Initialization of Data model structures');
  4120. if (self::$m_bUseAPCCache)
  4121. {
  4122. $oKPI = new ExecutionKPI();
  4123. $aCache = array();
  4124. $aCache['m_aExtensionClasses'] = self::$m_aExtensionClasses;
  4125. $aCache['m_Category2Class'] = self::$m_Category2Class;
  4126. $aCache['m_aRootClasses'] = self::$m_aRootClasses; // array of "classname" => "rootclass"
  4127. $aCache['m_aParentClasses'] = self::$m_aParentClasses; // array of ("classname" => array of "parentclass")
  4128. $aCache['m_aChildClasses'] = self::$m_aChildClasses; // array of ("classname" => array of "childclass")
  4129. $aCache['m_aClassParams'] = self::$m_aClassParams; // array of ("classname" => array of class information)
  4130. $aCache['m_aAttribDefs'] = self::$m_aAttribDefs; // array of ("classname" => array of attributes)
  4131. $aCache['m_aAttribOrigins'] = self::$m_aAttribOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4132. $aCache['m_aIgnoredAttributes'] = self::$m_aIgnoredAttributes; //array of ("classname" => array of ("attcode")
  4133. $aCache['m_aFilterDefs'] = self::$m_aFilterDefs; // array of ("classname" => array filterdef)
  4134. $aCache['m_aFilterOrigins'] = self::$m_aFilterOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4135. $aCache['m_aListInfos'] = self::$m_aListInfos; // array of ("listcode" => various info on the list, common to every classes)
  4136. $aCache['m_aListData'] = self::$m_aListData; // array of ("classname" => array of "listcode" => list)
  4137. $aCache['m_aRelationInfos'] = self::$m_aRelationInfos; // array of ("relcode" => various info on the list, common to every classes)
  4138. $aCache['m_aStates'] = self::$m_aStates; // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  4139. $aCache['m_aStimuli'] = self::$m_aStimuli; // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  4140. $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)))
  4141. $aCache['m_aHighlightScales'] = self::$m_aHighlightScales; // array of ("classname" => array of higlightcodes)))
  4142. $aCache['m_aEnumToMeta'] = self::$m_aEnumToMeta;
  4143. apc_store($sOqlAPCCacheId, $aCache);
  4144. $oKPI->ComputeAndReport('Metamodel APC (store)');
  4145. }
  4146. }
  4147. self::$m_sDBName = $sSource;
  4148. self::$m_sTablePrefix = $sTablePrefix;
  4149. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  4150. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  4151. // Later when timezone implementation is correctly done: CMDBSource::SetTimezone($sDBTimezone);
  4152. }
  4153. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  4154. {
  4155. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  4156. }
  4157. public static function GetModuleParameter($sModule, $sProperty, $defaultvalue = null)
  4158. {
  4159. $value = $defaultvalue;
  4160. if (!array_key_exists($sModule, self::$m_aModulesParameters))
  4161. {
  4162. }
  4163. if (!self::$m_aModulesParameters[$sModule] == null)
  4164. {
  4165. $value = self::$m_aModulesParameters[$sModule]->Get($sProperty, $defaultvalue);
  4166. }
  4167. return $value;
  4168. }
  4169. /**
  4170. * @return Config
  4171. */
  4172. public static function GetConfig()
  4173. {
  4174. return self::$m_oConfig;
  4175. }
  4176. public static function GetEnvironmentId()
  4177. {
  4178. return md5(APPROOT).'-'.self::$m_sEnvironment;
  4179. }
  4180. protected static $m_aExtensionClasses = array();
  4181. protected static function IncludeModule($sToInclude, $sModuleType = null)
  4182. {
  4183. $sFirstChar = substr($sToInclude, 0, 1);
  4184. $sSecondChar = substr($sToInclude, 1, 1);
  4185. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  4186. {
  4187. // It is a relative path, prepend APPROOT
  4188. if (substr($sToInclude, 0, 3) == '../')
  4189. {
  4190. // Preserve compatibility with config files written before 1.0.1
  4191. // Replace '../' by '<root>/'
  4192. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  4193. }
  4194. else
  4195. {
  4196. $sFile = APPROOT.'/'.$sToInclude;
  4197. }
  4198. }
  4199. else
  4200. {
  4201. // Leave as is - should be an absolute path
  4202. $sFile = $sToInclude;
  4203. }
  4204. if (!file_exists($sFile))
  4205. {
  4206. $sConfigFile = self::$m_oConfig->GetLoadedFile();
  4207. if ($sModuleType == null)
  4208. {
  4209. throw new CoreException("Include: unable to load the file '$sFile'");
  4210. }
  4211. else
  4212. {
  4213. if (strlen($sConfigFile) > 0)
  4214. {
  4215. throw new CoreException('Include: wrong file name in configuration file', array('config file' => $sConfigFile, 'section' => $sModuleType, 'filename' => $sFile));
  4216. }
  4217. else
  4218. {
  4219. // The configuration is in memory only
  4220. throw new CoreException('Include: wrong file name in configuration file (in memory)', array('section' => $sModuleType, 'filename' => $sFile));
  4221. }
  4222. }
  4223. }
  4224. // Note: We do not expect the modules to output characters while loading them.
  4225. // Therefore, and because unexpected characters can corrupt the output,
  4226. // they must be trashed here.
  4227. // Additionnaly, pages aiming at delivering data in their output can call WebPage::TrashUnexpectedOutput()
  4228. // to get rid of chars that could be generated during the execution of the code
  4229. ob_start();
  4230. require_once($sFile);
  4231. $sPreviousContent = ob_get_clean();
  4232. if (self::$m_oConfig->Get('debug_report_spurious_chars'))
  4233. {
  4234. if ($sPreviousContent != '')
  4235. {
  4236. IssueLog::Error("Spurious characters injected by '$sFile'");
  4237. }
  4238. }
  4239. }
  4240. // Building an object
  4241. //
  4242. //
  4243. private static $aQueryCacheGetObject = array();
  4244. private static $aQueryCacheGetObjectHits = array();
  4245. public static function GetQueryCacheStatus()
  4246. {
  4247. $aRes = array();
  4248. $iTotalHits = 0;
  4249. foreach(self::$aQueryCacheGetObjectHits as $sClassSign => $iHits)
  4250. {
  4251. $aRes[] = "$sClassSign: $iHits";
  4252. $iTotalHits += $iHits;
  4253. }
  4254. return $iTotalHits.' ('.implode(', ', $aRes).')';
  4255. }
  4256. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4257. {
  4258. // Build the query cache signature
  4259. //
  4260. $sQuerySign = $sClass;
  4261. if($bAllowAllData)
  4262. {
  4263. $sQuerySign .= '_all_';
  4264. }
  4265. if (count($aModifierProperties))
  4266. {
  4267. array_multisort($aModifierProperties);
  4268. $sModifierProperties = json_encode($aModifierProperties);
  4269. $sQuerySign .= '_all_'.md5($sModifierProperties);
  4270. }
  4271. $sQuerySign .= utils::IsArchiveMode() ? '_arch_' : '';
  4272. if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject))
  4273. {
  4274. // NOTE: Quick and VERY dirty caching mechanism which relies on
  4275. // the fact that the string '987654321' will never appear in the
  4276. // standard query
  4277. // This could be simplified a little, relying solely on the query cache,
  4278. // but this would slow down -by how much time?- the application
  4279. $oFilter = new DBObjectSearch($sClass);
  4280. $oFilter->AddCondition('id', 987654321, '=');
  4281. if ($aModifierProperties)
  4282. {
  4283. foreach ($aModifierProperties as $sPluginClass => $aProperties)
  4284. {
  4285. foreach ($aProperties as $sProperty => $value)
  4286. {
  4287. $oFilter->SetModifierProperty($sPluginClass, $sProperty, $value);
  4288. }
  4289. }
  4290. }
  4291. if ($bAllowAllData)
  4292. {
  4293. $oFilter->AllowAllData();
  4294. }
  4295. $oFilter->NoContextParameters();
  4296. $sSQL = $oFilter->MakeSelectQuery();
  4297. self::$aQueryCacheGetObject[$sQuerySign] = $sSQL;
  4298. self::$aQueryCacheGetObjectHits[$sQuerySign] = 0;
  4299. }
  4300. else
  4301. {
  4302. $sSQL = self::$aQueryCacheGetObject[$sQuerySign];
  4303. self::$aQueryCacheGetObjectHits[$sQuerySign] += 1;
  4304. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sQuerySign]."<br/>\n";
  4305. }
  4306. $sSQL = str_replace(CMDBSource::Quote(987654321), CMDBSource::Quote($iKey), $sSQL);
  4307. $res = CMDBSource::Query($sSQL);
  4308. $aRow = CMDBSource::FetchArray($res);
  4309. CMDBSource::FreeResult($res);
  4310. if ($bMustBeFound && empty($aRow))
  4311. {
  4312. throw new CoreException("No result for the single row query: '$sSQL'");
  4313. }
  4314. return $aRow;
  4315. }
  4316. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  4317. {
  4318. self::_check_subclass($sClass);
  4319. if (strlen($sClassAlias) == 0)
  4320. {
  4321. $sClassAlias = $sClass;
  4322. }
  4323. // Compound objects: if available, get the final object class
  4324. //
  4325. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  4326. {
  4327. // Either this is a bug (forgot to specify a root class with a finalclass field
  4328. // Or this is the expected behavior, because the object is not made of several tables
  4329. }
  4330. elseif (empty($aRow[$sClassAlias."finalclass"]))
  4331. {
  4332. // The data is missing in the DB
  4333. // @#@ possible improvement: check that the class is valid !
  4334. $sRootClass = self::GetRootClass($sClass);
  4335. $sFinalClassField = self::DBGetClassField($sRootClass);
  4336. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  4337. }
  4338. else
  4339. {
  4340. // do the job for the real target class
  4341. $sClass = $aRow[$sClassAlias."finalclass"];
  4342. }
  4343. return new $sClass($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  4344. }
  4345. /**
  4346. * @param $sClass
  4347. * @param $iKey
  4348. * @param bool $bMustBeFound
  4349. * @param bool $bAllowAllData
  4350. * @param null $aModifierProperties
  4351. * @return DBObject|null
  4352. */
  4353. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4354. {
  4355. self::_check_subclass($sClass);
  4356. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
  4357. if (empty($aRow))
  4358. {
  4359. return null;
  4360. }
  4361. return self::GetObjectByRow($sClass, $aRow);
  4362. }
  4363. public static function GetObjectWithArchive($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4364. {
  4365. utils::PushArchiveMode(true);
  4366. $oObject = static::GetObject($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
  4367. utils::PopArchiveMode();
  4368. return $oObject;
  4369. }
  4370. public static function GetObjectByName($sClass, $sName, $bMustBeFound = true)
  4371. {
  4372. self::_check_subclass($sClass);
  4373. $oObjSearch = new DBObjectSearch($sClass);
  4374. $oObjSearch->AddNameCondition($sName);
  4375. $oSet = new DBObjectSet($oObjSearch);
  4376. if ($oSet->Count() != 1)
  4377. {
  4378. if ($bMustBeFound) throw new CoreException('Failed to get an object by its name', array('class'=>$sClass, 'name'=>$sName));
  4379. return null;
  4380. }
  4381. $oObj = $oSet->fetch();
  4382. return $oObj;
  4383. }
  4384. static protected $m_aCacheObjectByColumn = array();
  4385. public static function GetObjectByColumn($sClass, $sAttCode, $value, $bMustBeFoundUnique = true)
  4386. {
  4387. if (!isset(self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value]))
  4388. {
  4389. self::_check_subclass($sClass);
  4390. $oObjSearch = new DBObjectSearch($sClass);
  4391. $oObjSearch->AddCondition($sAttCode, $value, '=');
  4392. $oSet = new DBObjectSet($oObjSearch);
  4393. if ($oSet->Count() == 1)
  4394. {
  4395. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch();
  4396. }
  4397. else
  4398. {
  4399. if ($bMustBeFoundUnique) throw new CoreException('Failed to get an object by column', array('class'=>$sClass, 'attcode'=>$sAttCode, 'value'=>$value, 'matches' => $oSet->Count()));
  4400. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null;
  4401. }
  4402. }
  4403. return self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value];
  4404. }
  4405. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  4406. {
  4407. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  4408. if ($bAllowAllData)
  4409. {
  4410. $oFilter->AllowAllData();
  4411. }
  4412. $oSet = new DBObjectSet($oFilter);
  4413. $oObject = $oSet->Fetch();
  4414. return $oObject;
  4415. }
  4416. public static function GetHyperLink($sTargetClass, $iKey)
  4417. {
  4418. if ($iKey < 0)
  4419. {
  4420. return "$sTargetClass: $iKey (invalid value)";
  4421. }
  4422. $oObj = self::GetObject($sTargetClass, $iKey, false);
  4423. if (is_null($oObj))
  4424. {
  4425. // Whatever we are looking for, the root class is the key to search for
  4426. $sRootClass = self::GetRootClass($sTargetClass);
  4427. $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', array('objclass' => $sRootClass, 'objkey' => $iKey));
  4428. $oSet = new DBObjectSet($oSearch);
  4429. $oRecord = $oSet->Fetch();
  4430. // An empty fname is obtained with iTop < 2.0
  4431. if (is_null($oRecord) || (strlen(trim($oRecord->Get('fname'))) == 0))
  4432. {
  4433. $sName = Dict::Format('Core:UnknownObjectLabel', $sTargetClass, $iKey);
  4434. $sTitle = Dict::S('Core:UnknownObjectTip');
  4435. }
  4436. else
  4437. {
  4438. $sName = $oRecord->Get('fname');
  4439. $sTitle = Dict::Format('Core:DeletedObjectTip', $oRecord->Get('date'), $oRecord->Get('userinfo'));
  4440. }
  4441. return '<span class="itop-deleted-object" title="'.htmlentities($sTitle, ENT_QUOTES, 'UTF-8').'">'.htmlentities($sName, ENT_QUOTES, 'UTF-8').'</span>';
  4442. }
  4443. return $oObj->GetHyperLink();
  4444. }
  4445. public static function NewObject($sClass)
  4446. {
  4447. self::_check_subclass($sClass);
  4448. return new $sClass();
  4449. }
  4450. public static function GetNextKey($sClass)
  4451. {
  4452. $sRootClass = MetaModel::GetRootClass($sClass);
  4453. $sRootTable = MetaModel::DBGetTable($sRootClass);
  4454. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  4455. return $iNextKey;
  4456. }
  4457. /**
  4458. * Deletion of records, bypassing DBObject::DBDelete !!!
  4459. * It is NOT recommended to use this shortcut
  4460. * In particular, it will not work
  4461. * - if the class is not a final class
  4462. * - if the class has a hierarchical key (need to rebuild the indexes)
  4463. * - if the class overload DBDelete !
  4464. * Todo: protect it against forbidden usages (in such a case, delete objects one by one)
  4465. */
  4466. public static function BulkDelete(DBObjectSearch $oFilter)
  4467. {
  4468. $sSQL = $oFilter->MakeDeleteQuery();
  4469. if (!self::DBIsReadOnly())
  4470. {
  4471. CMDBSource::Query($sSQL);
  4472. }
  4473. }
  4474. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  4475. {
  4476. // $aValues is an array of $sAttCode => $value
  4477. $sSQL = $oFilter->MakeUpdateQuery($aValues);
  4478. if (!self::DBIsReadOnly())
  4479. {
  4480. CMDBSource::Query($sSQL);
  4481. }
  4482. }
  4483. /**
  4484. * Helper to remove selected objects without calling any handler
  4485. * Surpasses BulkDelete as it can handle abstract classes, but has the other limitation as it bypasses standard objects handlers
  4486. *
  4487. * @param string $oFilter Scope of objects to wipe out
  4488. * @return The count of deleted objects
  4489. */
  4490. public static function PurgeData($oFilter)
  4491. {
  4492. $sTargetClass = $oFilter->GetClass();
  4493. $oSet = new DBObjectSet($oFilter);
  4494. $oSet->OptimizeColumnLoad(array($sTargetClass => array('finalclass')));
  4495. $aIdToClass = $oSet->GetColumnAsArray('finalclass', true);
  4496. $aIds = array_keys($aIdToClass);
  4497. if (count($aIds) > 0)
  4498. {
  4499. $aQuotedIds = CMDBSource::Quote($aIds);
  4500. $sIdList = implode(',', $aQuotedIds);
  4501. $aTargetClasses = array_merge(
  4502. self::EnumChildClasses($sTargetClass, ENUM_CHILD_CLASSES_ALL),
  4503. self::EnumParentClasses($sTargetClass, ENUM_PARENT_CLASSES_EXCLUDELEAF)
  4504. );
  4505. foreach ($aTargetClasses as $sSomeClass)
  4506. {
  4507. $sTable = MetaModel::DBGetTable($sSomeClass);
  4508. $sPKField = MetaModel::DBGetKey($sSomeClass);
  4509. $sDeleteSQL = "DELETE FROM `$sTable` WHERE `$sPKField` IN ($sIdList)";
  4510. CMDBSource::DeleteFrom($sDeleteSQL);
  4511. }
  4512. }
  4513. return count($aIds);
  4514. }
  4515. // Links
  4516. //
  4517. //
  4518. public static function EnumReferencedClasses($sClass)
  4519. {
  4520. self::_check_subclass($sClass);
  4521. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  4522. $aResult = array();
  4523. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  4524. {
  4525. if ($oAttDef->IsExternalKey())
  4526. {
  4527. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  4528. }
  4529. }
  4530. return $aResult;
  4531. }
  4532. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  4533. {
  4534. self::_check_subclass($sClass);
  4535. if ($bSkipLinkingClasses)
  4536. {
  4537. $aLinksClasses = self::EnumLinksClasses();
  4538. }
  4539. // 1-N links (referencing my class), array of sClass => array of sAttcode
  4540. $aResult = array();
  4541. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4542. {
  4543. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  4544. $aExtKeys = array();
  4545. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4546. {
  4547. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4548. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  4549. {
  4550. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  4551. // Ok, I want this one
  4552. $aExtKeys[$sAttCode] = $oAttDef;
  4553. }
  4554. }
  4555. if (count($aExtKeys) != 0)
  4556. {
  4557. $aResult[$sSomeClass] = $aExtKeys;
  4558. }
  4559. }
  4560. return $aResult;
  4561. }
  4562. /**
  4563. * It is not recommended to use this function: call GetLinkClasses instead
  4564. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  4565. * The only difference with EnumLinkingClasses is the output format
  4566. */
  4567. public static function EnumLinksClasses()
  4568. {
  4569. // Returns a flat array of classes having at least two external keys
  4570. $aResult = array();
  4571. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4572. {
  4573. $iExtKeyCount = 0;
  4574. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4575. {
  4576. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4577. if ($oAttDef->IsExternalKey())
  4578. {
  4579. $iExtKeyCount++;
  4580. }
  4581. }
  4582. if ($iExtKeyCount >= 2)
  4583. {
  4584. $aResult[] = $sSomeClass;
  4585. }
  4586. }
  4587. return $aResult;
  4588. }
  4589. /**
  4590. * It is not recommended to use this function: call GetLinkClasses instead
  4591. * Return classes having at least to external keys (thus too many classes as compared to GetLinkClasses)
  4592. * The only difference with EnumLinksClasses is the output format
  4593. */
  4594. public static function EnumLinkingClasses($sClass = "")
  4595. {
  4596. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  4597. $aResult = array();
  4598. foreach (self::EnumLinksClasses() as $sSomeClass)
  4599. {
  4600. $aTargets = array();
  4601. $bFoundClass = false;
  4602. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  4603. {
  4604. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4605. if ($oAttDef->IsExternalKey())
  4606. {
  4607. $sRemoteClass = $oAttDef->GetTargetClass();
  4608. if (empty($sClass))
  4609. {
  4610. $aTargets[$sAttCode] = $sRemoteClass;
  4611. }
  4612. elseif ($sClass == $sRemoteClass)
  4613. {
  4614. $bFoundClass = true;
  4615. }
  4616. else
  4617. {
  4618. $aTargets[$sAttCode] = $sRemoteClass;
  4619. }
  4620. }
  4621. }
  4622. if (empty($sClass) || $bFoundClass)
  4623. {
  4624. $aResult[$sSomeClass] = $aTargets;
  4625. }
  4626. }
  4627. return $aResult;
  4628. }
  4629. /**
  4630. * This function has two siblings that will be soon deprecated:
  4631. * EnumLinkingClasses and EnumLinkClasses
  4632. *
  4633. * Using GetLinkClasses is the recommended way to determine if a class is
  4634. * actually an N-N relation because it is based on the decision made by the
  4635. * designer the data model
  4636. */
  4637. public static function GetLinkClasses()
  4638. {
  4639. $aRet = array();
  4640. foreach(self::GetClasses() as $sClass)
  4641. {
  4642. if (isset(self::$m_aClassParams[$sClass]["is_link"]))
  4643. {
  4644. if (self::$m_aClassParams[$sClass]["is_link"])
  4645. {
  4646. $aExtKeys = array();
  4647. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  4648. {
  4649. if ($oAttDef->IsExternalKey())
  4650. {
  4651. $aExtKeys[$sAttCode] = $oAttDef->GetTargetClass();
  4652. }
  4653. }
  4654. $aRet[$sClass] = $aExtKeys;
  4655. }
  4656. }
  4657. }
  4658. return $aRet;
  4659. }
  4660. public static function GetLinkLabel($sLinkClass, $sAttCode)
  4661. {
  4662. self::_check_subclass($sLinkClass);
  4663. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  4664. return self::GetLabel($sLinkClass, $sAttCode);
  4665. }
  4666. /**
  4667. * Replaces all the parameters by the values passed in the hash array
  4668. */
  4669. static public function ApplyParams($sInput, $aParams)
  4670. {
  4671. // Declare magic parameters
  4672. $aParams['APP_URL'] = utils::GetAbsoluteUrlAppRoot();
  4673. $aParams['MODULES_URL'] = utils::GetAbsoluteUrlModulesRoot();
  4674. $aSearches = array();
  4675. $aReplacements = array();
  4676. foreach($aParams as $sSearch => $replace)
  4677. {
  4678. // Some environment parameters are objects, we just need scalars
  4679. if (is_object($replace))
  4680. {
  4681. $iPos = strpos($sSearch, '->object()');
  4682. if ($iPos !== false)
  4683. {
  4684. // Expand the parameters for the object
  4685. $sName = substr($sSearch, 0, $iPos);
  4686. if (preg_match_all('/\\$'.$sName.'-(>|&gt;)([^\\$]+)\\$/', $sInput, $aMatches)) // Support both syntaxes: $this->xxx$ or $this-&gt;xxx$ for HTML compatibility
  4687. {
  4688. foreach($aMatches[2] as $idx => $sPlaceholderAttCode)
  4689. {
  4690. try
  4691. {
  4692. $sReplacement = $replace->GetForTemplate($sPlaceholderAttCode);
  4693. if ($sReplacement !== null)
  4694. {
  4695. $aReplacements[] = $sReplacement;
  4696. $aSearches[] = '$'.$sName.'-'.$aMatches[1][$idx].$sPlaceholderAttCode.'$';
  4697. }
  4698. }
  4699. catch(Exception $e)
  4700. {
  4701. // No replacement will occur
  4702. }
  4703. }
  4704. }
  4705. }
  4706. else
  4707. {
  4708. continue; // Ignore this non-scalar value
  4709. }
  4710. }
  4711. else
  4712. {
  4713. $aSearches[] = '$'.$sSearch.'$';
  4714. $aReplacements[] = (string) $replace;
  4715. }
  4716. }
  4717. return str_replace($aSearches, $aReplacements, $sInput);
  4718. }
  4719. /**
  4720. * Returns an array of classes=>instance implementing the given interface
  4721. */
  4722. public static function EnumPlugins($sInterface)
  4723. {
  4724. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4725. {
  4726. return self::$m_aExtensionClasses[$sInterface];
  4727. }
  4728. else
  4729. {
  4730. return array();
  4731. }
  4732. }
  4733. /**
  4734. * Returns the instance of the specified plug-ins for the given interface
  4735. */
  4736. public static function GetPlugins($sInterface, $sClassName)
  4737. {
  4738. $oInstance = null;
  4739. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4740. {
  4741. if (array_key_exists($sClassName, self::$m_aExtensionClasses[$sInterface]))
  4742. {
  4743. return self::$m_aExtensionClasses[$sInterface][$sClassName];
  4744. }
  4745. }
  4746. return $oInstance;
  4747. }
  4748. public static function GetCacheEntries($sEnvironment = null)
  4749. {
  4750. if (!function_exists('apc_cache_info')) return array();
  4751. if (is_null($sEnvironment))
  4752. {
  4753. $sEnvironment = MetaModel::GetEnvironmentId();
  4754. }
  4755. $aEntries = array();
  4756. if (extension_loaded('apcu'))
  4757. {
  4758. // Beware: APCu behaves slightly differently from APC !!
  4759. $aCacheUserData = @apc_cache_info();
  4760. }
  4761. else
  4762. {
  4763. $aCacheUserData = @apc_cache_info('user');
  4764. }
  4765. if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list']))
  4766. {
  4767. $sPrefix = 'itop-'.$sEnvironment.'-';
  4768. foreach($aCacheUserData['cache_list'] as $i => $aEntry)
  4769. {
  4770. $sEntryKey = array_key_exists('info', $aEntry) ? $aEntry['info'] : $aEntry['key'];
  4771. if (strpos($sEntryKey, $sPrefix) === 0)
  4772. {
  4773. $sCleanKey = substr($sEntryKey, strlen($sPrefix));
  4774. $aEntries[$sCleanKey] = $aEntry;
  4775. $aEntries[$sCleanKey]['info'] = $sEntryKey;
  4776. }
  4777. }
  4778. }
  4779. return $aEntries;
  4780. }
  4781. public static function ResetCache($sEnvironmentId = null)
  4782. {
  4783. if (!function_exists('apc_delete')) return;
  4784. if (is_null($sEnvironmentId))
  4785. {
  4786. $sEnvironmentId = MetaModel::GetEnvironmentId();
  4787. }
  4788. $sAppIdentity = 'itop-'.$sEnvironmentId;
  4789. Dict::ResetCache($sAppIdentity);
  4790. foreach(self::GetCacheEntries($sEnvironmentId) as $sKey => $aAPCInfo)
  4791. {
  4792. $sAPCKey = $aAPCInfo['info'];
  4793. apc_delete($sAPCKey);
  4794. }
  4795. }
  4796. /**
  4797. * Given a field spec, get the most relevant (unique) representation
  4798. * Examples for a user request:
  4799. * - friendlyname => ref
  4800. * - org_name => org_id->name
  4801. * - org_id_friendlyname => org_id=>name
  4802. * - caller_name => caller_id->name
  4803. * - caller_id_friendlyname => caller_id->friendlyname
  4804. * @param string $sClass
  4805. * @param string $sField
  4806. * @return string
  4807. */
  4808. public static function NormalizeFieldSpec($sClass, $sField)
  4809. {
  4810. $sRet = $sField;
  4811. if ($sField == 'id')
  4812. {
  4813. $sRet = 'id';
  4814. }
  4815. elseif ($sField == 'friendlyname')
  4816. {
  4817. $sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sClass);
  4818. if (!is_null($sFriendlyNameAttCode))
  4819. {
  4820. // The friendly name is made of a single attribute
  4821. $sRet = $sFriendlyNameAttCode;
  4822. }
  4823. }
  4824. else
  4825. {
  4826. $oAttDef = static::GetAttributeDef($sClass, $sField);
  4827. if ($oAttDef->IsExternalField())
  4828. {
  4829. if ($oAttDef->IsFriendlyName())
  4830. {
  4831. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $oAttDef->GetKeyAttCode());
  4832. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  4833. $sFriendlyNameAttCode = static::GetFriendlyNameAttributeCode($sRemoteClass);
  4834. if (is_null($sFriendlyNameAttCode))
  4835. {
  4836. // The friendly name is made of several attributes
  4837. $sRet = $oAttDef->GetKeyAttCode().'->friendlyname';
  4838. }
  4839. else
  4840. {
  4841. // The friendly name is made of a single attribute
  4842. $sRet = $oAttDef->GetKeyAttCode().'->'.$sFriendlyNameAttCode;
  4843. }
  4844. }
  4845. else
  4846. {
  4847. $sRet = $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode();
  4848. }
  4849. }
  4850. }
  4851. return $sRet;
  4852. }
  4853. } // class MetaModel
  4854. // Standard attribute lists
  4855. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  4856. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  4857. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  4858. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  4859. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  4860. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));