metamodel.class.php 180 KB

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