metamodel.class.php 177 KB

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