metamodel.class.php 173 KB

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