metamodel.class.php 177 KB

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