metamodel.class.php 180 KB

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