metamodel.class.php 176 KB

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