attributedef.class.inc.php 164 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922
  1. <?php
  2. // Copyright (C) 2010-2015 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. * Typology for the attributes
  20. *
  21. * @copyright Copyright (C) 2010-2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('MyHelpers.class.inc.php');
  25. require_once('ormdocument.class.inc.php');
  26. require_once('ormstopwatch.class.inc.php');
  27. require_once('ormpassword.class.inc.php');
  28. require_once('ormcaselog.class.inc.php');
  29. /**
  30. * MissingColumnException - sent if an attribute is being created but the column is missing in the row
  31. *
  32. * @package iTopORM
  33. */
  34. class MissingColumnException extends Exception
  35. {}
  36. /**
  37. * add some description here...
  38. *
  39. * @package iTopORM
  40. */
  41. define('EXTKEY_RELATIVE', 1);
  42. /**
  43. * add some description here...
  44. *
  45. * @package iTopORM
  46. */
  47. define('EXTKEY_ABSOLUTE', 2);
  48. /**
  49. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  50. *
  51. * @package iTopORM
  52. */
  53. define('DEL_MANUAL', 1);
  54. /**
  55. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  56. *
  57. * @package iTopORM
  58. */
  59. define('DEL_AUTO', 2);
  60. /**
  61. * Fully silent delete... not yet implemented
  62. */
  63. define('DEL_SILENT', 2);
  64. /**
  65. * For HierarchicalKeys only: move all the children up one level automatically
  66. */
  67. define('DEL_MOVEUP', 3);
  68. /**
  69. * For Link sets: tracking_level
  70. *
  71. * @package iTopORM
  72. */
  73. define('ATTRIBUTE_TRACKING_NONE', 0); // Do not track changes of the attribute
  74. define('ATTRIBUTE_TRACKING_ALL', 3); // Do track all changes of the attribute
  75. define('LINKSET_TRACKING_NONE', 0); // Do not track changes in the link set
  76. define('LINKSET_TRACKING_LIST', 1); // Do track added/removed items
  77. define('LINKSET_TRACKING_DETAILS', 2); // Do track modified items
  78. define('LINKSET_TRACKING_ALL', 3); // Do track added/removed/modified items
  79. define('LINKSET_EDITMODE_NONE', 0); // The linkset cannot be edited at all from inside this object
  80. define('LINKSET_EDITMODE_ADDONLY', 1); // The only possible action is to open a new window to create a new object
  81. define('LINKSET_EDITMODE_ACTIONS', 2); // Show the usual 'Actions' popup menu
  82. define('LINKSET_EDITMODE_INPLACE', 3); // The "linked" objects can be created/modified/deleted in place
  83. define('LINKSET_EDITMODE_ADDREMOVE', 4); // The "linked" objects can be added/removed in place
  84. /**
  85. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  86. *
  87. * @package iTopORM
  88. */
  89. abstract class AttributeDefinition
  90. {
  91. public function GetType()
  92. {
  93. return Dict::S('Core:'.get_class($this));
  94. }
  95. public function GetTypeDesc()
  96. {
  97. return Dict::S('Core:'.get_class($this).'+');
  98. }
  99. abstract public function GetEditClass();
  100. protected $m_sCode;
  101. private $m_aParams = array();
  102. protected $m_sHostClass = '!undefined!';
  103. public function Get($sParamName) {return $this->m_aParams[$sParamName];}
  104. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  105. protected function GetOptional($sParamName, $default)
  106. {
  107. if (array_key_exists($sParamName, $this->m_aParams))
  108. {
  109. return $this->m_aParams[$sParamName];
  110. }
  111. else
  112. {
  113. return $default;
  114. }
  115. }
  116. public function __construct($sCode, $aParams)
  117. {
  118. $this->m_sCode = $sCode;
  119. $this->m_aParams = $aParams;
  120. $this->ConsistencyCheck();
  121. }
  122. public function GetParams()
  123. {
  124. return $this->m_aParams;
  125. }
  126. public function SetHostClass($sHostClass)
  127. {
  128. $this->m_sHostClass = $sHostClass;
  129. }
  130. public function GetHostClass()
  131. {
  132. return $this->m_sHostClass;
  133. }
  134. public function ListSubItems()
  135. {
  136. $aSubItems = array();
  137. foreach(MetaModel::ListAttributeDefs($this->m_sHostClass) as $sAttCode => $oAttDef)
  138. {
  139. if ($oAttDef instanceof AttributeSubItem)
  140. {
  141. if ($oAttDef->Get('target_attcode') == $this->m_sCode)
  142. {
  143. $aSubItems[$sAttCode] = $oAttDef;
  144. }
  145. }
  146. }
  147. return $aSubItems;
  148. }
  149. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  150. // to be overloaded
  151. static public function ListExpectedParams()
  152. {
  153. return array();
  154. }
  155. private function ConsistencyCheck()
  156. {
  157. // Check that any mandatory param has been specified
  158. //
  159. $aExpectedParams = $this->ListExpectedParams();
  160. foreach($aExpectedParams as $sParamName)
  161. {
  162. if (!array_key_exists($sParamName, $this->m_aParams))
  163. {
  164. $aBacktrace = debug_backtrace();
  165. $sTargetClass = $aBacktrace[2]["class"];
  166. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  167. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  168. }
  169. }
  170. }
  171. // table, key field, name field
  172. public function ListDBJoins()
  173. {
  174. return "";
  175. // e.g: return array("Site", "infrid", "name");
  176. }
  177. public function GetFinalAttDef()
  178. {
  179. return $this;
  180. }
  181. public function IsDirectField() {return false;}
  182. public function IsScalar() {return false;}
  183. public function IsLinkSet() {return false;}
  184. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  185. public function IsHierarchicalKey() {return false;}
  186. public function IsExternalField() {return false;}
  187. public function IsWritable() {return false;}
  188. public function LoadInObject() {return true;}
  189. public function AlwaysLoadInTables() {return $this->GetOptional('always_load_in_tables', false);}
  190. public function GetValue($oHostObject){return null;} // must return the value if LoadInObject returns false
  191. public function IsNullAllowed() {return true;}
  192. public function GetCode() {return $this->m_sCode;}
  193. public function GetMirrorLinkAttribute() {return null;}
  194. /**
  195. * Helper to browse the hierarchy of classes, searching for a label
  196. */
  197. protected function SearchLabel($sDictEntrySuffix, $sDefault, $bUserLanguageOnly)
  198. {
  199. $sLabel = Dict::S('Class:'.$this->m_sHostClass.$sDictEntrySuffix, '', $bUserLanguageOnly);
  200. if (strlen($sLabel) == 0)
  201. {
  202. // Nothing found: go higher in the hierarchy (if possible)
  203. //
  204. $sLabel = $sDefault;
  205. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  206. if ($sParentClass)
  207. {
  208. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  209. {
  210. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  211. $sLabel = $oAttDef->SearchLabel($sDictEntrySuffix, $sDefault, $bUserLanguageOnly);
  212. }
  213. }
  214. }
  215. return $sLabel;
  216. }
  217. public function GetLabel($sDefault = null)
  218. {
  219. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode, null, true /*user lang*/);
  220. if (is_null($sLabel))
  221. {
  222. // If no default value is specified, let's define the most relevant one for developping purposes
  223. if (is_null($sDefault))
  224. {
  225. $sDefault = str_replace('_', ' ', $this->m_sCode);
  226. }
  227. // Browse the hierarchy again, accepting default (english) translations
  228. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode, $sDefault, false);
  229. }
  230. return $sLabel;
  231. }
  232. /**
  233. * Get the label corresponding to the given value (in plain text)
  234. * To be overloaded for localized enums
  235. */
  236. public function GetValueLabel($sValue)
  237. {
  238. return $sValue;
  239. }
  240. /**
  241. * Get the value from a given string (plain text, CSV import)
  242. * Return null if no match could be found
  243. */
  244. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  245. {
  246. return $this->MakeRealValue($sProposedValue, null);
  247. }
  248. public function GetLabel_Obsolete()
  249. {
  250. // Written for compatibility with a data model written prior to version 0.9.1
  251. if (array_key_exists('label', $this->m_aParams))
  252. {
  253. return $this->m_aParams['label'];
  254. }
  255. else
  256. {
  257. return $this->GetLabel();
  258. }
  259. }
  260. public function GetDescription($sDefault = null)
  261. {
  262. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'+', null, true /*user lang*/);
  263. if (is_null($sLabel))
  264. {
  265. // If no default value is specified, let's define the most relevant one for developping purposes
  266. if (is_null($sDefault))
  267. {
  268. $sDefault = '';
  269. }
  270. // Browse the hierarchy again, accepting default (english) translations
  271. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'+', $sDefault, false);
  272. }
  273. return $sLabel;
  274. }
  275. public function GetHelpOnEdition($sDefault = null)
  276. {
  277. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'?', null, true /*user lang*/);
  278. if (is_null($sLabel))
  279. {
  280. // If no default value is specified, let's define the most relevant one for developping purposes
  281. if (is_null($sDefault))
  282. {
  283. $sDefault = '';
  284. }
  285. // Browse the hierarchy again, accepting default (english) translations
  286. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'?', $sDefault, false);
  287. }
  288. return $sLabel;
  289. }
  290. public function GetHelpOnSmartSearch()
  291. {
  292. $aParents = array_merge(array(get_class($this) => get_class($this)), class_parents($this));
  293. foreach ($aParents as $sClass)
  294. {
  295. $sHelp = Dict::S("Core:$sClass?SmartSearch", '-missing-');
  296. if ($sHelp != '-missing-')
  297. {
  298. return $sHelp;
  299. }
  300. }
  301. return '';
  302. }
  303. public function GetDescription_Obsolete()
  304. {
  305. // Written for compatibility with a data model written prior to version 0.9.1
  306. if (array_key_exists('description', $this->m_aParams))
  307. {
  308. return $this->m_aParams['description'];
  309. }
  310. else
  311. {
  312. return $this->GetDescription();
  313. }
  314. }
  315. public function GetTrackingLevel()
  316. {
  317. return $this->GetOptional('tracking_level', ATTRIBUTE_TRACKING_ALL);
  318. }
  319. public function GetValuesDef() {return null;}
  320. public function GetPrerequisiteAttributes() {return array();}
  321. public function GetNullValue() {return null;}
  322. public function IsNull($proposedValue) {return is_null($proposedValue);}
  323. public function MakeRealValue($proposedValue, $oHostObj) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  324. public function Equals($val1, $val2) {return ($val1 == $val2);}
  325. public function GetSQLExpressions($sPrefix = '') {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  326. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  327. public function GetSQLColumns($bFullSpec = false) {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  328. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  329. public function RequiresIndex() {return false;}
  330. public function GetOrderBySQLExpressions($sClassAlias)
  331. {
  332. // Note: This is the responsibility of this function to place backticks around column aliases
  333. return array('`'.$sClassAlias.$this->GetCode().'`');
  334. }
  335. public function GetOrderByHint()
  336. {
  337. return '';
  338. }
  339. // Import - differs slightly from SQL input, but identical in most cases
  340. //
  341. public function GetImportColumns() {return $this->GetSQLColumns();}
  342. public function FromImportToValue($aCols, $sPrefix = '')
  343. {
  344. $aValues = array();
  345. foreach ($this->GetSQLExpressions($sPrefix) as $sAlias => $sExpr)
  346. {
  347. // This is working, based on the assumption that importable fields
  348. // are not computed fields => the expression is the name of a column
  349. $aValues[$sPrefix.$sAlias] = $aCols[$sExpr];
  350. }
  351. return $this->FromSQLToValue($aValues, $sPrefix);
  352. }
  353. public function GetValidationPattern()
  354. {
  355. return '';
  356. }
  357. public function CheckFormat($value)
  358. {
  359. return true;
  360. }
  361. public function GetMaxSize()
  362. {
  363. return null;
  364. }
  365. public function MakeValue()
  366. {
  367. $sComputeFunc = $this->Get("compute_func");
  368. if (empty($sComputeFunc)) return null;
  369. return call_user_func($sComputeFunc);
  370. }
  371. abstract public function GetDefaultValue();
  372. //
  373. // To be overloaded in subclasses
  374. //
  375. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  376. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  377. //abstract protected GetBasicFilterHTMLInput();
  378. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  379. public function GetFilterDefinitions()
  380. {
  381. return array();
  382. }
  383. public function GetEditValue($sValue, $oHostObj = null)
  384. {
  385. return (string)$sValue;
  386. }
  387. /**
  388. * Helper to get a value that will be JSON encoded
  389. * The operation is the opposite to FromJSONToValue
  390. */
  391. public function GetForJSON($value)
  392. {
  393. // In most of the cases, that will be the expected behavior...
  394. return $this->GetEditValue($value);
  395. }
  396. /**
  397. * Helper to form a value, given JSON decoded data
  398. * The operation is the opposite to GetForJSON
  399. */
  400. public function FromJSONToValue($json)
  401. {
  402. // Passthrough in most of the cases
  403. return $json;
  404. }
  405. /**
  406. * Override to display the value in the GUI
  407. */
  408. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  409. {
  410. return Str::pure2html((string)$sValue);
  411. }
  412. /**
  413. * Override to export the value in XML
  414. */
  415. public function GetAsXML($sValue, $oHostObject = null, $bLocalize = true)
  416. {
  417. return Str::pure2xml((string)$sValue);
  418. }
  419. /**
  420. * Override to escape the value when read by DBObject::GetAsCSV()
  421. */
  422. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  423. {
  424. return (string)$sValue;
  425. }
  426. /**
  427. * Override to differentiate a value displayed in the UI or in the history
  428. */
  429. public function GetAsHTMLForHistory($sValue, $oHostObject = null, $bLocalize = true)
  430. {
  431. return $this->GetAsHTML($sValue, $oHostObject, $bLocalize);
  432. }
  433. /**
  434. * List the available verbs for 'GetForTemplate'
  435. */
  436. public static function EnumTemplateVerbs()
  437. {
  438. return array(
  439. '' => 'Plain text (unlocalized) representation',
  440. 'html' => 'HTML representation',
  441. 'label' => 'Localized representation',
  442. );
  443. }
  444. /**
  445. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  446. * @param $value mixed The current value of the field
  447. * @param $sVerb string The verb specifying the representation of the value
  448. * @param $oHostObject DBObject The object
  449. * @param $bLocalize bool Whether or not to localize the value
  450. */
  451. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  452. {
  453. if ($this->IsScalar())
  454. {
  455. switch ($sVerb)
  456. {
  457. case '':
  458. return $value;
  459. case 'html':
  460. return $this->GetAsHtml($value, $oHostObject, $bLocalize);
  461. case 'label':
  462. return $this->GetEditValue($value);
  463. default:
  464. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObj));
  465. }
  466. }
  467. return null;
  468. }
  469. public function GetAllowedValues($aArgs = array(), $sContains = '')
  470. {
  471. $oValSetDef = $this->GetValuesDef();
  472. if (!$oValSetDef) return null;
  473. return $oValSetDef->GetValues($aArgs, $sContains);
  474. }
  475. /**
  476. * Explain the change of the attribute (history)
  477. */
  478. public function DescribeChangeAsHTML($sOldValue, $sNewValue, $sLabel = null)
  479. {
  480. if (is_null($sLabel))
  481. {
  482. $sLabel = $this->GetLabel();
  483. }
  484. $sNewValueHtml = $this->GetAsHTMLForHistory($sNewValue);
  485. $sOldValueHtml = $this->GetAsHTMLForHistory($sOldValue);
  486. if($this->IsExternalKey())
  487. {
  488. $sTargetClass = $this->GetTargetClass();
  489. $sOldValueHtml = (int)$sOldValue ? MetaModel::GetHyperLink($sTargetClass, (int)$sOldValue) : null;
  490. $sNewValueHtml = (int)$sNewValue ? MetaModel::GetHyperLink($sTargetClass, (int)$sNewValue) : null;
  491. }
  492. if ( (($this->GetType() == 'String') || ($this->GetType() == 'Text')) &&
  493. (strlen($sNewValue) > strlen($sOldValue)) )
  494. {
  495. // Check if some text was not appended to the field
  496. if (substr($sNewValue,0, strlen($sOldValue)) == $sOldValue) // Text added at the end
  497. {
  498. $sDelta = $this->GetAsHTML(substr($sNewValue, strlen($sOldValue)));
  499. $sResult = Dict::Format('Change:Text_AppendedTo_AttName', $sDelta, $sLabel);
  500. }
  501. else if (substr($sNewValue, -strlen($sOldValue)) == $sOldValue) // Text added at the beginning
  502. {
  503. $sDelta = $this->GetAsHTML(substr($sNewValue, 0, strlen($sNewValue) - strlen($sOldValue)));
  504. $sResult = Dict::Format('Change:Text_AppendedTo_AttName', $sDelta, $sLabel);
  505. }
  506. else
  507. {
  508. if (strlen($sOldValue) == 0)
  509. {
  510. $sResult = Dict::Format('Change:AttName_SetTo', $sLabel, $sNewValueHtml);
  511. }
  512. else
  513. {
  514. if (is_null($sNewValue))
  515. {
  516. $sNewValueHtml = Dict::S('UI:UndefinedObject');
  517. }
  518. $sResult = Dict::Format('Change:AttName_SetTo_NewValue_PreviousValue_OldValue', $sLabel, $sNewValueHtml, $sOldValueHtml);
  519. }
  520. }
  521. }
  522. else
  523. {
  524. if (strlen($sOldValue) == 0)
  525. {
  526. $sResult = Dict::Format('Change:AttName_SetTo', $sLabel, $sNewValueHtml);
  527. }
  528. else
  529. {
  530. if (is_null($sNewValue))
  531. {
  532. $sNewValueHtml = Dict::S('UI:UndefinedObject');
  533. }
  534. $sResult = Dict::Format('Change:AttName_SetTo_NewValue_PreviousValue_OldValue', $sLabel, $sNewValueHtml, $sOldValueHtml);
  535. }
  536. }
  537. return $sResult;
  538. }
  539. /**
  540. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  541. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  542. * does nothing special, and just calls the default (loose) operator
  543. * @param string $sSearchText The search string to analyze for smart patterns
  544. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  545. * @param Hash $aParams Values of the query parameters
  546. * @return Expression The search condition to be added (AND) to the current search
  547. */
  548. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  549. {
  550. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  551. $oRightExpr = new VariableExpression($sParamName);
  552. $sOperator = $this->GetBasicFilterLooseOperator();
  553. switch ($sOperator)
  554. {
  555. case 'Contains':
  556. $aParams[$sParamName] = "%$sSearchText%";
  557. $sSQLOperator = 'LIKE';
  558. break;
  559. default:
  560. $sSQLOperator = $sOperator;
  561. $aParams[$sParamName] = $sSearchText;
  562. }
  563. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  564. return $oNewCondition;
  565. }
  566. /**
  567. * Tells if an attribute is part of the unique fingerprint of the object (used for comparing two objects)
  568. * All attributes which value is not based on a value from the object itself (like ExternalFields or LinkedSet)
  569. * must be excluded from the object's signature
  570. * @return boolean
  571. */
  572. public function IsPartOfFingerprint()
  573. {
  574. return true;
  575. }
  576. /**
  577. * The part of the current attribute in the object's signature, for the supplied value
  578. * @param unknown $value The value of this attribute for the object
  579. * @return string The "signature" for this field/attribute
  580. */
  581. public function Fingerprint($value)
  582. {
  583. return (string)$value;
  584. }
  585. }
  586. /**
  587. * Set of objects directly linked to an object, and being part of its definition
  588. *
  589. * @package iTopORM
  590. */
  591. class AttributeLinkedSet extends AttributeDefinition
  592. {
  593. static public function ListExpectedParams()
  594. {
  595. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  596. }
  597. public function GetEditClass() {return "LinkedSet";}
  598. public function IsWritable() {return true;}
  599. public function IsLinkSet() {return true;}
  600. public function IsIndirect() {return false;}
  601. public function GetValuesDef() {return $this->Get("allowed_values");}
  602. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  603. public function GetDefaultValue($aArgs = array())
  604. {
  605. // Note: so far, this feature is a prototype,
  606. // later, the argument 'this' should always be present in the arguments
  607. //
  608. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  609. {
  610. $aValues = $this->Get('default_value')->GetValues($aArgs);
  611. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  612. return $oSet;
  613. }
  614. else
  615. {
  616. return DBObjectSet::FromScratch($this->Get('linked_class'));
  617. }
  618. }
  619. public function GetTrackingLevel()
  620. {
  621. return $this->GetOptional('tracking_level', MetaModel::GetConfig()->Get('tracking_level_linked_set_default'));
  622. }
  623. public function GetEditMode()
  624. {
  625. return $this->GetOptional('edit_mode', LINKSET_EDITMODE_ACTIONS);
  626. }
  627. public function GetLinkedClass() {return $this->Get('linked_class');}
  628. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  629. public function GetBasicFilterOperators() {return array();}
  630. public function GetBasicFilterLooseOperator() {return '';}
  631. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  632. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  633. {
  634. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  635. {
  636. $sValue->Rewind();
  637. $aItems = array();
  638. while ($oObj = $sValue->Fetch())
  639. {
  640. // Show only relevant information (hide the external key to the current object)
  641. $aAttributes = array();
  642. foreach(MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef)
  643. {
  644. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  645. if ($oAttDef->IsExternalField()) continue;
  646. $sAttValue = $oObj->GetAsHTML($sAttCode);
  647. if (strlen($sAttValue) > 0)
  648. {
  649. $aAttributes[] = $sAttValue;
  650. }
  651. }
  652. $sAttributes = implode(', ', $aAttributes);
  653. $aItems[] = $sAttributes;
  654. }
  655. return implode('<br/>', $aItems);
  656. }
  657. return null;
  658. }
  659. public function GetAsXML($sValue, $oHostObject = null, $bLocalize = true)
  660. {
  661. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  662. {
  663. $sValue->Rewind();
  664. $sRes = "<Set>\n";
  665. while ($oObj = $sValue->Fetch())
  666. {
  667. $sObjClass = get_class($oObj);
  668. $sRes .= "<$sObjClass id=\"".$oObj->GetKey()."\">\n";
  669. // Show only relevant information (hide the external key to the current object)
  670. $aAttributes = array();
  671. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  672. {
  673. if ($sAttCode == 'finalclass')
  674. {
  675. if ($sObjClass == $this->GetLinkedClass())
  676. {
  677. // Simplify the output if the exact class could be determined implicitely
  678. continue;
  679. }
  680. }
  681. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  682. if ($oAttDef->IsExternalField() && ($oAttDef->GetKeyAttCode() == $this->GetExtKeyToMe())) continue;
  683. if (($oAttDef instanceof AttributeFriendlyName) && ($oAttDef->GetKeyAttCode() == $this->GetExtKeyToMe())) continue;
  684. if (($oAttDef instanceof AttributeFriendlyName) && ($oAttDef->GetKeyAttCode() == 'id')) continue;
  685. if (!$oAttDef->IsScalar()) continue;
  686. $sAttValue = $oObj->GetAsXML($sAttCode, $bLocalize);
  687. $sRes .= "<$sAttCode>$sAttValue</$sAttCode>\n";
  688. }
  689. $sRes .= "</$sObjClass>\n";
  690. }
  691. $sRes .= "</Set>\n";
  692. }
  693. else
  694. {
  695. $sRes = '';
  696. }
  697. return $sRes;
  698. }
  699. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  700. {
  701. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  702. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  703. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  704. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  705. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  706. {
  707. $sValue->Rewind();
  708. $aItems = array();
  709. while ($oObj = $sValue->Fetch())
  710. {
  711. $sObjClass = get_class($oObj);
  712. // Show only relevant information (hide the external key to the current object)
  713. $aAttributes = array();
  714. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  715. {
  716. if ($sAttCode == 'finalclass')
  717. {
  718. if ($sObjClass == $this->GetLinkedClass())
  719. {
  720. // Simplify the output if the exact class could be determined implicitely
  721. continue;
  722. }
  723. }
  724. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  725. if ($oAttDef->IsExternalField()) continue;
  726. if (!$oAttDef->IsDirectField()) continue;
  727. if (!$oAttDef->IsScalar()) continue;
  728. $sAttValue = $oObj->GetAsCSV($sAttCode, $sSepValue, '', $bLocalize);
  729. if (strlen($sAttValue) > 0)
  730. {
  731. $sAttributeData = str_replace($sAttributeQualifier, $sAttributeQualifier.$sAttributeQualifier, $sAttCode.$sSepValue.$sAttValue);
  732. $aAttributes[] = $sAttributeQualifier.$sAttributeData.$sAttributeQualifier;
  733. }
  734. }
  735. $sAttributes = implode($sSepAttribute, $aAttributes);
  736. $aItems[] = $sAttributes;
  737. }
  738. $sRes = implode($sSepItem, $aItems);
  739. }
  740. else
  741. {
  742. $sRes = '';
  743. }
  744. $sRes = str_replace($sTextQualifier, $sTextQualifier.$sTextQualifier, $sRes);
  745. $sRes = $sTextQualifier.$sRes.$sTextQualifier;
  746. return $sRes;
  747. }
  748. /**
  749. * List the available verbs for 'GetForTemplate'
  750. */
  751. public static function EnumTemplateVerbs()
  752. {
  753. return array(
  754. '' => 'Plain text (unlocalized) representation',
  755. 'html' => 'HTML representation (unordered list)',
  756. );
  757. }
  758. /**
  759. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  760. * @param $value mixed The current value of the field
  761. * @param $sVerb string The verb specifying the representation of the value
  762. * @param $oHostObject DBObject The object
  763. * @param $bLocalize bool Whether or not to localize the value
  764. */
  765. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  766. {
  767. $sRemoteName = $this->IsIndirect() ? $this->GetExtKeyToRemote().'_friendlyname' : 'friendlyname';
  768. $oLinkSet = clone $value; // Workaround/Safety net for Trac #887
  769. $iLimit = MetaModel::GetConfig()->Get('max_linkset_output');
  770. if ($iLimit > 0)
  771. {
  772. $oLinkSet->SetLimit($iLimit);
  773. }
  774. $aNames = $oLinkSet->GetColumnAsArray($sRemoteName);
  775. if ($iLimit > 0)
  776. {
  777. $iTotal = $oLinkSet->Count();
  778. if ($iTotal > count($aNames))
  779. {
  780. $aNames[] = '... '.Dict::Format('UI:TruncatedResults', count($aNames), $iTotal);
  781. }
  782. }
  783. switch($sVerb)
  784. {
  785. case '':
  786. return implode("\n", $aNames);
  787. case 'html':
  788. return '<ul><li>'.implode("</li><li>", $aNames).'</li></ul>';
  789. default:
  790. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObj));
  791. }
  792. }
  793. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  794. public function GetImportColumns()
  795. {
  796. $aColumns = array();
  797. $aColumns[$this->GetCode()] = 'TEXT';
  798. return $aColumns;
  799. }
  800. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  801. {
  802. if (is_null($sSepItem) || empty($sSepItem))
  803. {
  804. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  805. }
  806. if (is_null($sSepAttribute) || empty($sSepAttribute))
  807. {
  808. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  809. }
  810. if (is_null($sSepValue) || empty($sSepValue))
  811. {
  812. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  813. }
  814. if (is_null($sAttributeQualifier) || empty($sAttributeQualifier))
  815. {
  816. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  817. }
  818. $sTargetClass = $this->Get('linked_class');
  819. $sInput = str_replace($sSepItem, "\n", $sProposedValue);
  820. $oCSVParser = new CSVParser($sInput, $sSepAttribute, $sAttributeQualifier);
  821. $aInput = $oCSVParser->ToArray(0 /* do not skip lines */);
  822. $aLinks = array();
  823. foreach($aInput as $aRow)
  824. {
  825. // 1st - get the values, split the extkey->searchkey specs, and eventually get the finalclass value
  826. $aExtKeys = array();
  827. $aValues = array();
  828. foreach($aRow as $sCell)
  829. {
  830. $iSepPos = strpos($sCell, $sSepValue);
  831. if ($iSepPos === false)
  832. {
  833. // Houston...
  834. throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell));
  835. }
  836. $sAttCode = trim(substr($sCell, 0, $iSepPos));
  837. $sValue = substr($sCell, $iSepPos + strlen($sSepValue));
  838. if (preg_match('/^(.+)->(.+)$/', $sAttCode, $aMatches))
  839. {
  840. $sKeyAttCode = $aMatches[1];
  841. $sRemoteAttCode = $aMatches[2];
  842. $aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue;
  843. if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode))
  844. {
  845. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sKeyAttCode));
  846. }
  847. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  848. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  849. if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode))
  850. {
  851. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode));
  852. }
  853. }
  854. else
  855. {
  856. if(!MetaModel::IsValidAttCode($sTargetClass, $sAttCode))
  857. {
  858. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sAttCode));
  859. }
  860. $oAttDef = MetaModel::GetAttributeDef($sTargetClass, $sAttCode);
  861. $aValues[$sAttCode] = $oAttDef->MakeValueFromString($sValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue, $sAttributeQualifier);
  862. }
  863. }
  864. // 2nd - Instanciate the object and set the value
  865. if (isset($aValues['finalclass']))
  866. {
  867. $sLinkClass = $aValues['finalclass'];
  868. if (!is_subclass_of($sLinkClass, $sTargetClass))
  869. {
  870. throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
  871. }
  872. }
  873. elseif (MetaModel::IsAbstract($sTargetClass))
  874. {
  875. throw new CoreException('Missing finalclass for link attribute specification');
  876. }
  877. else
  878. {
  879. $sLinkClass = $sTargetClass;
  880. }
  881. $oLink = MetaModel::NewObject($sLinkClass);
  882. foreach ($aValues as $sAttCode => $sValue)
  883. {
  884. $oLink->Set($sAttCode, $sValue);
  885. }
  886. // 3rd - Set external keys from search conditions
  887. foreach ($aExtKeys as $sKeyAttCode => $aReconciliation)
  888. {
  889. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  890. $sKeyClass = $oKeyAttDef->GetTargetClass();
  891. $oExtKeyFilter = new DBObjectSearch($sKeyClass);
  892. $aReconciliationDesc = array();
  893. foreach($aReconciliation as $sRemoteAttCode => $sValue)
  894. {
  895. $oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '=');
  896. $aReconciliationDesc[] = "$sRemoteAttCode=$sValue";
  897. }
  898. $oExtKeySet = new CMDBObjectSet($oExtKeyFilter);
  899. switch($oExtKeySet->Count())
  900. {
  901. case 0:
  902. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  903. throw new CoreException("Found no match", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  904. break;
  905. case 1:
  906. $oRemoteObj = $oExtKeySet->Fetch();
  907. $oLink->Set($sKeyAttCode, $oRemoteObj->GetKey());
  908. break;
  909. default:
  910. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  911. throw new CoreException("Found several matches", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  912. // Found several matches, ambiguous
  913. }
  914. }
  915. // Check (roughly) if such a link is valid
  916. $aErrors = array();
  917. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  918. {
  919. if ($oAttDef->IsExternalKey())
  920. {
  921. if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of($this->GetHostClass(), $oAttDef->GetTargetClass())))
  922. {
  923. continue; // Don't check the key to self
  924. }
  925. }
  926. if ($oAttDef->IsWritable() && $oAttDef->IsNull($oLink->Get($sAttCode)) && !$oAttDef->IsNullAllowed())
  927. {
  928. $aErrors[] = $sAttCode;
  929. }
  930. }
  931. if (count($aErrors) > 0)
  932. {
  933. throw new CoreException("Missing value for mandatory attribute(s): ".implode(', ', $aErrors));
  934. }
  935. $aLinks[] = $oLink;
  936. }
  937. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  938. return $oSet;
  939. }
  940. /**
  941. * Helper to get a value that will be JSON encoded
  942. * The operation is the opposite to FromJSONToValue
  943. */
  944. public function GetForJSON($value)
  945. {
  946. $aRet = array();
  947. if (is_object($value) && ($value instanceof DBObjectSet))
  948. {
  949. $value->Rewind();
  950. while ($oObj = $value->Fetch())
  951. {
  952. $sObjClass = get_class($oObj);
  953. // Show only relevant information (hide the external key to the current object)
  954. $aAttributes = array();
  955. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  956. {
  957. if ($sAttCode == 'finalclass')
  958. {
  959. if ($sObjClass == $this->GetLinkedClass())
  960. {
  961. // Simplify the output if the exact class could be determined implicitely
  962. continue;
  963. }
  964. }
  965. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  966. if ($oAttDef->IsExternalField()) continue;
  967. if (!$oAttDef->IsDirectField()) continue;
  968. if (!$oAttDef->IsScalar()) continue;
  969. $attValue = $oObj->Get($sAttCode);
  970. $aAttributes[$sAttCode] = $oAttDef->GetForJSON($attValue);
  971. }
  972. $aRet[] = $aAttributes;
  973. }
  974. }
  975. return $aRet;
  976. }
  977. /**
  978. * Helper to form a value, given JSON decoded data
  979. * The operation is the opposite to GetForJSON
  980. */
  981. public function FromJSONToValue($json)
  982. {
  983. $sTargetClass = $this->Get('linked_class');
  984. $aLinks = array();
  985. foreach($json as $aValues)
  986. {
  987. if (isset($aValues['finalclass']))
  988. {
  989. $sLinkClass = $aValues['finalclass'];
  990. if (!is_subclass_of($sLinkClass, $sTargetClass))
  991. {
  992. throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
  993. }
  994. }
  995. elseif (MetaModel::IsAbstract($sTargetClass))
  996. {
  997. throw new CoreException('Missing finalclass for link attribute specification');
  998. }
  999. else
  1000. {
  1001. $sLinkClass = $sTargetClass;
  1002. }
  1003. $oLink = MetaModel::NewObject($sLinkClass);
  1004. foreach ($aValues as $sAttCode => $sValue)
  1005. {
  1006. $oLink->Set($sAttCode, $sValue);
  1007. }
  1008. // Check (roughly) if such a link is valid
  1009. $aErrors = array();
  1010. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  1011. {
  1012. if ($oAttDef->IsExternalKey())
  1013. {
  1014. if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of($this->GetHostClass(), $oAttDef->GetTargetClass())))
  1015. {
  1016. continue; // Don't check the key to self
  1017. }
  1018. }
  1019. if ($oAttDef->IsWritable() && $oAttDef->IsNull($oLink->Get($sAttCode)) && !$oAttDef->IsNullAllowed())
  1020. {
  1021. $aErrors[] = $sAttCode;
  1022. }
  1023. }
  1024. if (count($aErrors) > 0)
  1025. {
  1026. throw new CoreException("Missing value for mandatory attribute(s): ".implode(', ', $aErrors));
  1027. }
  1028. $aLinks[] = $oLink;
  1029. }
  1030. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  1031. return $oSet;
  1032. }
  1033. public function Equals($val1, $val2)
  1034. {
  1035. if ($val1 === $val2) return true;
  1036. if (is_object($val1) != is_object($val2))
  1037. {
  1038. return false;
  1039. }
  1040. if (!is_object($val1))
  1041. {
  1042. // string ?
  1043. // todo = implement this case ?
  1044. return false;
  1045. }
  1046. // Note: maintain this algorithm so as to make sure it is strictly equivalent to the one used within DBObject::DBWriteLinks()
  1047. $sExtKeyToMe = $this->GetExtKeyToMe();
  1048. $sAdditionalKey = null;
  1049. if ($this->IsIndirect() && !$this->DuplicatesAllowed())
  1050. {
  1051. $sAdditionalKey = $this->GetExtKeyToRemote();
  1052. }
  1053. $oComparator = new DBObjectSetComparator($val1, $val2, array($sExtKeyToMe), $sAdditionalKey);
  1054. $aChanges = $oComparator->GetDifferences();
  1055. $bAreEquivalent = (count($aChanges['added']) == 0) && (count($aChanges['removed']) == 0) && (count($aChanges['modified']) == 0);
  1056. return $bAreEquivalent;
  1057. }
  1058. /**
  1059. * Find the corresponding "link" attribute on the target class
  1060. *
  1061. * @return string The attribute code on the target class, or null if none has been found
  1062. */
  1063. public function GetMirrorLinkAttribute()
  1064. {
  1065. $oRemoteAtt = MetaModel::GetAttributeDef($this->GetLinkedClass(), $this->GetExtKeyToMe());
  1066. return $oRemoteAtt;
  1067. }
  1068. public function IsPartOfFingerprint() { return false; }
  1069. }
  1070. /**
  1071. * Set of objects linked to an object (n-n), and being part of its definition
  1072. *
  1073. * @package iTopORM
  1074. */
  1075. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  1076. {
  1077. static public function ListExpectedParams()
  1078. {
  1079. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  1080. }
  1081. public function IsIndirect() {return true;}
  1082. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  1083. public function GetEditClass() {return "LinkedSet";}
  1084. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  1085. public function GetTrackingLevel()
  1086. {
  1087. return $this->GetOptional('tracking_level', MetaModel::GetConfig()->Get('tracking_level_linked_set_indirect_default'));
  1088. }
  1089. /**
  1090. * Find the corresponding "link" attribute on the target class
  1091. *
  1092. * @return string The attribute code on the target class, or null if none has been found
  1093. */
  1094. public function GetMirrorLinkAttribute()
  1095. {
  1096. $oRet = null;
  1097. $oExtKeyToRemote = MetaModel::GetAttributeDef($this->GetLinkedClass(), $this->GetExtKeyToRemote());
  1098. $sRemoteClass = $oExtKeyToRemote->GetTargetClass();
  1099. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  1100. {
  1101. if (!$oRemoteAttDef instanceof AttributeLinkedSetIndirect) continue;
  1102. if ($oRemoteAttDef->GetLinkedClass() != $this->GetLinkedClass()) continue;
  1103. if ($oRemoteAttDef->GetExtKeyToMe() != $this->GetExtKeyToRemote()) continue;
  1104. if ($oRemoteAttDef->GetExtKeyToRemote() != $this->GetExtKeyToMe()) continue;
  1105. $oRet = $oRemoteAttDef;
  1106. break;
  1107. }
  1108. return $oRet;
  1109. }
  1110. }
  1111. /**
  1112. * Abstract class implementing default filters for a DB column
  1113. *
  1114. * @package iTopORM
  1115. */
  1116. class AttributeDBFieldVoid extends AttributeDefinition
  1117. {
  1118. static public function ListExpectedParams()
  1119. {
  1120. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  1121. }
  1122. // To be overriden, used in GetSQLColumns
  1123. protected function GetSQLCol($bFullSpec = false)
  1124. {
  1125. return "VARCHAR(255)".($bFullSpec ? $this->GetSQLColSpec() : '');
  1126. }
  1127. protected function GetSQLColSpec()
  1128. {
  1129. $default = $this->ScalarToSQL($this->GetDefaultValue());
  1130. if (is_null($default))
  1131. {
  1132. $sRet = '';
  1133. }
  1134. else
  1135. {
  1136. if (is_numeric($default))
  1137. {
  1138. // Though it is a string in PHP, it will be considered as a numeric value in MySQL
  1139. // Then it must not be quoted here, to preserve the compatibility with the value returned by CMDBSource::GetFieldSpec
  1140. $sRet = " DEFAULT $default";
  1141. }
  1142. else
  1143. {
  1144. $sRet = " DEFAULT ".CMDBSource::Quote($default);
  1145. }
  1146. }
  1147. return $sRet;
  1148. }
  1149. public function GetEditClass() {return "String";}
  1150. public function GetValuesDef() {return $this->Get("allowed_values");}
  1151. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  1152. public function IsDirectField() {return true;}
  1153. public function IsScalar() {return true;}
  1154. public function IsWritable() {return true;}
  1155. public function GetSQLExpr() {return $this->Get("sql");}
  1156. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  1157. public function IsNullAllowed() {return false;}
  1158. //
  1159. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  1160. public function GetSQLExpressions($sPrefix = '')
  1161. {
  1162. $aColumns = array();
  1163. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1164. $aColumns[''] = $this->Get("sql");
  1165. return $aColumns;
  1166. }
  1167. public function FromSQLToValue($aCols, $sPrefix = '')
  1168. {
  1169. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  1170. return $value;
  1171. }
  1172. public function GetSQLValues($value)
  1173. {
  1174. $aValues = array();
  1175. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  1176. return $aValues;
  1177. }
  1178. public function GetSQLColumns($bFullSpec = false)
  1179. {
  1180. $aColumns = array();
  1181. $aColumns[$this->Get("sql")] = $this->GetSQLCol($bFullSpec);
  1182. return $aColumns;
  1183. }
  1184. public function GetFilterDefinitions()
  1185. {
  1186. return array($this->GetCode() => new FilterFromAttribute($this));
  1187. }
  1188. public function GetBasicFilterOperators()
  1189. {
  1190. return array("="=>"equals", "!="=>"differs from");
  1191. }
  1192. public function GetBasicFilterLooseOperator()
  1193. {
  1194. return "=";
  1195. }
  1196. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1197. {
  1198. $sQValue = CMDBSource::Quote($value);
  1199. switch ($sOpCode)
  1200. {
  1201. case '!=':
  1202. return $this->GetSQLExpr()." != $sQValue";
  1203. break;
  1204. case '=':
  1205. default:
  1206. return $this->GetSQLExpr()." = $sQValue";
  1207. }
  1208. }
  1209. }
  1210. /**
  1211. * Base class for all kind of DB attributes, with the exception of external keys
  1212. *
  1213. * @package iTopORM
  1214. */
  1215. class AttributeDBField extends AttributeDBFieldVoid
  1216. {
  1217. static public function ListExpectedParams()
  1218. {
  1219. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  1220. }
  1221. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"), null);}
  1222. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  1223. }
  1224. /**
  1225. * Map an integer column to an attribute
  1226. *
  1227. * @package iTopORM
  1228. */
  1229. class AttributeInteger extends AttributeDBField
  1230. {
  1231. static public function ListExpectedParams()
  1232. {
  1233. return parent::ListExpectedParams();
  1234. //return array_merge(parent::ListExpectedParams(), array());
  1235. }
  1236. public function GetEditClass() {return "String";}
  1237. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1238. public function GetValidationPattern()
  1239. {
  1240. return "^[0-9]+$";
  1241. }
  1242. public function GetBasicFilterOperators()
  1243. {
  1244. return array(
  1245. "!="=>"differs from",
  1246. "="=>"equals",
  1247. ">"=>"greater (strict) than",
  1248. ">="=>"greater than",
  1249. "<"=>"less (strict) than",
  1250. "<="=>"less than",
  1251. "in"=>"in"
  1252. );
  1253. }
  1254. public function GetBasicFilterLooseOperator()
  1255. {
  1256. // Unless we implement an "equals approximately..." or "same order of magnitude"
  1257. return "=";
  1258. }
  1259. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1260. {
  1261. $sQValue = CMDBSource::Quote($value);
  1262. switch ($sOpCode)
  1263. {
  1264. case '!=':
  1265. return $this->GetSQLExpr()." != $sQValue";
  1266. break;
  1267. case '>':
  1268. return $this->GetSQLExpr()." > $sQValue";
  1269. break;
  1270. case '>=':
  1271. return $this->GetSQLExpr()." >= $sQValue";
  1272. break;
  1273. case '<':
  1274. return $this->GetSQLExpr()." < $sQValue";
  1275. break;
  1276. case '<=':
  1277. return $this->GetSQLExpr()." <= $sQValue";
  1278. break;
  1279. case 'in':
  1280. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  1281. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  1282. break;
  1283. case '=':
  1284. default:
  1285. return $this->GetSQLExpr()." = \"$value\"";
  1286. }
  1287. }
  1288. public function GetNullValue()
  1289. {
  1290. return null;
  1291. }
  1292. public function IsNull($proposedValue)
  1293. {
  1294. return is_null($proposedValue);
  1295. }
  1296. public function MakeRealValue($proposedValue, $oHostObj)
  1297. {
  1298. if (is_null($proposedValue)) return null;
  1299. if ($proposedValue === '') return null; // 0 is transformed into '' !
  1300. return (int)$proposedValue;
  1301. }
  1302. public function ScalarToSQL($value)
  1303. {
  1304. assert(is_numeric($value) || is_null($value));
  1305. return $value; // supposed to be an int
  1306. }
  1307. }
  1308. /**
  1309. * An external key for which the class is defined as the value of another attribute
  1310. *
  1311. * @package iTopORM
  1312. */
  1313. class AttributeObjectKey extends AttributeDBFieldVoid
  1314. {
  1315. static public function ListExpectedParams()
  1316. {
  1317. return array_merge(parent::ListExpectedParams(), array('class_attcode', 'is_null_allowed'));
  1318. }
  1319. public function GetEditClass() {return "String";}
  1320. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? " DEFAULT 0" : "");}
  1321. public function GetDefaultValue() {return 0;}
  1322. public function IsNullAllowed()
  1323. {
  1324. return $this->Get("is_null_allowed");
  1325. }
  1326. public function GetBasicFilterOperators()
  1327. {
  1328. return parent::GetBasicFilterOperators();
  1329. }
  1330. public function GetBasicFilterLooseOperator()
  1331. {
  1332. return parent::GetBasicFilterLooseOperator();
  1333. }
  1334. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1335. {
  1336. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1337. }
  1338. public function GetNullValue()
  1339. {
  1340. return 0;
  1341. }
  1342. public function IsNull($proposedValue)
  1343. {
  1344. return ($proposedValue == 0);
  1345. }
  1346. public function MakeRealValue($proposedValue, $oHostObj)
  1347. {
  1348. if (is_null($proposedValue)) return 0;
  1349. if ($proposedValue === '') return 0;
  1350. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  1351. return (int)$proposedValue;
  1352. }
  1353. }
  1354. /**
  1355. * Display an integer between 0 and 100 as a percentage / horizontal bar graph
  1356. *
  1357. * @package iTopORM
  1358. */
  1359. class AttributePercentage extends AttributeInteger
  1360. {
  1361. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1362. {
  1363. $iWidth = 5; // Total width of the percentage bar graph, in em...
  1364. $iValue = (int)$sValue;
  1365. if ($iValue > 100)
  1366. {
  1367. $iValue = 100;
  1368. }
  1369. else if ($iValue < 0)
  1370. {
  1371. $iValue = 0;
  1372. }
  1373. if ($iValue > 90)
  1374. {
  1375. $sColor = "#cc3300";
  1376. }
  1377. else if ($iValue > 50)
  1378. {
  1379. $sColor = "#cccc00";
  1380. }
  1381. else
  1382. {
  1383. $sColor = "#33cc00";
  1384. }
  1385. $iPercentWidth = ($iWidth * $iValue) / 100;
  1386. return "<div style=\"width:{$iWidth}em;-moz-border-radius: 3px;-webkit-border-radius: 3px;border-radius: 3px;display:inline-block;border: 1px #ccc solid;\"><div style=\"width:{$iPercentWidth}em; display:inline-block;background-color:$sColor;\">&nbsp;</div></div>&nbsp;$sValue %";
  1387. }
  1388. }
  1389. /**
  1390. * Map a decimal value column (suitable for financial computations) to an attribute
  1391. * internally in PHP such numbers are represented as string. Should you want to perform
  1392. * a calculation on them, it is recommended to use the BC Math functions in order to
  1393. * retain the precision
  1394. *
  1395. * @package iTopORM
  1396. */
  1397. class AttributeDecimal extends AttributeDBField
  1398. {
  1399. static public function ListExpectedParams()
  1400. {
  1401. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  1402. }
  1403. public function GetEditClass() {return "String";}
  1404. protected function GetSQLCol($bFullSpec = false)
  1405. {
  1406. return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")".($bFullSpec ? $this->GetSQLColSpec() : '');
  1407. }
  1408. public function GetValidationPattern()
  1409. {
  1410. $iNbDigits = $this->Get('digits');
  1411. $iPrecision = $this->Get('decimals');
  1412. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  1413. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  1414. }
  1415. public function GetBasicFilterOperators()
  1416. {
  1417. return array(
  1418. "!="=>"differs from",
  1419. "="=>"equals",
  1420. ">"=>"greater (strict) than",
  1421. ">="=>"greater than",
  1422. "<"=>"less (strict) than",
  1423. "<="=>"less than",
  1424. "in"=>"in"
  1425. );
  1426. }
  1427. public function GetBasicFilterLooseOperator()
  1428. {
  1429. // Unless we implement an "equals approximately..." or "same order of magnitude"
  1430. return "=";
  1431. }
  1432. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1433. {
  1434. $sQValue = CMDBSource::Quote($value);
  1435. switch ($sOpCode)
  1436. {
  1437. case '!=':
  1438. return $this->GetSQLExpr()." != $sQValue";
  1439. break;
  1440. case '>':
  1441. return $this->GetSQLExpr()." > $sQValue";
  1442. break;
  1443. case '>=':
  1444. return $this->GetSQLExpr()." >= $sQValue";
  1445. break;
  1446. case '<':
  1447. return $this->GetSQLExpr()." < $sQValue";
  1448. break;
  1449. case '<=':
  1450. return $this->GetSQLExpr()." <= $sQValue";
  1451. break;
  1452. case 'in':
  1453. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  1454. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  1455. break;
  1456. case '=':
  1457. default:
  1458. return $this->GetSQLExpr()." = \"$value\"";
  1459. }
  1460. }
  1461. public function GetNullValue()
  1462. {
  1463. return null;
  1464. }
  1465. public function IsNull($proposedValue)
  1466. {
  1467. return is_null($proposedValue);
  1468. }
  1469. public function MakeRealValue($proposedValue, $oHostObj)
  1470. {
  1471. if (is_null($proposedValue)) return null;
  1472. if ($proposedValue === '') return null;
  1473. return (string)$proposedValue;
  1474. }
  1475. public function ScalarToSQL($value)
  1476. {
  1477. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  1478. return $value; // null or string
  1479. }
  1480. }
  1481. /**
  1482. * Map a boolean column to an attribute
  1483. *
  1484. * @package iTopORM
  1485. */
  1486. class AttributeBoolean extends AttributeInteger
  1487. {
  1488. static public function ListExpectedParams()
  1489. {
  1490. return parent::ListExpectedParams();
  1491. //return array_merge(parent::ListExpectedParams(), array());
  1492. }
  1493. public function GetEditClass() {return "Integer";}
  1494. protected function GetSQLCol($bFullSpec = false) {return "TINYINT(1)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1495. public function MakeRealValue($proposedValue, $oHostObj)
  1496. {
  1497. if (is_null($proposedValue)) return null;
  1498. if ($proposedValue === '') return null;
  1499. if ((int)$proposedValue) return true;
  1500. return false;
  1501. }
  1502. public function ScalarToSQL($value)
  1503. {
  1504. if ($value) return 1;
  1505. return 0;
  1506. }
  1507. public function GetAsXML($sValue, $oHostObject = null, $bLocalize = true)
  1508. {
  1509. return $sValue ? '1' : '0';
  1510. }
  1511. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  1512. {
  1513. return $sValue ? '1' : '0';
  1514. }
  1515. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1516. {
  1517. return $sValue ? '1' : '0';
  1518. }
  1519. /**
  1520. * Helper to get a value that will be JSON encoded
  1521. * The operation is the opposite to FromJSONToValue
  1522. */
  1523. public function GetForJSON($value)
  1524. {
  1525. return $value ? '1' : '0';
  1526. }
  1527. }
  1528. /**
  1529. * Map a varchar column (size < ?) to an attribute
  1530. *
  1531. * @package iTopORM
  1532. */
  1533. class AttributeString extends AttributeDBField
  1534. {
  1535. static public function ListExpectedParams()
  1536. {
  1537. return parent::ListExpectedParams();
  1538. //return array_merge(parent::ListExpectedParams(), array());
  1539. }
  1540. public function GetEditClass() {return "String";}
  1541. protected function GetSQLCol($bFullSpec = false) {return "VARCHAR(255)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1542. public function GetValidationPattern()
  1543. {
  1544. $sPattern = $this->GetOptional('validation_pattern', '');
  1545. if (empty($sPattern))
  1546. {
  1547. return parent::GetValidationPattern();
  1548. }
  1549. else
  1550. {
  1551. return $sPattern;
  1552. }
  1553. }
  1554. public function CheckFormat($value)
  1555. {
  1556. $sRegExp = $this->GetValidationPattern();
  1557. if (empty($sRegExp))
  1558. {
  1559. return true;
  1560. }
  1561. else
  1562. {
  1563. $sRegExp = str_replace('/', '\\/', $sRegExp);
  1564. return preg_match("/$sRegExp/", $value);
  1565. }
  1566. }
  1567. public function GetMaxSize()
  1568. {
  1569. return 255;
  1570. }
  1571. public function GetBasicFilterOperators()
  1572. {
  1573. return array(
  1574. "="=>"equals",
  1575. "!="=>"differs from",
  1576. "Like"=>"equals (no case)",
  1577. "NotLike"=>"differs from (no case)",
  1578. "Contains"=>"contains",
  1579. "Begins with"=>"begins with",
  1580. "Finishes with"=>"finishes with"
  1581. );
  1582. }
  1583. public function GetBasicFilterLooseOperator()
  1584. {
  1585. return "Contains";
  1586. }
  1587. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1588. {
  1589. $sQValue = CMDBSource::Quote($value);
  1590. switch ($sOpCode)
  1591. {
  1592. case '=':
  1593. case '!=':
  1594. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1595. case 'Begins with':
  1596. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  1597. case 'Finishes with':
  1598. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  1599. case 'Contains':
  1600. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  1601. case 'NotLike':
  1602. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  1603. case 'Like':
  1604. default:
  1605. return $this->GetSQLExpr()." LIKE $sQValue";
  1606. }
  1607. }
  1608. public function GetNullValue()
  1609. {
  1610. return '';
  1611. }
  1612. public function IsNull($proposedValue)
  1613. {
  1614. return ($proposedValue == '');
  1615. }
  1616. public function MakeRealValue($proposedValue, $oHostObj)
  1617. {
  1618. if (is_null($proposedValue)) return '';
  1619. return (string)$proposedValue;
  1620. }
  1621. public function ScalarToSQL($value)
  1622. {
  1623. if (!is_string($value) && !is_null($value))
  1624. {
  1625. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetHostClass(), 'attribute' => $this->GetCode()));
  1626. }
  1627. return $value;
  1628. }
  1629. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  1630. {
  1631. $sFrom = array("\r\n", $sTextQualifier);
  1632. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1633. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1634. return $sTextQualifier.$sEscaped.$sTextQualifier;
  1635. }
  1636. public function GetDisplayStyle()
  1637. {
  1638. return $this->GetOptional('display_style', 'select');
  1639. }
  1640. }
  1641. /**
  1642. * An attibute that matches an object class
  1643. *
  1644. * @package iTopORM
  1645. */
  1646. class AttributeClass extends AttributeString
  1647. {
  1648. static public function ListExpectedParams()
  1649. {
  1650. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  1651. }
  1652. public function __construct($sCode, $aParams)
  1653. {
  1654. $this->m_sCode = $sCode;
  1655. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  1656. parent::__construct($sCode, $aParams);
  1657. }
  1658. public function GetDefaultValue()
  1659. {
  1660. $sDefault = parent::GetDefaultValue();
  1661. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  1662. {
  1663. // For this kind of attribute specifying null as default value
  1664. // is authorized even if null is not allowed
  1665. // Pick the first one...
  1666. $aClasses = $this->GetAllowedValues();
  1667. $sDefault = key($aClasses);
  1668. }
  1669. return $sDefault;
  1670. }
  1671. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1672. {
  1673. if (empty($sValue)) return '';
  1674. return MetaModel::GetName($sValue);
  1675. }
  1676. public function RequiresIndex()
  1677. {
  1678. return true;
  1679. }
  1680. public function GetBasicFilterLooseOperator()
  1681. {
  1682. return '=';
  1683. }
  1684. }
  1685. /**
  1686. * An attibute that matches one of the language codes availables in the dictionnary
  1687. *
  1688. * @package iTopORM
  1689. */
  1690. class AttributeApplicationLanguage extends AttributeString
  1691. {
  1692. static public function ListExpectedParams()
  1693. {
  1694. return parent::ListExpectedParams();
  1695. }
  1696. public function __construct($sCode, $aParams)
  1697. {
  1698. $this->m_sCode = $sCode;
  1699. $aAvailableLanguages = Dict::GetLanguages();
  1700. $aLanguageCodes = array();
  1701. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  1702. {
  1703. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  1704. }
  1705. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  1706. parent::__construct($sCode, $aParams);
  1707. }
  1708. public function RequiresIndex()
  1709. {
  1710. return true;
  1711. }
  1712. public function GetBasicFilterLooseOperator()
  1713. {
  1714. return '=';
  1715. }
  1716. }
  1717. /**
  1718. * The attribute dedicated to the finalclass automatic attribute
  1719. *
  1720. * @package iTopORM
  1721. */
  1722. class AttributeFinalClass extends AttributeString
  1723. {
  1724. public function __construct($sCode, $aParams)
  1725. {
  1726. $this->m_sCode = $sCode;
  1727. $aParams["allowed_values"] = null;
  1728. parent::__construct($sCode, $aParams);
  1729. $this->m_sValue = $this->Get("default_value");
  1730. }
  1731. public function IsWritable()
  1732. {
  1733. return false;
  1734. }
  1735. public function RequiresIndex()
  1736. {
  1737. return true;
  1738. }
  1739. public function SetFixedValue($sValue)
  1740. {
  1741. $this->m_sValue = $sValue;
  1742. }
  1743. public function GetDefaultValue()
  1744. {
  1745. return $this->m_sValue;
  1746. }
  1747. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1748. {
  1749. if (empty($sValue)) return '';
  1750. if ($bLocalize)
  1751. {
  1752. return MetaModel::GetName($sValue);
  1753. }
  1754. else
  1755. {
  1756. return $sValue;
  1757. }
  1758. }
  1759. // Because this is sometimes used to get a localized/string version of an attribute...
  1760. public function GetEditValue($sValue, $oHostObj = null)
  1761. {
  1762. if (empty($sValue)) return '';
  1763. return MetaModel::GetName($sValue);
  1764. }
  1765. /**
  1766. * Helper to get a value that will be JSON encoded
  1767. * The operation is the opposite to FromJSONToValue
  1768. */
  1769. public function GetForJSON($value)
  1770. {
  1771. // JSON values are NOT localized
  1772. return $value;
  1773. }
  1774. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  1775. {
  1776. if ($bLocalize && $value != '')
  1777. {
  1778. $sRawValue = MetaModel::GetName($value);
  1779. }
  1780. else
  1781. {
  1782. $sRawValue = $value;
  1783. }
  1784. return parent::GetAsCSV($sRawValue, $sSeparator, $sTextQualifier, null, false);
  1785. }
  1786. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  1787. {
  1788. if (empty($value)) return '';
  1789. if ($bLocalize)
  1790. {
  1791. $sRawValue = MetaModel::GetName($value);
  1792. }
  1793. else
  1794. {
  1795. $sRawValue = $value;
  1796. }
  1797. return Str::pure2xml($sRawValue);
  1798. }
  1799. public function GetBasicFilterLooseOperator()
  1800. {
  1801. return '=';
  1802. }
  1803. public function GetValueLabel($sValue)
  1804. {
  1805. if (empty($sValue)) return '';
  1806. return MetaModel::GetName($sValue);
  1807. }
  1808. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1809. {
  1810. $aRawValues = MetaModel::EnumChildClasses($this->GetHostClass(), ENUM_CHILD_CLASSES_ALL);
  1811. $aLocalizedValues = array();
  1812. foreach ($aRawValues as $sClass)
  1813. {
  1814. $aLocalizedValues[$sClass] = MetaModel::GetName($sClass);
  1815. }
  1816. return $aLocalizedValues;
  1817. }
  1818. }
  1819. /**
  1820. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  1821. *
  1822. * @package iTopORM
  1823. */
  1824. class AttributePassword extends AttributeString
  1825. {
  1826. static public function ListExpectedParams()
  1827. {
  1828. return parent::ListExpectedParams();
  1829. //return array_merge(parent::ListExpectedParams(), array());
  1830. }
  1831. public function GetEditClass() {return "Password";}
  1832. protected function GetSQLCol($bFullSpec = false) {return "VARCHAR(64)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  1833. public function GetMaxSize()
  1834. {
  1835. return 64;
  1836. }
  1837. public function GetFilterDefinitions()
  1838. {
  1839. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  1840. // not allowed to search on passwords!
  1841. return array();
  1842. }
  1843. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1844. {
  1845. if (strlen($sValue) == 0)
  1846. {
  1847. return '';
  1848. }
  1849. else
  1850. {
  1851. return '******';
  1852. }
  1853. }
  1854. public function IsPartOfFingerprint() { return false; } // Cannot reliably compare two encrypted passwords since the same password will be encrypted in diffferent manners depending on the random 'salt'
  1855. }
  1856. /**
  1857. * Map a text column (size < 255) to an attribute that is encrypted in the database
  1858. * The encryption is based on a key set per iTop instance. Thus if you export your
  1859. * database (in SQL) to someone else without providing the key at the same time
  1860. * the encrypted fields will remain encrypted
  1861. *
  1862. * @package iTopORM
  1863. */
  1864. class AttributeEncryptedString extends AttributeString
  1865. {
  1866. static $sKey = null; // Encryption key used for all encrypted fields
  1867. public function __construct($sCode, $aParams)
  1868. {
  1869. parent::__construct($sCode, $aParams);
  1870. if (self::$sKey == null)
  1871. {
  1872. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1873. }
  1874. }
  1875. /**
  1876. * When the attribute definitions are stored in APC cache:
  1877. * 1) The static class variable $sKey is NOT serialized
  1878. * 2) The object's constructor is NOT called upon wakeup
  1879. * 3) mcrypt may crash the server if passed an empty key !!
  1880. *
  1881. * So let's restore the key (if needed) when waking up
  1882. **/
  1883. public function __wakeup()
  1884. {
  1885. if (self::$sKey == null)
  1886. {
  1887. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1888. }
  1889. }
  1890. protected function GetSQLCol($bFullSpec = false) {return "TINYBLOB";}
  1891. public function GetMaxSize()
  1892. {
  1893. return 255;
  1894. }
  1895. public function GetFilterDefinitions()
  1896. {
  1897. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  1898. // not allowed to search on encrypted fields !
  1899. return array();
  1900. }
  1901. public function MakeRealValue($proposedValue, $oHostObj)
  1902. {
  1903. if (is_null($proposedValue)) return null;
  1904. return (string)$proposedValue;
  1905. }
  1906. /**
  1907. * Decrypt the value when reading from the database
  1908. */
  1909. public function FromSQLToValue($aCols, $sPrefix = '')
  1910. {
  1911. $oSimpleCrypt = new SimpleCrypt();
  1912. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  1913. return $sValue;
  1914. }
  1915. /**
  1916. * Encrypt the value before storing it in the database
  1917. */
  1918. public function GetSQLValues($value)
  1919. {
  1920. $oSimpleCrypt = new SimpleCrypt();
  1921. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  1922. $aValues = array();
  1923. $aValues[$this->Get("sql")] = $encryptedValue;
  1924. return $aValues;
  1925. }
  1926. }
  1927. // Wiki formatting - experimental
  1928. //
  1929. // [[<objClass>:<objName>]]
  1930. // Example: [[Server:db1.tnut.com]]
  1931. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  1932. /**
  1933. * Map a text column (size > ?) to an attribute
  1934. *
  1935. * @package iTopORM
  1936. */
  1937. class AttributeText extends AttributeString
  1938. {
  1939. public function GetEditClass() {return "Text";}
  1940. protected function GetSQLCol($bFullSpec = false) {return "TEXT";}
  1941. public function GetMaxSize()
  1942. {
  1943. // Is there a way to know the current limitation for mysql?
  1944. // See mysql_field_len()
  1945. return 65535;
  1946. }
  1947. static public function RenderWikiHtml($sText)
  1948. {
  1949. $sPattern = '/'.str_replace('/', '\/', utils::GetConfig()->Get('url_validation_pattern')).'/i';
  1950. if (preg_match_all($sPattern, $sText, $aAllMatches, PREG_SET_ORDER /* important !*/ |PREG_OFFSET_CAPTURE /* important ! */))
  1951. {
  1952. $aUrls = array();
  1953. $i = count($aAllMatches);
  1954. // Replace the URLs by an actual hyperlink <a href="...">...</a>
  1955. // Let's do it backwards so that the initial positions are not modified by the replacement
  1956. // This works if the matches are captured: in the order they occur in the string AND
  1957. // with their offset (i.e. position) inside the string
  1958. while($i > 0)
  1959. {
  1960. $i--;
  1961. $sUrl = $aAllMatches[$i][0][0]; // String corresponding to the main pattern
  1962. $iPos = $aAllMatches[$i][0][1]; // Position of the main pattern
  1963. $sText = substr_replace($sText, "<a href=\"$sUrl\">$sUrl</a>", $iPos, strlen($sUrl));
  1964. }
  1965. }
  1966. if (preg_match_all(WIKI_OBJECT_REGEXP, $sText, $aAllMatches, PREG_SET_ORDER))
  1967. {
  1968. foreach($aAllMatches as $iPos => $aMatches)
  1969. {
  1970. $sClass = $aMatches[1];
  1971. $sName = $aMatches[2];
  1972. if (MetaModel::IsValidClass($sClass))
  1973. {
  1974. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  1975. if (is_object($oObj))
  1976. {
  1977. // Propose a std link to the object
  1978. $sText = str_replace($aMatches[0], $oObj->GetHyperlink(), $sText);
  1979. }
  1980. else
  1981. {
  1982. // Propose a std link to the object
  1983. $sClassLabel = MetaModel::GetName($sClass);
  1984. $sText = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sText);
  1985. // Later: propose a link to create a new object
  1986. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  1987. //$sText = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="'.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sText);
  1988. }
  1989. }
  1990. }
  1991. }
  1992. return $sText;
  1993. }
  1994. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  1995. {
  1996. $sValue = parent::GetAsHTML($sValue, $oHostObject, $bLocalize);
  1997. $sValue = self::RenderWikiHtml($sValue);
  1998. $aStyles = array();
  1999. if ($this->GetWidth() != '')
  2000. {
  2001. $aStyles[] = 'width:'.$this->GetWidth();
  2002. }
  2003. if ($this->GetHeight() != '')
  2004. {
  2005. $aStyles[] = 'height:'.$this->GetHeight();
  2006. }
  2007. $sStyle = '';
  2008. if (count($aStyles) > 0)
  2009. {
  2010. $aStyles[] = 'overflow:auto';
  2011. $sStyle = 'style="'.implode(';', $aStyles).'"';
  2012. }
  2013. return "<div $sStyle>".str_replace("\n", "<br>\n", $sValue).'</div>';
  2014. }
  2015. public function GetEditValue($sValue, $oHostObj = null)
  2016. {
  2017. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  2018. {
  2019. foreach($aAllMatches as $iPos => $aMatches)
  2020. {
  2021. $sClass = $aMatches[1];
  2022. $sName = $aMatches[2];
  2023. if (MetaModel::IsValidClass($sClass))
  2024. {
  2025. $sClassLabel = MetaModel::GetName($sClass);
  2026. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  2027. }
  2028. }
  2029. }
  2030. return $sValue;
  2031. }
  2032. public function MakeRealValue($proposedValue, $oHostObj)
  2033. {
  2034. $sValue = $proposedValue;
  2035. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  2036. {
  2037. foreach($aAllMatches as $iPos => $aMatches)
  2038. {
  2039. $sClassLabel = $aMatches[1];
  2040. $sName = $aMatches[2];
  2041. if (!MetaModel::IsValidClass($sClassLabel))
  2042. {
  2043. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  2044. if ($sClass)
  2045. {
  2046. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  2047. }
  2048. }
  2049. }
  2050. }
  2051. return $sValue;
  2052. }
  2053. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2054. {
  2055. return Str::pure2xml($value);
  2056. }
  2057. public function GetWidth()
  2058. {
  2059. return $this->GetOptional('width', '');
  2060. }
  2061. public function GetHeight()
  2062. {
  2063. return $this->GetOptional('height', '');
  2064. }
  2065. }
  2066. /**
  2067. * Map a log to an attribute
  2068. *
  2069. * @package iTopORM
  2070. */
  2071. class AttributeLongText extends AttributeText
  2072. {
  2073. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  2074. public function GetMaxSize()
  2075. {
  2076. // Is there a way to know the current limitation for mysql?
  2077. // See mysql_field_len()
  2078. return 65535*1024; // Limited... still 64 Mb!
  2079. }
  2080. }
  2081. /**
  2082. * An attibute that stores a case log (i.e journal)
  2083. *
  2084. * @package iTopORM
  2085. */
  2086. class AttributeCaseLog extends AttributeLongText
  2087. {
  2088. public function GetNullValue()
  2089. {
  2090. return '';
  2091. }
  2092. public function IsNull($proposedValue)
  2093. {
  2094. if (!($proposedValue instanceof ormCaseLog))
  2095. {
  2096. return ($proposedValue == '');
  2097. }
  2098. return ($proposedValue->GetText() == '');
  2099. }
  2100. public function ScalarToSQL($value)
  2101. {
  2102. if (!is_string($value) && !is_null($value))
  2103. {
  2104. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  2105. }
  2106. return $value;
  2107. }
  2108. public function GetEditClass() {return "CaseLog";}
  2109. public function GetEditValue($sValue, $oHostObj = null)
  2110. {
  2111. if (!($sValue instanceOf ormCaseLog))
  2112. {
  2113. return '';
  2114. }
  2115. return $sValue->GetModifiedEntry();
  2116. }
  2117. public function GetDefaultValue() {return new ormCaseLog();}
  2118. public function Equals($val1, $val2) {return ($val1->GetText() == $val2->GetText());}
  2119. // Facilitate things: allow the user to Set the value from a string
  2120. public function MakeRealValue($proposedValue, $oHostObj)
  2121. {
  2122. if ($proposedValue instanceof ormCaseLog)
  2123. {
  2124. // Passthrough
  2125. $ret = $proposedValue;
  2126. }
  2127. else
  2128. {
  2129. // Append the new value if an instance of the object is supplied
  2130. //
  2131. $oPreviousLog = null;
  2132. if ($oHostObj != null)
  2133. {
  2134. $oPreviousLog = $oHostObj->Get($this->GetCode());
  2135. if (!is_object($oPreviousLog))
  2136. {
  2137. $oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
  2138. }
  2139. }
  2140. if (is_object($oPreviousLog))
  2141. {
  2142. $oCaseLog = clone($oPreviousLog);
  2143. }
  2144. else
  2145. {
  2146. $oCaseLog = new ormCaseLog();
  2147. }
  2148. if ($proposedValue instanceof stdClass)
  2149. {
  2150. $oCaseLog->AddLogEntryFromJSON($proposedValue);
  2151. }
  2152. else
  2153. {
  2154. if (strlen($proposedValue) > 0)
  2155. {
  2156. $oCaseLog->AddLogEntry(parent::MakeRealValue($proposedValue, $oHostObj));
  2157. }
  2158. }
  2159. $ret = $oCaseLog;
  2160. }
  2161. return $ret;
  2162. }
  2163. public function GetSQLExpressions($sPrefix = '')
  2164. {
  2165. if ($sPrefix == '')
  2166. {
  2167. $sPrefix = $this->GetCode();
  2168. }
  2169. $aColumns = array();
  2170. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2171. $aColumns[''] = $sPrefix;
  2172. $aColumns['_index'] = $sPrefix.'_index';
  2173. return $aColumns;
  2174. }
  2175. public function FromSQLToValue($aCols, $sPrefix = '')
  2176. {
  2177. if (!array_key_exists($sPrefix, $aCols))
  2178. {
  2179. $sAvailable = implode(', ', array_keys($aCols));
  2180. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2181. }
  2182. $sLog = $aCols[$sPrefix];
  2183. if (isset($aCols[$sPrefix.'_index']))
  2184. {
  2185. $sIndex = $aCols[$sPrefix.'_index'];
  2186. }
  2187. else
  2188. {
  2189. // For backward compatibility, allow the current state to be: 1 log, no index
  2190. $sIndex = '';
  2191. }
  2192. if (strlen($sIndex) > 0)
  2193. {
  2194. $aIndex = unserialize($sIndex);
  2195. $value = new ormCaseLog($sLog, $aIndex);
  2196. }
  2197. else
  2198. {
  2199. $value = new ormCaseLog($sLog);
  2200. }
  2201. return $value;
  2202. }
  2203. public function GetSQLValues($value)
  2204. {
  2205. if (!($value instanceOf ormCaseLog))
  2206. {
  2207. $value = new ormCaseLog('');
  2208. }
  2209. $aValues = array();
  2210. $aValues[$this->GetCode()] = $value->GetText();
  2211. $aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
  2212. return $aValues;
  2213. }
  2214. public function GetSQLColumns($bFullSpec = false)
  2215. {
  2216. $aColumns = array();
  2217. $aColumns[$this->GetCode()] = 'LONGTEXT'; // 2^32 (4 Gb)
  2218. $aColumns[$this->GetCode().'_index'] = 'BLOB';
  2219. return $aColumns;
  2220. }
  2221. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2222. {
  2223. if ($value instanceOf ormCaseLog)
  2224. {
  2225. $sContent = $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
  2226. }
  2227. else
  2228. {
  2229. $sContent = '';
  2230. }
  2231. $aStyles = array();
  2232. if ($this->GetWidth() != '')
  2233. {
  2234. $aStyles[] = 'width:'.$this->GetWidth();
  2235. }
  2236. if ($this->GetHeight() != '')
  2237. {
  2238. $aStyles[] = 'height:'.$this->GetHeight();
  2239. }
  2240. $sStyle = '';
  2241. if (count($aStyles) > 0)
  2242. {
  2243. $sStyle = 'style="'.implode(';', $aStyles).'"';
  2244. }
  2245. return "<div class=\"caselog\" $sStyle>".$sContent.'</div>'; }
  2246. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  2247. {
  2248. if ($value instanceOf ormCaseLog)
  2249. {
  2250. return parent::GetAsCSV($value->GetText(), $sSeparator, $sTextQualifier, $oHostObject, $bLocalize);
  2251. }
  2252. else
  2253. {
  2254. return '';
  2255. }
  2256. }
  2257. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2258. {
  2259. if ($value instanceOf ormCaseLog)
  2260. {
  2261. return parent::GetAsXML($value->GetText(), $oHostObject, $bLocalize);
  2262. }
  2263. else
  2264. {
  2265. return '';
  2266. }
  2267. }
  2268. /**
  2269. * List the available verbs for 'GetForTemplate'
  2270. */
  2271. public static function EnumTemplateVerbs()
  2272. {
  2273. return array(
  2274. '' => 'Plain text representation of all the log entries',
  2275. 'head' => 'Plain text representation of the latest entry',
  2276. 'head_html' => 'HTML representation of the latest entry',
  2277. 'html' => 'HTML representation of all the log entries',
  2278. );
  2279. }
  2280. /**
  2281. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  2282. * @param $value mixed The current value of the field
  2283. * @param $sVerb string The verb specifying the representation of the value
  2284. * @param $oHostObject DBObject The object
  2285. * @param $bLocalize bool Whether or not to localize the value
  2286. */
  2287. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  2288. {
  2289. switch($sVerb)
  2290. {
  2291. case '':
  2292. return $value->GetText();
  2293. case 'head':
  2294. return $value->GetLatestEntry();
  2295. case 'head_html':
  2296. return '<div class="caselog_entry">'.str_replace( array( "\r\n", "\n", "\r"), "<br/>", htmlentities($value->GetLatestEntry(), ENT_QUOTES, 'UTF-8')).'</div>';
  2297. case 'html':
  2298. return $value->GetAsEmailHtml();
  2299. default:
  2300. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObj));
  2301. }
  2302. }
  2303. /**
  2304. * Helper to get a value that will be JSON encoded
  2305. * The operation is the opposite to FromJSONToValue
  2306. */
  2307. public function GetForJSON($value)
  2308. {
  2309. return $value->GetForJSON();
  2310. }
  2311. /**
  2312. * Helper to form a value, given JSON decoded data
  2313. * The operation is the opposite to GetForJSON
  2314. */
  2315. public function FromJSONToValue($json)
  2316. {
  2317. if (is_string($json))
  2318. {
  2319. // Will be correctly handled in MakeRealValue
  2320. $ret = $json;
  2321. }
  2322. else
  2323. {
  2324. if (isset($json->add_item))
  2325. {
  2326. // Will be correctly handled in MakeRealValue
  2327. $ret = $json->add_item;
  2328. if (!isset($ret->message))
  2329. {
  2330. throw new Exception("Missing mandatory entry: 'message'");
  2331. }
  2332. }
  2333. else
  2334. {
  2335. $ret = ormCaseLog::FromJSON($json);
  2336. }
  2337. }
  2338. return $ret;
  2339. }
  2340. public function Fingerprint($value)
  2341. {
  2342. $sFingerprint = '';
  2343. if ($value instanceOf ormCaseLog)
  2344. {
  2345. $sFingerprint = $value->GetText();
  2346. }
  2347. return $sFingerprint;
  2348. }
  2349. }
  2350. /**
  2351. * Map a text column (size > ?), containing HTML code, to an attribute
  2352. *
  2353. * @package iTopORM
  2354. */
  2355. class AttributeHTML extends AttributeLongText
  2356. {
  2357. public function GetEditClass() {return "HTML";}
  2358. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2359. {
  2360. return $sValue;
  2361. }
  2362. }
  2363. /**
  2364. * Specialization of a string: email
  2365. *
  2366. * @package iTopORM
  2367. */
  2368. class AttributeEmailAddress extends AttributeString
  2369. {
  2370. public function GetValidationPattern()
  2371. {
  2372. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('email_validation_pattern').'$');
  2373. }
  2374. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2375. {
  2376. if (empty($sValue)) return '';
  2377. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  2378. }
  2379. }
  2380. /**
  2381. * Specialization of a string: IP address
  2382. *
  2383. * @package iTopORM
  2384. */
  2385. class AttributeIPAddress extends AttributeString
  2386. {
  2387. public function GetValidationPattern()
  2388. {
  2389. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  2390. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  2391. }
  2392. public function GetOrderBySQLExpressions($sClassAlias)
  2393. {
  2394. // Note: This is the responsibility of this function to place backticks around column aliases
  2395. return array('INET_ATON(`'.$sClassAlias.$this->GetCode().'`)');
  2396. }
  2397. }
  2398. /**
  2399. * Specialization of a string: OQL expression
  2400. *
  2401. * @package iTopORM
  2402. */
  2403. class AttributeOQL extends AttributeText
  2404. {
  2405. public function GetEditClass() {return "OQLExpression";}
  2406. }
  2407. /**
  2408. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2409. *
  2410. * @package iTopORM
  2411. */
  2412. class AttributeTemplateString extends AttributeString
  2413. {
  2414. }
  2415. /**
  2416. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2417. *
  2418. * @package iTopORM
  2419. */
  2420. class AttributeTemplateText extends AttributeText
  2421. {
  2422. }
  2423. /**
  2424. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2425. *
  2426. * @package iTopORM
  2427. */
  2428. class AttributeTemplateHTML extends AttributeText
  2429. {
  2430. public function GetEditClass() {return "HTML";}
  2431. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2432. {
  2433. return $sValue;
  2434. }
  2435. }
  2436. /**
  2437. * Map a enum column to an attribute
  2438. *
  2439. * @package iTopORM
  2440. */
  2441. class AttributeEnum extends AttributeString
  2442. {
  2443. static public function ListExpectedParams()
  2444. {
  2445. return parent::ListExpectedParams();
  2446. //return array_merge(parent::ListExpectedParams(), array());
  2447. }
  2448. public function GetEditClass() {return "String";}
  2449. protected function GetSQLCol($bFullSpec = false)
  2450. {
  2451. $oValDef = $this->GetValuesDef();
  2452. if ($oValDef)
  2453. {
  2454. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  2455. }
  2456. else
  2457. {
  2458. $aValues = array();
  2459. }
  2460. if (count($aValues) > 0)
  2461. {
  2462. // The syntax used here do matters
  2463. // In particular, I had to remove unnecessary spaces to
  2464. // make sure that this string will match the field type returned by the DB
  2465. // (used to perform a comparison between the current DB format and the data model)
  2466. return "ENUM(".implode(",", $aValues).")".($bFullSpec ? $this->GetSQLColSpec() : '');
  2467. }
  2468. else
  2469. {
  2470. return "VARCHAR(255)".($bFullSpec ? " DEFAULT ''" : ""); // ENUM() is not an allowed syntax!
  2471. }
  2472. }
  2473. protected function GetSQLColSpec()
  2474. {
  2475. $default = $this->ScalarToSQL($this->GetDefaultValue());
  2476. if (is_null($default))
  2477. {
  2478. $sRet = '';
  2479. }
  2480. else
  2481. {
  2482. // ENUMs values are strings so the default value must be a string as well,
  2483. // otherwise MySQL interprets the number as the zero-based index of the value in the list (i.e. the nth value in the list)
  2484. $sRet = " DEFAULT ".CMDBSource::Quote($default);
  2485. }
  2486. return $sRet;
  2487. }
  2488. public function ScalarToSQL($value)
  2489. {
  2490. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  2491. // but that wasn't working for enums, because '' is NOT one of the allowed values
  2492. // that's why a null value must be forced to a real null
  2493. $value = parent::ScalarToSQL($value);
  2494. if ($this->IsNull($value))
  2495. {
  2496. return null;
  2497. }
  2498. else
  2499. {
  2500. return $value;
  2501. }
  2502. }
  2503. public function RequiresIndex()
  2504. {
  2505. return false;
  2506. }
  2507. public function GetBasicFilterOperators()
  2508. {
  2509. return parent::GetBasicFilterOperators();
  2510. }
  2511. public function GetBasicFilterLooseOperator()
  2512. {
  2513. return '=';
  2514. }
  2515. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2516. {
  2517. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2518. }
  2519. public function GetValueLabel($sValue)
  2520. {
  2521. if (is_null($sValue))
  2522. {
  2523. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2524. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  2525. }
  2526. else
  2527. {
  2528. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, null, true /*user lang*/);
  2529. if (is_null($sLabel))
  2530. {
  2531. $sDefault = str_replace('_', ' ', $sValue);
  2532. // Browse the hierarchy again, accepting default (english) translations
  2533. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, $sDefault, false);
  2534. }
  2535. }
  2536. return $sLabel;
  2537. }
  2538. public function GetValueDescription($sValue)
  2539. {
  2540. if (is_null($sValue))
  2541. {
  2542. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2543. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', Dict::S('Enum:Undefined'));
  2544. }
  2545. else
  2546. {
  2547. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', '', true /* user language only */);
  2548. if (strlen($sDescription) == 0)
  2549. {
  2550. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  2551. if ($sParentClass)
  2552. {
  2553. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  2554. {
  2555. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  2556. $sDescription = $oAttDef->GetValueDescription($sValue);
  2557. }
  2558. }
  2559. }
  2560. }
  2561. return $sDescription;
  2562. }
  2563. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2564. {
  2565. if ($bLocalize)
  2566. {
  2567. $sLabel = $this->GetValueLabel($sValue);
  2568. $sDescription = $this->GetValueDescription($sValue);
  2569. // later, we could imagine a detailed description in the title
  2570. $sRes = "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  2571. }
  2572. else
  2573. {
  2574. $sRes = parent::GetAsHtml($sValue, $oHostObject, $bLocalize);
  2575. }
  2576. return $sRes;
  2577. }
  2578. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2579. {
  2580. if (is_null($value))
  2581. {
  2582. $sFinalValue = '';
  2583. }
  2584. elseif ($bLocalize)
  2585. {
  2586. $sFinalValue = $this->GetValueLabel($value);
  2587. }
  2588. else
  2589. {
  2590. $sFinalValue = $value;
  2591. }
  2592. $sRes = parent::GetAsXML($sFinalValue, $oHostObject, $bLocalize);
  2593. return $sRes;
  2594. }
  2595. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  2596. {
  2597. if (is_null($sValue))
  2598. {
  2599. $sFinalValue = '';
  2600. }
  2601. elseif ($bLocalize)
  2602. {
  2603. $sFinalValue = $this->GetValueLabel($sValue);
  2604. }
  2605. else
  2606. {
  2607. $sFinalValue = $sValue;
  2608. }
  2609. $sRes = parent::GetAsCSV($sFinalValue, $sSeparator, $sTextQualifier, $oHostObject, $bLocalize);
  2610. return $sRes;
  2611. }
  2612. public function GetEditValue($sValue, $oHostObj = null)
  2613. {
  2614. if (is_null($sValue))
  2615. {
  2616. return '';
  2617. }
  2618. else
  2619. {
  2620. return $this->GetValueLabel($sValue);
  2621. }
  2622. }
  2623. /**
  2624. * Helper to get a value that will be JSON encoded
  2625. * The operation is the opposite to FromJSONToValue
  2626. */
  2627. public function GetForJSON($value)
  2628. {
  2629. return $value;
  2630. }
  2631. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2632. {
  2633. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  2634. if (is_null($aRawValues)) return null;
  2635. $aLocalizedValues = array();
  2636. foreach ($aRawValues as $sKey => $sValue)
  2637. {
  2638. $aLocalizedValues[$sKey] = Str::pure2html($this->GetValueLabel($sKey));
  2639. }
  2640. return $aLocalizedValues;
  2641. }
  2642. /**
  2643. * An enum can be localized
  2644. */
  2645. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  2646. {
  2647. if ($bLocalizedValue)
  2648. {
  2649. // Lookup for the value matching the input
  2650. //
  2651. $sFoundValue = null;
  2652. $aRawValues = parent::GetAllowedValues();
  2653. if (!is_null($aRawValues))
  2654. {
  2655. foreach ($aRawValues as $sKey => $sValue)
  2656. {
  2657. $sRefValue = $this->GetValueLabel($sKey);
  2658. if ($sProposedValue == $sRefValue)
  2659. {
  2660. $sFoundValue = $sKey;
  2661. break;
  2662. }
  2663. }
  2664. }
  2665. if (is_null($sFoundValue))
  2666. {
  2667. return null;
  2668. }
  2669. return $this->MakeRealValue($sFoundValue, null);
  2670. }
  2671. else
  2672. {
  2673. return parent::MakeValueFromString($sProposedValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue, $sAttributeQualifier);
  2674. }
  2675. }
  2676. /**
  2677. * Processes the input value to align it with the values supported
  2678. * by this type of attribute. In this case: turns empty strings into nulls
  2679. * @param mixed $proposedValue The value to be set for the attribute
  2680. * @return mixed The actual value that will be set
  2681. */
  2682. public function MakeRealValue($proposedValue, $oHostObj)
  2683. {
  2684. if ($proposedValue == '') return null;
  2685. return parent::MakeRealValue($proposedValue, $oHostObj);
  2686. }
  2687. public function GetOrderByHint()
  2688. {
  2689. $aValues = $this->GetAllowedValues();
  2690. return Dict::Format('UI:OrderByHint_Values', implode(', ', $aValues));
  2691. }
  2692. }
  2693. /**
  2694. * Map a date+time column to an attribute
  2695. *
  2696. * @package iTopORM
  2697. */
  2698. class AttributeDateTime extends AttributeDBField
  2699. {
  2700. static public function GetDateFormat()
  2701. {
  2702. return "Y-m-d H:i:s";
  2703. }
  2704. static public function ListExpectedParams()
  2705. {
  2706. return parent::ListExpectedParams();
  2707. //return array_merge(parent::ListExpectedParams(), array());
  2708. }
  2709. public function GetEditClass() {return "DateTime";}
  2710. protected function GetSQLCol($bFullSpec = false) {return "DATETIME";}
  2711. public static function GetAsUnixSeconds($value)
  2712. {
  2713. $oDeadlineDateTime = new DateTime($value);
  2714. $iUnixSeconds = $oDeadlineDateTime->format('U');
  2715. return $iUnixSeconds;
  2716. }
  2717. // This has been done at the time when itop was using TIMESTAMP columns,
  2718. // now that iTop is using DATETIME columns, it seems possible to have IsNullAllowed returning false... later when this is needed
  2719. public function IsNullAllowed() {return true;}
  2720. public function GetDefaultValue()
  2721. {
  2722. $default = parent::GetDefaultValue();
  2723. if (!parent::IsNullAllowed())
  2724. {
  2725. if (empty($default))
  2726. {
  2727. $default = date($this->GetDateFormat());
  2728. }
  2729. }
  2730. return $default;
  2731. }
  2732. // END OF THE WORKAROUND
  2733. ///////////////////////////////////////////////////////////////
  2734. public function GetValidationPattern()
  2735. {
  2736. return "^(([0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30))))( (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])(:([0-5][0-9])){0,1}){0,1}|0000-00-00 00:00:00|0000-00-00)$";
  2737. }
  2738. public function GetBasicFilterOperators()
  2739. {
  2740. return array(
  2741. "="=>"equals",
  2742. "!="=>"differs from",
  2743. "<"=>"before",
  2744. "<="=>"before",
  2745. ">"=>"after (strictly)",
  2746. ">="=>"after",
  2747. "SameDay"=>"same day (strip time)",
  2748. "SameMonth"=>"same year/month",
  2749. "SameYear"=>"same year",
  2750. "Today"=>"today",
  2751. ">|"=>"after today + N days",
  2752. "<|"=>"before today + N days",
  2753. "=|"=>"equals today + N days",
  2754. );
  2755. }
  2756. public function GetBasicFilterLooseOperator()
  2757. {
  2758. // Unless we implement a "same xxx, depending on given precision" !
  2759. return "=";
  2760. }
  2761. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2762. {
  2763. $sQValue = CMDBSource::Quote($value);
  2764. switch ($sOpCode)
  2765. {
  2766. case '=':
  2767. case '!=':
  2768. case '<':
  2769. case '<=':
  2770. case '>':
  2771. case '>=':
  2772. return $this->GetSQLExpr()." $sOpCode $sQValue";
  2773. case 'SameDay':
  2774. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  2775. case 'SameMonth':
  2776. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  2777. case 'SameYear':
  2778. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  2779. case 'Today':
  2780. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  2781. case '>|':
  2782. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2783. case '<|':
  2784. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2785. case '=|':
  2786. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2787. default:
  2788. return $this->GetSQLExpr()." = $sQValue";
  2789. }
  2790. }
  2791. public function MakeRealValue($proposedValue, $oHostObj)
  2792. {
  2793. if (is_null($proposedValue))
  2794. {
  2795. return null;
  2796. }
  2797. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  2798. {
  2799. return null;
  2800. }
  2801. if (!is_numeric($proposedValue))
  2802. {
  2803. return $proposedValue;
  2804. }
  2805. return date(self::GetDateFormat(), $proposedValue);
  2806. }
  2807. public function ScalarToSQL($value)
  2808. {
  2809. if (is_null($value))
  2810. {
  2811. return null;
  2812. }
  2813. elseif (empty($value))
  2814. {
  2815. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  2816. return '0000-00-00 00:00:00';
  2817. }
  2818. return $value;
  2819. }
  2820. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2821. {
  2822. return Str::pure2html($value);
  2823. }
  2824. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2825. {
  2826. return Str::pure2xml($value);
  2827. }
  2828. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  2829. {
  2830. $sFrom = array("\r\n", $sTextQualifier);
  2831. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  2832. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  2833. return $sTextQualifier.$sEscaped.$sTextQualifier;
  2834. }
  2835. /**
  2836. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  2837. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  2838. * does nothing special, and just calls the default (loose) operator
  2839. * @param string $sSearchText The search string to analyze for smart patterns
  2840. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  2841. * @param Hash $aParams Values of the query parameters
  2842. * @return Expression The search condition to be added (AND) to the current search
  2843. */
  2844. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  2845. {
  2846. // Possible smart patterns
  2847. $aPatterns = array(
  2848. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  2849. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  2850. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  2851. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  2852. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  2853. );
  2854. $sPatternFound = '';
  2855. $aMatches = array();
  2856. foreach($aPatterns as $sPatName => $sPattern)
  2857. {
  2858. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  2859. {
  2860. $sPatternFound = $sPatName;
  2861. break;
  2862. }
  2863. }
  2864. switch($sPatternFound)
  2865. {
  2866. case 'between':
  2867. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  2868. $oRightExpr = new VariableExpression($sParamName1);
  2869. $aParams[$sParamName1] = $aMatches[1];
  2870. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  2871. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  2872. $oRightExpr = new VariableExpression($sParamName2);
  2873. $sOperator = $this->GetBasicFilterLooseOperator();
  2874. $aParams[$sParamName2] = $aMatches[2];
  2875. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  2876. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  2877. break;
  2878. case 'greater than':
  2879. case 'greater than or equal':
  2880. case 'less than':
  2881. case 'less than or equal':
  2882. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  2883. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  2884. $oRightExpr = new VariableExpression($sParamName);
  2885. $aParams[$sParamName] = $aMatches[1];
  2886. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  2887. break;
  2888. default:
  2889. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  2890. }
  2891. return $oNewCondition;
  2892. }
  2893. }
  2894. /**
  2895. * Store a duration as a number of seconds
  2896. *
  2897. * @package iTopORM
  2898. */
  2899. class AttributeDuration extends AttributeInteger
  2900. {
  2901. public function GetEditClass() {return "Duration";}
  2902. protected function GetSQLCol($bFullSpec = false) {return "INT(11) UNSIGNED";}
  2903. public function GetNullValue() {return '0';}
  2904. public function MakeRealValue($proposedValue, $oHostObj)
  2905. {
  2906. if (is_null($proposedValue)) return null;
  2907. if (!is_numeric($proposedValue)) return null;
  2908. if ( ((int)$proposedValue) < 0) return null;
  2909. return (int)$proposedValue;
  2910. }
  2911. public function ScalarToSQL($value)
  2912. {
  2913. if (is_null($value))
  2914. {
  2915. return null;
  2916. }
  2917. return $value;
  2918. }
  2919. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2920. {
  2921. return Str::pure2html(self::FormatDuration($value));
  2922. }
  2923. public static function FormatDuration($duration)
  2924. {
  2925. $aDuration = self::SplitDuration($duration);
  2926. $sResult = '';
  2927. if ($duration < 60)
  2928. {
  2929. // Less than 1 min
  2930. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  2931. }
  2932. else if ($duration < 3600)
  2933. {
  2934. // less than 1 hour, display it in minutes/seconds
  2935. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  2936. }
  2937. else if ($duration < 86400)
  2938. {
  2939. // Less than 1 day, display it in hours/minutes/seconds
  2940. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2941. }
  2942. else
  2943. {
  2944. // more than 1 day, display it in days/hours/minutes/seconds
  2945. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2946. }
  2947. return $sResult;
  2948. }
  2949. static function SplitDuration($duration)
  2950. {
  2951. $duration = (int) $duration;
  2952. $days = floor($duration / 86400);
  2953. $hours = floor(($duration - (86400*$days)) / 3600);
  2954. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2955. $seconds = ($duration % 60); // modulo
  2956. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  2957. }
  2958. }
  2959. /**
  2960. * Map a date+time column to an attribute
  2961. *
  2962. * @package iTopORM
  2963. */
  2964. class AttributeDate extends AttributeDateTime
  2965. {
  2966. const MYDATEFORMAT = "Y-m-d";
  2967. static public function GetDateFormat()
  2968. {
  2969. return "Y-m-d";
  2970. }
  2971. static public function ListExpectedParams()
  2972. {
  2973. return parent::ListExpectedParams();
  2974. //return array_merge(parent::ListExpectedParams(), array());
  2975. }
  2976. public function GetEditClass() {return "Date";}
  2977. protected function GetSQLCol($bFullSpec = false) {return "DATE";}
  2978. public function GetValidationPattern()
  2979. {
  2980. return "^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$";
  2981. }
  2982. }
  2983. /**
  2984. * A dead line stored as a date & time
  2985. * The only difference with the DateTime attribute is the display:
  2986. * relative to the current time
  2987. */
  2988. class AttributeDeadline extends AttributeDateTime
  2989. {
  2990. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2991. {
  2992. $sResult = self::FormatDeadline($value);
  2993. return $sResult;
  2994. }
  2995. public static function FormatDeadline($value)
  2996. {
  2997. $sResult = '';
  2998. if ($value !== null)
  2999. {
  3000. $iValue = AttributeDateTime::GetAsUnixSeconds($value);
  3001. $sDate = $value;
  3002. $difference = $iValue - time();
  3003. if ($difference >= 0)
  3004. {
  3005. $sDifference = self::FormatDuration($difference);
  3006. }
  3007. else
  3008. {
  3009. $sDifference = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  3010. }
  3011. $sFormat = MetaModel::GetConfig()->Get('deadline_format', '$difference$');
  3012. $sResult = str_replace(array('$date$', '$difference$'), array($sDate, $sDifference), $sFormat);
  3013. }
  3014. return $sResult;
  3015. }
  3016. static function FormatDuration($duration)
  3017. {
  3018. $days = floor($duration / 86400);
  3019. $hours = floor(($duration - (86400*$days)) / 3600);
  3020. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  3021. $sResult = '';
  3022. if ($duration < 60)
  3023. {
  3024. // Less than 1 min
  3025. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  3026. }
  3027. else if ($duration < 3600)
  3028. {
  3029. // less than 1 hour, display it in minutes
  3030. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  3031. }
  3032. else if ($duration < 86400)
  3033. {
  3034. // Less that 1 day, display it in hours/minutes
  3035. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  3036. }
  3037. else
  3038. {
  3039. // Less that 1 day, display it in hours/minutes
  3040. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  3041. }
  3042. return $sResult;
  3043. }
  3044. }
  3045. /**
  3046. * Map a foreign key to an attribute
  3047. * AttributeExternalKey and AttributeExternalField may be an external key
  3048. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  3049. * where an AttributeExternalField corresponds to a column into another table (class)
  3050. *
  3051. * @package iTopORM
  3052. */
  3053. class AttributeExternalKey extends AttributeDBFieldVoid
  3054. {
  3055. static public function ListExpectedParams()
  3056. {
  3057. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  3058. }
  3059. public function GetEditClass() {return "ExtKey";}
  3060. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? " DEFAULT 0" : "");}
  3061. public function RequiresIndex()
  3062. {
  3063. return true;
  3064. }
  3065. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  3066. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  3067. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  3068. public function GetKeyAttCode() {return $this->GetCode();}
  3069. public function GetDisplayStyle() { return $this->GetOptional('display_style', 'select'); }
  3070. public function GetDefaultValue() {return 0;}
  3071. public function IsNullAllowed()
  3072. {
  3073. if (MetaModel::GetConfig()->Get('disable_mandatory_ext_keys'))
  3074. {
  3075. return true;
  3076. }
  3077. return $this->Get("is_null_allowed");
  3078. }
  3079. public function GetBasicFilterOperators()
  3080. {
  3081. return parent::GetBasicFilterOperators();
  3082. }
  3083. public function GetBasicFilterLooseOperator()
  3084. {
  3085. return parent::GetBasicFilterLooseOperator();
  3086. }
  3087. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3088. {
  3089. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  3090. }
  3091. // overloaded here so that an ext key always have the answer to
  3092. // "what are your possible values?"
  3093. public function GetValuesDef()
  3094. {
  3095. $oValSetDef = $this->Get("allowed_values");
  3096. if (!$oValSetDef)
  3097. {
  3098. // Let's propose every existing value
  3099. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  3100. }
  3101. return $oValSetDef;
  3102. }
  3103. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3104. {
  3105. //throw new Exception("GetAllowedValues on ext key has been deprecated");
  3106. try
  3107. {
  3108. return parent::GetAllowedValues($aArgs, $sContains);
  3109. }
  3110. catch (MissingQueryArgument $e)
  3111. {
  3112. // Some required arguments could not be found, enlarge to any existing value
  3113. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  3114. return $oValSetDef->GetValues($aArgs, $sContains);
  3115. }
  3116. }
  3117. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  3118. {
  3119. $oValSetDef = $this->GetValuesDef();
  3120. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  3121. return $oSet;
  3122. }
  3123. public function GetDeletionPropagationOption()
  3124. {
  3125. return $this->Get("on_target_delete");
  3126. }
  3127. public function GetNullValue()
  3128. {
  3129. return 0;
  3130. }
  3131. public function IsNull($proposedValue)
  3132. {
  3133. return ($proposedValue == 0);
  3134. }
  3135. public function MakeRealValue($proposedValue, $oHostObj)
  3136. {
  3137. if (is_null($proposedValue)) return 0;
  3138. if ($proposedValue === '') return 0;
  3139. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  3140. return (int)$proposedValue;
  3141. }
  3142. public function GetMaximumComboLength()
  3143. {
  3144. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  3145. }
  3146. public function GetMinAutoCompleteChars()
  3147. {
  3148. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  3149. }
  3150. public function AllowTargetCreation()
  3151. {
  3152. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  3153. }
  3154. /**
  3155. * Find the corresponding "link" attribute on the target class
  3156. *
  3157. * @return string The attribute code on the target class, or null if none has been found
  3158. */
  3159. public function GetMirrorLinkAttribute()
  3160. {
  3161. $oRet = null;
  3162. $sRemoteClass = $this->GetTargetClass();
  3163. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  3164. {
  3165. if (!$oRemoteAttDef->IsLinkSet()) continue;
  3166. if (!is_subclass_of($this->GetHostClass(), $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $this->GetHostClass()) continue;
  3167. if ($oRemoteAttDef->GetExtKeyToMe() != $this->GetCode()) continue;
  3168. $oRet = $oRemoteAttDef;
  3169. break;
  3170. }
  3171. return $oRet;
  3172. }
  3173. }
  3174. /**
  3175. * Special kind of External Key to manage a hierarchy of objects
  3176. */
  3177. class AttributeHierarchicalKey extends AttributeExternalKey
  3178. {
  3179. protected $m_sTargetClass;
  3180. static public function ListExpectedParams()
  3181. {
  3182. $aParams = parent::ListExpectedParams();
  3183. $idx = array_search('targetclass', $aParams);
  3184. unset($aParams[$idx]);
  3185. $idx = array_search('jointype', $aParams);
  3186. unset($aParams[$idx]);
  3187. return $aParams; // TODO: mettre les bons parametres ici !!
  3188. }
  3189. public function GetEditClass() {return "ExtKey";}
  3190. public function RequiresIndex()
  3191. {
  3192. return true;
  3193. }
  3194. /*
  3195. * The target class is the class for which the attribute has been defined first
  3196. */
  3197. public function SetHostClass($sHostClass)
  3198. {
  3199. if (!isset($this->m_sTargetClass))
  3200. {
  3201. $this->m_sTargetClass = $sHostClass;
  3202. }
  3203. parent::SetHostClass($sHostClass);
  3204. }
  3205. public function IsHierarchicalKey() {return true;}
  3206. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->m_sTargetClass;}
  3207. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  3208. public function GetKeyAttCode() {return $this->GetCode();}
  3209. public function GetBasicFilterOperators()
  3210. {
  3211. return parent::GetBasicFilterOperators();
  3212. }
  3213. public function GetBasicFilterLooseOperator()
  3214. {
  3215. return parent::GetBasicFilterLooseOperator();
  3216. }
  3217. public function GetSQLColumns($bFullSpec = false)
  3218. {
  3219. $aColumns = array();
  3220. $aColumns[$this->GetCode()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3221. $aColumns[$this->GetSQLLeft()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3222. $aColumns[$this->GetSQLRight()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3223. return $aColumns;
  3224. }
  3225. public function GetSQLRight()
  3226. {
  3227. return $this->GetCode().'_right';
  3228. }
  3229. public function GetSQLLeft()
  3230. {
  3231. return $this->GetCode().'_left';
  3232. }
  3233. public function GetSQLValues($value)
  3234. {
  3235. if (!is_array($value))
  3236. {
  3237. $aValues[$this->GetCode()] = $value;
  3238. }
  3239. else
  3240. {
  3241. $aValues = array();
  3242. $aValues[$this->GetCode()] = $value[$this->GetCode()];
  3243. $aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
  3244. $aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
  3245. }
  3246. return $aValues;
  3247. }
  3248. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3249. {
  3250. if (array_key_exists('this', $aArgs))
  3251. {
  3252. // Hierarchical keys have one more constraint: the "parent value" cannot be
  3253. // "under" themselves
  3254. $iRootId = $aArgs['this']->GetKey();
  3255. if ($iRootId > 0) // ignore objects that do no exist in the database...
  3256. {
  3257. $oValSetDef = $this->GetValuesDef();
  3258. $sClass = $this->m_sTargetClass;
  3259. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  3260. $oValSetDef->AddCondition($oFilter);
  3261. }
  3262. }
  3263. else
  3264. {
  3265. return parent::GetAllowedValues($aArgs, $sContains);
  3266. }
  3267. }
  3268. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  3269. {
  3270. $oValSetDef = $this->GetValuesDef();
  3271. if (array_key_exists('this', $aArgs))
  3272. {
  3273. // Hierarchical keys have one more constraint: the "parent value" cannot be
  3274. // "under" themselves
  3275. $iRootId = $aArgs['this']->GetKey();
  3276. if ($iRootId > 0) // ignore objects that do no exist in the database...
  3277. {
  3278. $aValuesSetDef = $this->GetValuesDef();
  3279. $sClass = $this->m_sTargetClass;
  3280. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  3281. $oValSetDef->AddCondition($oFilter);
  3282. }
  3283. }
  3284. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  3285. return $oSet;
  3286. }
  3287. /**
  3288. * Find the corresponding "link" attribute on the target class
  3289. *
  3290. * @return string The attribute code on the target class, or null if none has been found
  3291. */
  3292. public function GetMirrorLinkAttribute()
  3293. {
  3294. return null;
  3295. }
  3296. }
  3297. /**
  3298. * An attribute which corresponds to an external key (direct or indirect)
  3299. *
  3300. * @package iTopORM
  3301. */
  3302. class AttributeExternalField extends AttributeDefinition
  3303. {
  3304. static public function ListExpectedParams()
  3305. {
  3306. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  3307. }
  3308. public function GetEditClass() {return "ExtField";}
  3309. public function GetFinalAttDef()
  3310. {
  3311. $oExtAttDef = $this->GetExtAttDef();
  3312. return $oExtAttDef->GetFinalAttDef();
  3313. }
  3314. protected function GetSQLCol($bFullSpec = false)
  3315. {
  3316. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  3317. $oExtAttDef = $this->GetExtAttDef();
  3318. return $oExtAttDef->GetSQLCol($bFullSpec);
  3319. }
  3320. public function GetSQLExpressions($sPrefix = '')
  3321. {
  3322. if ($sPrefix == '')
  3323. {
  3324. return array('' => $this->GetCode());
  3325. }
  3326. else
  3327. {
  3328. return $sPrefix;
  3329. }
  3330. }
  3331. public function GetLabel($sDefault = null)
  3332. {
  3333. $sLabel = parent::GetLabel('');
  3334. if (strlen($sLabel) == 0)
  3335. {
  3336. $oRemoteAtt = $this->GetExtAttDef();
  3337. $sLabel = $oRemoteAtt->GetLabel($this->m_sCode);
  3338. }
  3339. return $sLabel;
  3340. }
  3341. public function GetDescription($sDefault = null)
  3342. {
  3343. $sLabel = parent::GetDescription('');
  3344. if (strlen($sLabel) == 0)
  3345. {
  3346. $oRemoteAtt = $this->GetExtAttDef();
  3347. $sLabel = $oRemoteAtt->GetDescription('');
  3348. }
  3349. return $sLabel;
  3350. }
  3351. public function GetHelpOnEdition($sDefault = null)
  3352. {
  3353. $sLabel = parent::GetHelpOnEdition('');
  3354. if (strlen($sLabel) == 0)
  3355. {
  3356. $oRemoteAtt = $this->GetExtAttDef();
  3357. $sLabel = $oRemoteAtt->GetHelpOnEdition('');
  3358. }
  3359. return $sLabel;
  3360. }
  3361. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  3362. {
  3363. switch($iType)
  3364. {
  3365. case EXTKEY_ABSOLUTE:
  3366. // see further
  3367. $oRemoteAtt = $this->GetExtAttDef();
  3368. return $oRemoteAtt->IsExternalKey($iType);
  3369. case EXTKEY_RELATIVE:
  3370. return false;
  3371. default:
  3372. throw new CoreException("Unexpected value for argument iType: '$iType'");
  3373. }
  3374. }
  3375. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  3376. {
  3377. return $this->GetKeyAttDef($iType)->GetTargetClass();
  3378. }
  3379. public function IsExternalField() {return true;}
  3380. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  3381. public function GetExtAttCode() {return $this->Get("target_attcode");}
  3382. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  3383. {
  3384. switch($iType)
  3385. {
  3386. case EXTKEY_ABSOLUTE:
  3387. // see further
  3388. $oRemoteAtt = $this->GetExtAttDef();
  3389. if ($oRemoteAtt->IsExternalField())
  3390. {
  3391. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  3392. }
  3393. else if ($oRemoteAtt->IsExternalKey())
  3394. {
  3395. return $oRemoteAtt;
  3396. }
  3397. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  3398. case EXTKEY_RELATIVE:
  3399. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  3400. default:
  3401. throw new CoreException("Unexpected value for argument iType: '$iType'");
  3402. }
  3403. }
  3404. public function GetPrerequisiteAttributes()
  3405. {
  3406. return array($this->Get("extkey_attcode"));
  3407. }
  3408. public function GetExtAttDef()
  3409. {
  3410. $oKeyAttDef = $this->GetKeyAttDef();
  3411. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $this->Get("target_attcode"));
  3412. if (!is_object($oExtAttDef)) throw new CoreException("Invalid external field ".$this->GetCode()." in class ".$this->GetHostClass().". The class ".$oKeyAttDef->GetTargetClass()." has no attribute ".$this->Get("target_attcode"));
  3413. return $oExtAttDef;
  3414. }
  3415. public function GetSQLExpr()
  3416. {
  3417. $oExtAttDef = $this->GetExtAttDef();
  3418. return $oExtAttDef->GetSQLExpr();
  3419. }
  3420. public function GetDefaultValue()
  3421. {
  3422. $oExtAttDef = $this->GetExtAttDef();
  3423. return $oExtAttDef->GetDefaultValue();
  3424. }
  3425. public function IsNullAllowed()
  3426. {
  3427. $oExtAttDef = $this->GetExtAttDef();
  3428. return $oExtAttDef->IsNullAllowed();
  3429. }
  3430. public function IsScalar()
  3431. {
  3432. $oExtAttDef = $this->GetExtAttDef();
  3433. return $oExtAttDef->IsScalar();
  3434. }
  3435. public function GetFilterDefinitions()
  3436. {
  3437. return array($this->GetCode() => new FilterFromAttribute($this));
  3438. }
  3439. public function GetBasicFilterOperators()
  3440. {
  3441. $oExtAttDef = $this->GetExtAttDef();
  3442. return $oExtAttDef->GetBasicFilterOperators();
  3443. }
  3444. public function GetBasicFilterLooseOperator()
  3445. {
  3446. $oExtAttDef = $this->GetExtAttDef();
  3447. return $oExtAttDef->GetBasicFilterLooseOperator();
  3448. }
  3449. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3450. {
  3451. $oExtAttDef = $this->GetExtAttDef();
  3452. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  3453. }
  3454. public function GetNullValue()
  3455. {
  3456. $oExtAttDef = $this->GetExtAttDef();
  3457. return $oExtAttDef->GetNullValue();
  3458. }
  3459. public function IsNull($proposedValue)
  3460. {
  3461. $oExtAttDef = $this->GetExtAttDef();
  3462. return $oExtAttDef->IsNull($proposedValue);
  3463. }
  3464. public function MakeRealValue($proposedValue, $oHostObj)
  3465. {
  3466. $oExtAttDef = $this->GetExtAttDef();
  3467. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  3468. }
  3469. public function ScalarToSQL($value)
  3470. {
  3471. // This one could be used in case of filtering only
  3472. $oExtAttDef = $this->GetExtAttDef();
  3473. return $oExtAttDef->ScalarToSQL($value);
  3474. }
  3475. // Do not overload GetSQLExpression here because this is handled in the joins
  3476. //public function GetSQLExpressions($sPrefix = '') {return array();}
  3477. // Here, we get the data...
  3478. public function FromSQLToValue($aCols, $sPrefix = '')
  3479. {
  3480. $oExtAttDef = $this->GetExtAttDef();
  3481. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  3482. }
  3483. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3484. {
  3485. $oExtAttDef = $this->GetExtAttDef();
  3486. return $oExtAttDef->GetAsHTML($value, null, $bLocalize);
  3487. }
  3488. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3489. {
  3490. $oExtAttDef = $this->GetExtAttDef();
  3491. return $oExtAttDef->GetAsXML($value, null, $bLocalize);
  3492. }
  3493. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null, $bLocalize = true)
  3494. {
  3495. $oExtAttDef = $this->GetExtAttDef();
  3496. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier, null, $bLocalize);
  3497. }
  3498. public function IsPartOfFingerprint() { return false; }
  3499. }
  3500. /**
  3501. * Map a varchar column to an URL (formats the ouput in HMTL)
  3502. *
  3503. * @package iTopORM
  3504. */
  3505. class AttributeURL extends AttributeString
  3506. {
  3507. static public function ListExpectedParams()
  3508. {
  3509. //return parent::ListExpectedParams();
  3510. return array_merge(parent::ListExpectedParams(), array("target"));
  3511. }
  3512. public function GetEditClass() {return "String";}
  3513. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  3514. {
  3515. $sTarget = $this->Get("target");
  3516. if (empty($sTarget)) $sTarget = "_blank";
  3517. $sLabel = Str::pure2html($sValue);
  3518. if (strlen($sLabel) > 255)
  3519. {
  3520. // Truncate the length to 128 characters, by removing the middle
  3521. $sLabel = substr($sLabel, 0, 100).'.....'.substr($sLabel, -20);
  3522. }
  3523. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  3524. }
  3525. public function GetValidationPattern()
  3526. {
  3527. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('url_validation_pattern').'$');
  3528. }
  3529. }
  3530. /**
  3531. * A blob is an ormDocument, it is stored as several columns in the database
  3532. *
  3533. * @package iTopORM
  3534. */
  3535. class AttributeBlob extends AttributeDefinition
  3536. {
  3537. static public function ListExpectedParams()
  3538. {
  3539. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  3540. }
  3541. public function GetEditClass() {return "Document";}
  3542. public function IsDirectField() {return true;}
  3543. public function IsScalar() {return true;}
  3544. public function IsWritable() {return true;}
  3545. public function GetDefaultValue() {return "";}
  3546. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  3547. public function GetEditValue($sValue, $oHostObj = null)
  3548. {
  3549. return '';
  3550. }
  3551. // Facilitate things: allow administrators to upload a document
  3552. // from a CSV by specifying its path/URL
  3553. public function MakeRealValue($proposedValue, $oHostObj)
  3554. {
  3555. if (!is_object($proposedValue))
  3556. {
  3557. if (file_exists($proposedValue) && UserRights::IsAdministrator())
  3558. {
  3559. $sContent = file_get_contents($proposedValue);
  3560. $sExtension = strtolower(pathinfo($proposedValue, PATHINFO_EXTENSION));
  3561. $sMimeType = "application/x-octet-stream";
  3562. $aKnownExtensions = array(
  3563. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  3564. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3565. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3566. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3567. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3568. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3569. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3570. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3571. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3572. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12.xlsx',
  3573. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  3574. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  3575. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  3576. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  3577. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  3578. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  3579. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  3580. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  3581. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  3582. 'jpg' => 'image/jpeg',
  3583. 'jpeg' => 'image/jpeg',
  3584. 'gif' => 'image/gif',
  3585. 'png' => 'image/png',
  3586. 'pdf' => 'application/pdf',
  3587. 'doc' => 'application/msword',
  3588. 'dot' => 'application/msword',
  3589. 'xls' => 'application/vnd.ms-excel',
  3590. 'ppt' => 'application/vnd.ms-powerpoint',
  3591. 'vsd' => 'application/x-visio',
  3592. 'vdx' => 'application/visio.drawing',
  3593. 'odt' => 'application/vnd.oasis.opendocument.text',
  3594. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  3595. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  3596. 'zip' => 'application/zip',
  3597. 'txt' => 'text/plain',
  3598. 'htm' => 'text/html',
  3599. 'html' => 'text/html',
  3600. 'exe' => 'application/octet-stream'
  3601. );
  3602. if (!array_key_exists($sExtension, $aKnownExtensions) && extension_loaded('fileinfo'))
  3603. {
  3604. $finfo = new finfo(FILEINFO_MIME);
  3605. $sMimeType = $finfo->file($proposedValue);
  3606. }
  3607. return new ormDocument($sContent, $sMimeType);
  3608. }
  3609. else
  3610. {
  3611. return new ormDocument($proposedValue, 'text/plain');
  3612. }
  3613. }
  3614. return $proposedValue;
  3615. }
  3616. public function GetSQLExpressions($sPrefix = '')
  3617. {
  3618. if ($sPrefix == '')
  3619. {
  3620. $sPrefix = $this->GetCode();
  3621. }
  3622. $aColumns = array();
  3623. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  3624. $aColumns[''] = $sPrefix.'_mimetype';
  3625. $aColumns['_data'] = $sPrefix.'_data';
  3626. $aColumns['_filename'] = $sPrefix.'_filename';
  3627. return $aColumns;
  3628. }
  3629. public function FromSQLToValue($aCols, $sPrefix = '')
  3630. {
  3631. if (!array_key_exists($sPrefix, $aCols))
  3632. {
  3633. $sAvailable = implode(', ', array_keys($aCols));
  3634. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  3635. }
  3636. $sMimeType = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  3637. if (!array_key_exists($sPrefix.'_data', $aCols))
  3638. {
  3639. $sAvailable = implode(', ', array_keys($aCols));
  3640. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  3641. }
  3642. $data = isset($aCols[$sPrefix.'_data']) ? $aCols[$sPrefix.'_data'] : null;
  3643. if (!array_key_exists($sPrefix.'_filename', $aCols))
  3644. {
  3645. $sAvailable = implode(', ', array_keys($aCols));
  3646. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  3647. }
  3648. $sFileName = isset($aCols[$sPrefix.'_filename']) ? $aCols[$sPrefix.'_filename'] : '';
  3649. $value = new ormDocument($data, $sMimeType, $sFileName);
  3650. return $value;
  3651. }
  3652. public function GetSQLValues($value)
  3653. {
  3654. // #@# Optimization: do not load blobs anytime
  3655. // As per mySQL doc, selecting blob columns will prevent mySQL from
  3656. // using memory in case a temporary table has to be created
  3657. // (temporary tables created on disk)
  3658. // We will have to remove the blobs from the list of attributes when doing the select
  3659. // then the use of Get() should finalize the load
  3660. if ($value instanceOf ormDocument)
  3661. {
  3662. $aValues = array();
  3663. $aValues[$this->GetCode().'_data'] = $value->GetData();
  3664. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  3665. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  3666. }
  3667. else
  3668. {
  3669. $aValues = array();
  3670. $aValues[$this->GetCode().'_data'] = '';
  3671. $aValues[$this->GetCode().'_mimetype'] = '';
  3672. $aValues[$this->GetCode().'_filename'] = '';
  3673. }
  3674. return $aValues;
  3675. }
  3676. public function GetSQLColumns($bFullSpec = false)
  3677. {
  3678. $aColumns = array();
  3679. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  3680. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  3681. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  3682. return $aColumns;
  3683. }
  3684. public function GetFilterDefinitions()
  3685. {
  3686. return array();
  3687. // still not working... see later...
  3688. return array(
  3689. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  3690. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  3691. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  3692. );
  3693. }
  3694. public function GetBasicFilterOperators()
  3695. {
  3696. return array();
  3697. }
  3698. public function GetBasicFilterLooseOperator()
  3699. {
  3700. return '=';
  3701. }
  3702. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3703. {
  3704. return 'true';
  3705. }
  3706. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3707. {
  3708. if (is_object($value))
  3709. {
  3710. return $value->GetAsHTML();
  3711. }
  3712. }
  3713. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  3714. {
  3715. return ''; // Not exportable in CSV !
  3716. }
  3717. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3718. {
  3719. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  3720. }
  3721. /**
  3722. * Helper to get a value that will be JSON encoded
  3723. * The operation is the opposite to FromJSONToValue
  3724. */
  3725. public function GetForJSON($value)
  3726. {
  3727. if ($value instanceOf ormDocument)
  3728. {
  3729. $aValues = array();
  3730. $aValues['data'] = base64_encode($value->GetData());
  3731. $aValues['mimetype'] = $value->GetMimeType();
  3732. $aValues['filename'] = $value->GetFileName();
  3733. }
  3734. else
  3735. {
  3736. $aValues = null;
  3737. }
  3738. return $aValues;
  3739. }
  3740. /**
  3741. * Helper to form a value, given JSON decoded data
  3742. * The operation is the opposite to GetForJSON
  3743. */
  3744. public function FromJSONToValue($json)
  3745. {
  3746. if (isset($json->data))
  3747. {
  3748. $data = base64_decode($json->data);
  3749. $value = new ormDocument($data, $json->mimetype, $json->filename);
  3750. }
  3751. else
  3752. {
  3753. $value = null;
  3754. }
  3755. return $value;
  3756. }
  3757. public function Fingerprint($value)
  3758. {
  3759. $sFingerprint = '';
  3760. if ($value instanceOf ormDocument)
  3761. {
  3762. $sFingerprint = md5($value->GetData());
  3763. }
  3764. return $sFingerprint;
  3765. }
  3766. }
  3767. /**
  3768. * A stop watch is an ormStopWatch object, it is stored as several columns in the database
  3769. *
  3770. * @package iTopORM
  3771. */
  3772. class AttributeStopWatch extends AttributeDefinition
  3773. {
  3774. static public function ListExpectedParams()
  3775. {
  3776. // The list of thresholds must be an array of iPercent => array of 'option' => value
  3777. return array_merge(parent::ListExpectedParams(), array("states", "goal_computing", "working_time_computing", "thresholds"));
  3778. }
  3779. public function GetEditClass() {return "StopWatch";}
  3780. public function IsDirectField() {return true;}
  3781. public function IsScalar() {return true;}
  3782. public function IsWritable() {return false;}
  3783. public function GetDefaultValue() {return $this->NewStopWatch();}
  3784. public function GetEditValue($value, $oHostObj = null)
  3785. {
  3786. return $value->GetTimeSpent();
  3787. }
  3788. public function GetStates()
  3789. {
  3790. return $this->Get('states');
  3791. }
  3792. public function AlwaysLoadInTables()
  3793. {
  3794. // Each and every stop watch is accessed for computing the highlight code (DBObject::GetHighlightCode())
  3795. return true;
  3796. }
  3797. /**
  3798. * Construct a brand new (but configured) stop watch
  3799. */
  3800. public function NewStopWatch()
  3801. {
  3802. $oSW = new ormStopWatch();
  3803. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3804. {
  3805. $oSW->DefineThreshold($iThreshold);
  3806. }
  3807. return $oSW;
  3808. }
  3809. // Facilitate things: allow the user to Set the value from a string
  3810. public function MakeRealValue($proposedValue, $oHostObj)
  3811. {
  3812. if (!$proposedValue instanceof ormStopWatch)
  3813. {
  3814. return $this->NewStopWatch();
  3815. }
  3816. return $proposedValue;
  3817. }
  3818. public function GetSQLExpressions($sPrefix = '')
  3819. {
  3820. if ($sPrefix == '')
  3821. {
  3822. $sPrefix = $this->GetCode();
  3823. }
  3824. $aColumns = array();
  3825. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  3826. $aColumns[''] = $sPrefix.'_timespent';
  3827. $aColumns['_started'] = $sPrefix.'_started';
  3828. $aColumns['_laststart'] = $sPrefix.'_laststart';
  3829. $aColumns['_stopped'] = $sPrefix.'_stopped';
  3830. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3831. {
  3832. $sThPrefix = '_'.$iThreshold;
  3833. $aColumns[$sThPrefix.'_deadline'] = $sPrefix.$sThPrefix.'_deadline';
  3834. $aColumns[$sThPrefix.'_passed'] = $sPrefix.$sThPrefix.'_passed';
  3835. $aColumns[$sThPrefix.'_triggered'] = $sPrefix.$sThPrefix.'_triggered';
  3836. $aColumns[$sThPrefix.'_overrun'] = $sPrefix.$sThPrefix.'_overrun';
  3837. }
  3838. return $aColumns;
  3839. }
  3840. public static function DateToSeconds($sDate)
  3841. {
  3842. if (is_null($sDate))
  3843. {
  3844. return null;
  3845. }
  3846. $oDateTime = new DateTime($sDate);
  3847. $iSeconds = $oDateTime->format('U');
  3848. return $iSeconds;
  3849. }
  3850. public static function SecondsToDate($iSeconds)
  3851. {
  3852. if (is_null($iSeconds))
  3853. {
  3854. return null;
  3855. }
  3856. return date("Y-m-d H:i:s", $iSeconds);
  3857. }
  3858. public function FromSQLToValue($aCols, $sPrefix = '')
  3859. {
  3860. $aExpectedCols = array($sPrefix, $sPrefix.'_started', $sPrefix.'_laststart', $sPrefix.'_stopped');
  3861. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3862. {
  3863. $sThPrefix = '_'.$iThreshold;
  3864. $aExpectedCols[] = $sPrefix.$sThPrefix.'_deadline';
  3865. $aExpectedCols[] = $sPrefix.$sThPrefix.'_passed';
  3866. $aExpectedCols[] = $sPrefix.$sThPrefix.'_triggered';
  3867. $aExpectedCols[] = $sPrefix.$sThPrefix.'_overrun';
  3868. }
  3869. foreach ($aExpectedCols as $sExpectedCol)
  3870. {
  3871. if (!array_key_exists($sExpectedCol, $aCols))
  3872. {
  3873. $sAvailable = implode(', ', array_keys($aCols));
  3874. throw new MissingColumnException("Missing column '$sExpectedCol' from {$sAvailable}");
  3875. }
  3876. }
  3877. $value = new ormStopWatch(
  3878. $aCols[$sPrefix],
  3879. self::DateToSeconds($aCols[$sPrefix.'_started']),
  3880. self::DateToSeconds($aCols[$sPrefix.'_laststart']),
  3881. self::DateToSeconds($aCols[$sPrefix.'_stopped'])
  3882. );
  3883. $aThresholds = array();
  3884. foreach ($this->ListThresholds() as $iThreshold => $aDefinition)
  3885. {
  3886. $sThPrefix = '_'.$iThreshold;
  3887. $value->DefineThreshold(
  3888. $iThreshold,
  3889. self::DateToSeconds($aCols[$sPrefix.$sThPrefix.'_deadline']),
  3890. (bool)($aCols[$sPrefix.$sThPrefix.'_passed'] == 1),
  3891. (bool)($aCols[$sPrefix.$sThPrefix.'_triggered'] == 1),
  3892. $aCols[$sPrefix.$sThPrefix.'_overrun'],
  3893. array_key_exists('highlight', $aDefinition) ? $aDefinition['highlight'] : null
  3894. );
  3895. }
  3896. return $value;
  3897. }
  3898. public function GetSQLValues($value)
  3899. {
  3900. if ($value instanceOf ormStopWatch)
  3901. {
  3902. $aValues = array();
  3903. $aValues[$this->GetCode().'_timespent'] = $value->GetTimeSpent();
  3904. $aValues[$this->GetCode().'_started'] = self::SecondsToDate($value->GetStartDate());
  3905. $aValues[$this->GetCode().'_laststart'] = self::SecondsToDate($value->GetLastStartDate());
  3906. $aValues[$this->GetCode().'_stopped'] = self::SecondsToDate($value->GetStopDate());
  3907. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3908. {
  3909. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3910. $aValues[$sPrefix.'_deadline'] = self::SecondsToDate($value->GetThresholdDate($iThreshold));
  3911. $aValues[$sPrefix.'_passed'] = $value->IsThresholdPassed($iThreshold) ? '1' : '0';
  3912. $aValues[$sPrefix.'_triggered'] = $value->IsThresholdTriggered($iThreshold) ? '1' : '0';
  3913. $aValues[$sPrefix.'_overrun'] = $value->GetOverrun($iThreshold);
  3914. }
  3915. }
  3916. else
  3917. {
  3918. $aValues = array();
  3919. $aValues[$this->GetCode().'_timespent'] = '';
  3920. $aValues[$this->GetCode().'_started'] = '';
  3921. $aValues[$this->GetCode().'_laststart'] = '';
  3922. $aValues[$this->GetCode().'_stopped'] = '';
  3923. }
  3924. return $aValues;
  3925. }
  3926. public function GetSQLColumns($bFullSpec = false)
  3927. {
  3928. $aColumns = array();
  3929. $aColumns[$this->GetCode().'_timespent'] = 'INT(11) UNSIGNED';
  3930. $aColumns[$this->GetCode().'_started'] = 'DATETIME';
  3931. $aColumns[$this->GetCode().'_laststart'] = 'DATETIME';
  3932. $aColumns[$this->GetCode().'_stopped'] = 'DATETIME';
  3933. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3934. {
  3935. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3936. $aColumns[$sPrefix.'_deadline'] = 'DATETIME';
  3937. $aColumns[$sPrefix.'_passed'] = 'TINYINT(1) UNSIGNED';
  3938. $aColumns[$sPrefix.'_triggered'] = 'TINYINT(1)';
  3939. $aColumns[$sPrefix.'_overrun'] = 'INT(11) UNSIGNED';
  3940. }
  3941. return $aColumns;
  3942. }
  3943. public function GetFilterDefinitions()
  3944. {
  3945. $aRes = array(
  3946. $this->GetCode() => new FilterFromAttribute($this),
  3947. $this->GetCode().'_started' => new FilterFromAttribute($this, '_started'),
  3948. $this->GetCode().'_laststart' => new FilterFromAttribute($this, '_laststart'),
  3949. $this->GetCode().'_stopped' => new FilterFromAttribute($this, '_stopped')
  3950. );
  3951. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3952. {
  3953. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3954. $aRes[$sPrefix.'_deadline'] = new FilterFromAttribute($this, '_deadline');
  3955. $aRes[$sPrefix.'_passed'] = new FilterFromAttribute($this, '_passed');
  3956. $aRes[$sPrefix.'_triggered'] = new FilterFromAttribute($this, '_triggered');
  3957. $aRes[$sPrefix.'_overrun'] = new FilterFromAttribute($this, '_overrun');
  3958. }
  3959. return $aRes;
  3960. }
  3961. public function GetBasicFilterOperators()
  3962. {
  3963. return array();
  3964. }
  3965. public function GetBasicFilterLooseOperator()
  3966. {
  3967. return '=';
  3968. }
  3969. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3970. {
  3971. return 'true';
  3972. }
  3973. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3974. {
  3975. if (is_object($value))
  3976. {
  3977. return $value->GetAsHTML($this, $oHostObject);
  3978. }
  3979. }
  3980. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  3981. {
  3982. return $value->GetTimeSpent();
  3983. }
  3984. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3985. {
  3986. return $value->GetTimeSpent();
  3987. }
  3988. public function ListThresholds()
  3989. {
  3990. return $this->Get('thresholds');
  3991. }
  3992. public function Fingerprint($value)
  3993. {
  3994. $sFingerprint = '';
  3995. if (is_object($value))
  3996. {
  3997. $sFingerprint = $value->GetAsHTML($this);
  3998. }
  3999. return $sFingerprint;
  4000. }
  4001. /**
  4002. * To expose internal values: Declare an attribute AttributeSubItem
  4003. * and implement the GetSubItemXXXX verbs
  4004. */
  4005. public function GetSubItemSQLExpression($sItemCode)
  4006. {
  4007. $sPrefix = $this->GetCode();
  4008. switch($sItemCode)
  4009. {
  4010. case 'timespent':
  4011. return array('' => $sPrefix.'_timespent');
  4012. case 'started':
  4013. return array('' => $sPrefix.'_started');
  4014. case 'laststart':
  4015. return array('' => $sPrefix.'_laststart');
  4016. case 'stopped':
  4017. return array('' => $sPrefix.'_stopped');
  4018. }
  4019. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4020. {
  4021. $sThPrefix = $iThreshold.'_';
  4022. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4023. {
  4024. // The current threshold is concerned
  4025. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4026. switch($sThresholdCode)
  4027. {
  4028. case 'deadline':
  4029. return array('' => $sPrefix.'_'.$iThreshold.'_deadline');
  4030. case 'passed':
  4031. return array('' => $sPrefix.'_'.$iThreshold.'_passed');
  4032. case 'triggered':
  4033. return array('' => $sPrefix.'_'.$iThreshold.'_triggered');
  4034. case 'overrun':
  4035. return array('' => $sPrefix.'_'.$iThreshold.'_overrun');
  4036. }
  4037. }
  4038. }
  4039. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  4040. }
  4041. public function GetSubItemValue($sItemCode, $value, $oHostObject = null)
  4042. {
  4043. $oStopWatch = $value;
  4044. switch($sItemCode)
  4045. {
  4046. case 'timespent':
  4047. return $oStopWatch->GetTimeSpent();
  4048. case 'started':
  4049. return $oStopWatch->GetStartDate();
  4050. case 'laststart':
  4051. return $oStopWatch->GetLastStartDate();
  4052. case 'stopped':
  4053. return $oStopWatch->GetStopDate();
  4054. }
  4055. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4056. {
  4057. $sThPrefix = $iThreshold.'_';
  4058. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4059. {
  4060. // The current threshold is concerned
  4061. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4062. switch($sThresholdCode)
  4063. {
  4064. case 'deadline':
  4065. return $oStopWatch->GetThresholdDate($iThreshold);
  4066. case 'passed':
  4067. return $oStopWatch->IsThresholdPassed($iThreshold);
  4068. case 'triggered':
  4069. return $oStopWatch->IsThresholdTriggered($iThreshold);
  4070. case 'overrun':
  4071. return $oStopWatch->GetOverrun($iThreshold);
  4072. }
  4073. }
  4074. }
  4075. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  4076. }
  4077. protected function GetBooleanLabel($bValue)
  4078. {
  4079. $sDictKey = $bValue ? 'yes' : 'no';
  4080. return Dict::S('BooleanLabel:'.$sDictKey, 'def:'.$sDictKey);
  4081. }
  4082. public function GetSubItemAsHTMLForHistory($sItemCode, $sValue)
  4083. {
  4084. switch($sItemCode)
  4085. {
  4086. case 'timespent':
  4087. $sHtml = (int)$sValue ? Str::pure2html(AttributeDuration::FormatDuration($sValue)) : null;
  4088. break;
  4089. case 'started':
  4090. case 'laststart':
  4091. case 'stopped':
  4092. $sHtml = (int)$sValue ? date(self::GetDateFormat(), (int)$sValue) : null;
  4093. break;
  4094. default:
  4095. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4096. {
  4097. $sThPrefix = $iThreshold.'_';
  4098. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4099. {
  4100. // The current threshold is concerned
  4101. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4102. switch($sThresholdCode)
  4103. {
  4104. case 'deadline':
  4105. $sHtml = (int)$sValue ? date(self::GetDateFormat(true /*full*/), (int)$sValue) : null;
  4106. break;
  4107. case 'passed':
  4108. $sHtml = $this->GetBooleanLabel((int)$sValue);
  4109. break;
  4110. case 'triggered':
  4111. $sHtml = $this->GetBooleanLabel((int)$sValue);
  4112. break;
  4113. case 'overrun':
  4114. $sHtml = (int)$sValue > 0 ? Str::pure2html(AttributeDuration::FormatDuration((int)$sValue)) : '';
  4115. }
  4116. }
  4117. }
  4118. }
  4119. return $sHtml;
  4120. }
  4121. static protected function GetDateFormat($bFull = false)
  4122. {
  4123. if ($bFull)
  4124. {
  4125. return "Y-m-d H:i:s";
  4126. }
  4127. else
  4128. {
  4129. return "Y-m-d H:i";
  4130. }
  4131. }
  4132. public function GetSubItemAsHTML($sItemCode, $value)
  4133. {
  4134. $sHtml = $value;
  4135. switch($sItemCode)
  4136. {
  4137. case 'timespent':
  4138. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  4139. break;
  4140. case 'started':
  4141. case 'laststart':
  4142. case 'stopped':
  4143. if (is_null($value))
  4144. {
  4145. $sHtml = ''; // Undefined
  4146. }
  4147. else
  4148. {
  4149. $sHtml = date(self::GetDateFormat(), $value);
  4150. }
  4151. break;
  4152. default:
  4153. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4154. {
  4155. $sThPrefix = $iThreshold.'_';
  4156. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4157. {
  4158. // The current threshold is concerned
  4159. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4160. switch($sThresholdCode)
  4161. {
  4162. case 'deadline':
  4163. if ($value)
  4164. {
  4165. $sDate = date(self::GetDateFormat(true /*full*/), $value);
  4166. $sHtml = Str::pure2html(AttributeDeadline::FormatDeadline($sDate));
  4167. }
  4168. else
  4169. {
  4170. $sHtml = '';
  4171. }
  4172. break;
  4173. case 'passed':
  4174. case 'triggered':
  4175. $sHtml = $this->GetBooleanLabel($value);
  4176. break;
  4177. case 'overrun':
  4178. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  4179. break;
  4180. }
  4181. }
  4182. }
  4183. }
  4184. return $sHtml;
  4185. }
  4186. public function GetSubItemAsCSV($sItemCode, $value, $sSeparator = ',', $sTextQualifier = '"')
  4187. {
  4188. $sFrom = array("\r\n", $sTextQualifier);
  4189. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4190. $sEscaped = str_replace($sFrom, $sTo, (string)$value);
  4191. $sRet = $sTextQualifier.$sEscaped.$sTextQualifier;
  4192. switch($sItemCode)
  4193. {
  4194. case 'timespent':
  4195. case 'started':
  4196. case 'laststart':
  4197. case 'stopped':
  4198. break;
  4199. default:
  4200. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4201. {
  4202. $sThPrefix = $iThreshold.'_';
  4203. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4204. {
  4205. // The current threshold is concerned
  4206. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4207. switch($sThresholdCode)
  4208. {
  4209. case 'deadline':
  4210. if ($value != '')
  4211. {
  4212. $sRet = $sTextQualifier.date(self::GetDateFormat(true /*full*/), $value).$sTextQualifier;
  4213. }
  4214. break;
  4215. case 'passed':
  4216. case 'triggered':
  4217. $sRet = $sTextQualifier.$this->GetBooleanLabel($value).$sTextQualifier;
  4218. break;
  4219. case 'overrun':
  4220. break;
  4221. }
  4222. }
  4223. }
  4224. }
  4225. return $sRet;
  4226. }
  4227. public function GetSubItemAsXML($sItemCode, $value)
  4228. {
  4229. $sRet = Str::pure2xml((string)$value);
  4230. switch($sItemCode)
  4231. {
  4232. case 'timespent':
  4233. case 'started':
  4234. case 'laststart':
  4235. case 'stopped':
  4236. break;
  4237. default:
  4238. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4239. {
  4240. $sThPrefix = $iThreshold.'_';
  4241. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4242. {
  4243. // The current threshold is concerned
  4244. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4245. switch($sThresholdCode)
  4246. {
  4247. case 'deadline':
  4248. break;
  4249. case 'passed':
  4250. case 'triggered':
  4251. $sRet = $this->GetBooleanLabel($value);
  4252. break;
  4253. case 'overrun':
  4254. break;
  4255. }
  4256. }
  4257. }
  4258. }
  4259. return $sRet;
  4260. }
  4261. /**
  4262. * Implemented for the HTML spreadsheet format!
  4263. */
  4264. public function GetSubItemAsEditValue($sItemCode, $value)
  4265. {
  4266. $sRet = $value;
  4267. switch($sItemCode)
  4268. {
  4269. case 'timespent':
  4270. break;
  4271. case 'started':
  4272. case 'laststart':
  4273. case 'stopped':
  4274. if (is_null($value))
  4275. {
  4276. $sRet = ''; // Undefined
  4277. }
  4278. else
  4279. {
  4280. $sRet = date(self::GetDateFormat(), $value);
  4281. }
  4282. break;
  4283. default:
  4284. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4285. {
  4286. $sThPrefix = $iThreshold.'_';
  4287. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4288. {
  4289. // The current threshold is concerned
  4290. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4291. switch($sThresholdCode)
  4292. {
  4293. case 'deadline':
  4294. if ($value)
  4295. {
  4296. $sRet = date(self::GetDateFormat(true /*full*/), $value);
  4297. }
  4298. else
  4299. {
  4300. $sRet = '';
  4301. }
  4302. break;
  4303. case 'passed':
  4304. case 'triggered':
  4305. $sRet = $this->GetBooleanLabel($value);
  4306. break;
  4307. case 'overrun':
  4308. break;
  4309. }
  4310. }
  4311. }
  4312. }
  4313. return $sRet;
  4314. }
  4315. }
  4316. /**
  4317. * View of a subvalue of another attribute
  4318. * If an attribute implements the verbs GetSubItem.... then it can expose
  4319. * internal values, each of them being an attribute and therefore they
  4320. * can be displayed at different times in the object lifecycle, and used for
  4321. * reporting (as a condition in OQL, or as an additional column in an export)
  4322. * Known usages: Stop Watches can expose threshold statuses
  4323. */
  4324. class AttributeSubItem extends AttributeDefinition
  4325. {
  4326. static public function ListExpectedParams()
  4327. {
  4328. return array_merge(parent::ListExpectedParams(), array('target_attcode', 'item_code'));
  4329. }
  4330. public function GetParentAttCode() {return $this->Get("target_attcode");}
  4331. /**
  4332. * Helper : get the attribute definition to which the execution will be forwarded
  4333. */
  4334. public function GetTargetAttDef()
  4335. {
  4336. $sClass = $this->GetHostClass();
  4337. $oParentAttDef = MetaModel::GetAttributeDef($sClass, $this->Get('target_attcode'));
  4338. return $oParentAttDef;
  4339. }
  4340. public function GetEditClass() {return "";}
  4341. public function GetValuesDef() {return null;}
  4342. //public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  4343. public function IsDirectField() {return true;}
  4344. public function IsScalar() {return true;}
  4345. public function IsWritable() {return false;}
  4346. public function GetDefaultValue() {return null;}
  4347. // public function IsNullAllowed() {return false;}
  4348. public function LoadInObject() {return false;} // if this verb returns true, then GetValue must be implemented
  4349. //
  4350. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  4351. public function FromSQLToValue($aCols, $sPrefix = '')
  4352. {
  4353. }
  4354. public function GetSQLColumns($bFullSpec = false)
  4355. {
  4356. return array();
  4357. }
  4358. public function GetFilterDefinitions()
  4359. {
  4360. return array($this->GetCode() => new FilterFromAttribute($this));
  4361. }
  4362. public function GetBasicFilterOperators()
  4363. {
  4364. return array();
  4365. }
  4366. public function GetBasicFilterLooseOperator()
  4367. {
  4368. return "=";
  4369. }
  4370. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4371. {
  4372. $sQValue = CMDBSource::Quote($value);
  4373. switch ($sOpCode)
  4374. {
  4375. case '!=':
  4376. return $this->GetSQLExpr()." != $sQValue";
  4377. break;
  4378. case '=':
  4379. default:
  4380. return $this->GetSQLExpr()." = $sQValue";
  4381. }
  4382. }
  4383. public function GetSQLExpressions($sPrefix = '')
  4384. {
  4385. $oParent = $this->GetTargetAttDef();
  4386. $res = $oParent->GetSubItemSQLExpression($this->Get('item_code'));
  4387. return $res;
  4388. }
  4389. /**
  4390. * Used by DBOBject::Get()
  4391. */
  4392. public function GetValue($parentValue, $oHostObject = null)
  4393. {
  4394. $oParent = $this->GetTargetAttDef();
  4395. $res = $oParent->GetSubItemValue($this->Get('item_code'), $parentValue, $oHostObject);
  4396. return $res;
  4397. }
  4398. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4399. {
  4400. $oParent = $this->GetTargetAttDef();
  4401. $res = $oParent->GetSubItemAsHTML($this->Get('item_code'), $value);
  4402. return $res;
  4403. }
  4404. public function GetAsHTMLForHistory($value, $oHostObject = null, $bLocalize = true)
  4405. {
  4406. $oParent = $this->GetTargetAttDef();
  4407. $res = $oParent->GetSubItemAsHTMLForHistory($this->Get('item_code'), $value);
  4408. return $res;
  4409. }
  4410. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4411. {
  4412. $oParent = $this->GetTargetAttDef();
  4413. $res = $oParent->GetSubItemAsCSV($this->Get('item_code'), $value, $sSeparator, $sTextQualifier);
  4414. return $res;
  4415. }
  4416. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4417. {
  4418. $oParent = $this->GetTargetAttDef();
  4419. $res = $oParent->GetSubItemAsXML($this->Get('item_code'), $value);
  4420. return $res;
  4421. }
  4422. /**
  4423. * As of now, this function must be implemented to have the value in spreadsheet format
  4424. */
  4425. public function GetEditValue($value, $oHostObj = null)
  4426. {
  4427. $oParent = $this->GetTargetAttDef();
  4428. $res = $oParent->GetSubItemAsEditValue($this->Get('item_code'), $value);
  4429. return $res;
  4430. }
  4431. public function IsPartOfFingerprint() { return false; }
  4432. }
  4433. /**
  4434. * One way encrypted (hashed) password
  4435. */
  4436. class AttributeOneWayPassword extends AttributeDefinition
  4437. {
  4438. static public function ListExpectedParams()
  4439. {
  4440. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  4441. }
  4442. public function GetEditClass() {return "One Way Password";}
  4443. public function IsDirectField() {return true;}
  4444. public function IsScalar() {return true;}
  4445. public function IsWritable() {return true;}
  4446. public function GetDefaultValue() {return "";}
  4447. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  4448. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  4449. public function MakeRealValue($proposedValue, $oHostObj)
  4450. {
  4451. $oPassword = $proposedValue;
  4452. if (!is_object($oPassword))
  4453. {
  4454. $oPassword = new ormPassword('', '');
  4455. $oPassword->SetPassword($proposedValue);
  4456. }
  4457. return $oPassword;
  4458. }
  4459. public function GetSQLExpressions($sPrefix = '')
  4460. {
  4461. if ($sPrefix == '')
  4462. {
  4463. $sPrefix = $this->GetCode();
  4464. }
  4465. $aColumns = array();
  4466. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  4467. $aColumns[''] = $sPrefix.'_hash';
  4468. $aColumns['_salt'] = $sPrefix.'_salt';
  4469. return $aColumns;
  4470. }
  4471. public function FromSQLToValue($aCols, $sPrefix = '')
  4472. {
  4473. if (!array_key_exists($sPrefix, $aCols))
  4474. {
  4475. $sAvailable = implode(', ', array_keys($aCols));
  4476. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4477. }
  4478. $hashed = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  4479. if (!array_key_exists($sPrefix.'_salt', $aCols))
  4480. {
  4481. $sAvailable = implode(', ', array_keys($aCols));
  4482. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  4483. }
  4484. $sSalt = isset($aCols[$sPrefix.'_salt']) ? $aCols[$sPrefix.'_salt'] : '';
  4485. $value = new ormPassword($hashed, $sSalt);
  4486. return $value;
  4487. }
  4488. public function GetSQLValues($value)
  4489. {
  4490. // #@# Optimization: do not load blobs anytime
  4491. // As per mySQL doc, selecting blob columns will prevent mySQL from
  4492. // using memory in case a temporary table has to be created
  4493. // (temporary tables created on disk)
  4494. // We will have to remove the blobs from the list of attributes when doing the select
  4495. // then the use of Get() should finalize the load
  4496. if ($value instanceOf ormPassword)
  4497. {
  4498. $aValues = array();
  4499. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  4500. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  4501. }
  4502. else
  4503. {
  4504. $aValues = array();
  4505. $aValues[$this->GetCode().'_hash'] = '';
  4506. $aValues[$this->GetCode().'_salt'] = '';
  4507. }
  4508. return $aValues;
  4509. }
  4510. public function GetSQLColumns($bFullSpec = false)
  4511. {
  4512. $aColumns = array();
  4513. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  4514. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  4515. return $aColumns;
  4516. }
  4517. public function GetImportColumns()
  4518. {
  4519. $aColumns = array();
  4520. $aColumns[$this->GetCode()] = 'TINYTEXT';
  4521. return $aColumns;
  4522. }
  4523. public function FromImportToValue($aCols, $sPrefix = '')
  4524. {
  4525. if (!isset($aCols[$sPrefix]))
  4526. {
  4527. $sAvailable = implode(', ', array_keys($aCols));
  4528. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4529. }
  4530. $sClearPwd = $aCols[$sPrefix];
  4531. $oPassword = new ormPassword('', '');
  4532. $oPassword->SetPassword($sClearPwd);
  4533. return $oPassword;
  4534. }
  4535. public function GetFilterDefinitions()
  4536. {
  4537. return array();
  4538. // still not working... see later...
  4539. }
  4540. public function GetBasicFilterOperators()
  4541. {
  4542. return array();
  4543. }
  4544. public function GetBasicFilterLooseOperator()
  4545. {
  4546. return '=';
  4547. }
  4548. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4549. {
  4550. return 'true';
  4551. }
  4552. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4553. {
  4554. if (is_object($value))
  4555. {
  4556. return $value->GetAsHTML();
  4557. }
  4558. }
  4559. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4560. {
  4561. return ''; // Not exportable in CSV
  4562. }
  4563. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4564. {
  4565. return ''; // Not exportable in XML
  4566. }
  4567. }
  4568. // Indexed array having two dimensions
  4569. class AttributeTable extends AttributeDBField
  4570. {
  4571. public function GetEditClass() {return "Table";}
  4572. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  4573. public function GetMaxSize()
  4574. {
  4575. return null;
  4576. }
  4577. public function GetNullValue()
  4578. {
  4579. return array();
  4580. }
  4581. public function IsNull($proposedValue)
  4582. {
  4583. return (count($proposedValue) == 0);
  4584. }
  4585. public function GetEditValue($sValue, $oHostObj = null)
  4586. {
  4587. return '';
  4588. }
  4589. // Facilitate things: allow the user to Set the value from a string
  4590. public function MakeRealValue($proposedValue, $oHostObj)
  4591. {
  4592. if (is_null($proposedValue))
  4593. {
  4594. return array();
  4595. }
  4596. else if (!is_array($proposedValue))
  4597. {
  4598. return array(0 => array(0 => $proposedValue));
  4599. }
  4600. return $proposedValue;
  4601. }
  4602. public function FromSQLToValue($aCols, $sPrefix = '')
  4603. {
  4604. try
  4605. {
  4606. $value = @unserialize($aCols[$sPrefix.'']);
  4607. if ($value === false)
  4608. {
  4609. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  4610. }
  4611. }
  4612. catch(Exception $e)
  4613. {
  4614. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  4615. }
  4616. return $value;
  4617. }
  4618. public function GetSQLValues($value)
  4619. {
  4620. $aValues = array();
  4621. $aValues[$this->Get("sql")] = serialize($value);
  4622. return $aValues;
  4623. }
  4624. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4625. {
  4626. if (!is_array($value))
  4627. {
  4628. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  4629. }
  4630. if (count($value) == 0)
  4631. {
  4632. return "";
  4633. }
  4634. $sRes = "<TABLE class=\"listResults\">";
  4635. $sRes .= "<TBODY>";
  4636. foreach($value as $iRow => $aRawData)
  4637. {
  4638. $sRes .= "<TR>";
  4639. foreach ($aRawData as $iCol => $cell)
  4640. {
  4641. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  4642. $sRes .= "<TD>$sCell</TD>";
  4643. }
  4644. $sRes .= "</TR>";
  4645. }
  4646. $sRes .= "</TBODY>";
  4647. $sRes .= "</TABLE>";
  4648. return $sRes;
  4649. }
  4650. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4651. {
  4652. // Not implemented
  4653. return '';
  4654. }
  4655. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4656. {
  4657. if (count($value) == 0)
  4658. {
  4659. return "";
  4660. }
  4661. $sRes = "";
  4662. foreach($value as $iRow => $aRawData)
  4663. {
  4664. $sRes .= "<row>";
  4665. foreach ($aRawData as $iCol => $cell)
  4666. {
  4667. $sCell = Str::pure2xml((string)$cell);
  4668. $sRes .= "<cell icol=\"$iCol\">$sCell</cell>";
  4669. }
  4670. $sRes .= "</row>";
  4671. }
  4672. return $sRes;
  4673. }
  4674. }
  4675. // The PHP value is a hash array, it is stored as a TEXT column
  4676. class AttributePropertySet extends AttributeTable
  4677. {
  4678. public function GetEditClass() {return "PropertySet";}
  4679. // Facilitate things: allow the user to Set the value from a string
  4680. public function MakeRealValue($proposedValue, $oHostObj)
  4681. {
  4682. if (!is_array($proposedValue))
  4683. {
  4684. return array('?' => (string)$proposedValue);
  4685. }
  4686. return $proposedValue;
  4687. }
  4688. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4689. {
  4690. if (!is_array($value))
  4691. {
  4692. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  4693. }
  4694. if (count($value) == 0)
  4695. {
  4696. return "";
  4697. }
  4698. $sRes = "<TABLE class=\"listResults\">";
  4699. $sRes .= "<TBODY>";
  4700. foreach($value as $sProperty => $sValue)
  4701. {
  4702. if ($sProperty == 'auth_pwd')
  4703. {
  4704. $sValue = '*****';
  4705. }
  4706. $sRes .= "<TR>";
  4707. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  4708. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  4709. $sRes .= "</TR>";
  4710. }
  4711. $sRes .= "</TBODY>";
  4712. $sRes .= "</TABLE>";
  4713. return $sRes;
  4714. }
  4715. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4716. {
  4717. if (count($value) == 0)
  4718. {
  4719. return "";
  4720. }
  4721. $aRes = array();
  4722. foreach($value as $sProperty => $sValue)
  4723. {
  4724. if ($sProperty == 'auth_pwd')
  4725. {
  4726. $sValue = '*****';
  4727. }
  4728. $sFrom = array(',', '=');
  4729. $sTo = array('\,', '\=');
  4730. $aRes[] = $sProperty.'='.str_replace($sFrom, $sTo, (string)$sValue);
  4731. }
  4732. $sRaw = implode(',', $aRes);
  4733. $sFrom = array("\r\n", $sTextQualifier);
  4734. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4735. $sEscaped = str_replace($sFrom, $sTo, $sRaw);
  4736. return $sTextQualifier.$sEscaped.$sTextQualifier;
  4737. }
  4738. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4739. {
  4740. if (count($value) == 0)
  4741. {
  4742. return "";
  4743. }
  4744. $sRes = "";
  4745. foreach($value as $sProperty => $sValue)
  4746. {
  4747. if ($sProperty == 'auth_pwd')
  4748. {
  4749. $sValue = '*****';
  4750. }
  4751. $sRes .= "<property id=\"$sProperty\">";
  4752. $sRes .= Str::pure2xml((string)$sValue);
  4753. $sRes .= "</property>";
  4754. }
  4755. return $sRes;
  4756. }
  4757. }
  4758. /**
  4759. * The attribute dedicated to the friendly name automatic attribute (not written)
  4760. *
  4761. * @package iTopORM
  4762. */
  4763. class AttributeComputedFieldVoid extends AttributeDefinition
  4764. {
  4765. static public function ListExpectedParams()
  4766. {
  4767. return array_merge(parent::ListExpectedParams(), array());
  4768. }
  4769. public function GetEditClass() {return "";}
  4770. public function GetValuesDef() {return null;}
  4771. public function GetPrerequisiteAttributes() {return $this->GetOptional("depends_on", array());}
  4772. public function IsDirectField() {return true;}
  4773. public function IsScalar() {return true;}
  4774. public function IsWritable() {return false;}
  4775. public function GetSQLExpr() {return null;}
  4776. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  4777. public function IsNullAllowed() {return false;}
  4778. //
  4779. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  4780. public function GetSQLExpressions($sPrefix = '')
  4781. {
  4782. if ($sPrefix == '')
  4783. {
  4784. $sPrefix = $this->GetCode();
  4785. }
  4786. return array('' => $sPrefix);
  4787. }
  4788. public function FromSQLToValue($aCols, $sPrefix = '')
  4789. {
  4790. return null;
  4791. }
  4792. public function GetSQLValues($value)
  4793. {
  4794. return array();
  4795. }
  4796. public function GetSQLColumns($bFullSpec = false)
  4797. {
  4798. return array();
  4799. }
  4800. public function GetFilterDefinitions()
  4801. {
  4802. return array($this->GetCode() => new FilterFromAttribute($this));
  4803. }
  4804. public function GetBasicFilterOperators()
  4805. {
  4806. return array("="=>"equals", "!="=>"differs from");
  4807. }
  4808. public function GetBasicFilterLooseOperator()
  4809. {
  4810. return "=";
  4811. }
  4812. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4813. {
  4814. $sQValue = CMDBSource::Quote($value);
  4815. switch ($sOpCode)
  4816. {
  4817. case '!=':
  4818. return $this->GetSQLExpr()." != $sQValue";
  4819. break;
  4820. case '=':
  4821. default:
  4822. return $this->GetSQLExpr()." = $sQValue";
  4823. }
  4824. }
  4825. public function IsPartOfFingerprint() { return false; }
  4826. }
  4827. /**
  4828. * The attribute dedicated to the friendly name automatic attribute (not written)
  4829. *
  4830. * @package iTopORM
  4831. */
  4832. class AttributeFriendlyName extends AttributeComputedFieldVoid
  4833. {
  4834. public function __construct($sCode, $sExtKeyAttCode)
  4835. {
  4836. $this->m_sCode = $sCode;
  4837. $aParams = array();
  4838. // $aParams["is_null_allowed"] = false,
  4839. $aParams["default_value"] = '';
  4840. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  4841. parent::__construct($sCode, $aParams);
  4842. $this->m_sValue = $this->Get("default_value");
  4843. }
  4844. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  4845. public function GetExtAttCode() {return 'friendlyname';}
  4846. public function GetLabel($sDefault = null)
  4847. {
  4848. $sLabel = parent::GetLabel('');
  4849. if (strlen($sLabel) == 0)
  4850. {
  4851. $sKeyAttCode = $this->Get("extkey_attcode");
  4852. if ($sKeyAttCode == 'id')
  4853. {
  4854. return Dict::S('Core:FriendlyName-Label');
  4855. }
  4856. else
  4857. {
  4858. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  4859. $sLabel = $oExtKeyAttDef->GetLabel($this->m_sCode);
  4860. }
  4861. }
  4862. return $sLabel;
  4863. }
  4864. public function GetDescription($sDefault = null)
  4865. {
  4866. $sLabel = parent::GetDescription('');
  4867. if (strlen($sLabel) == 0)
  4868. {
  4869. $sKeyAttCode = $this->Get("extkey_attcode");
  4870. if ($sKeyAttCode == 'id')
  4871. {
  4872. return Dict::S('Core:FriendlyName-Description');
  4873. }
  4874. else
  4875. {
  4876. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  4877. $sLabel = $oExtKeyAttDef->GetDescription('');
  4878. }
  4879. }
  4880. return $sLabel;
  4881. }
  4882. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  4883. protected function GetSQLCol($bFullSpec = false) {return "";}
  4884. public function FromSQLToValue($aCols, $sPrefix = '')
  4885. {
  4886. $sValue = $aCols[$sPrefix];
  4887. return $sValue;
  4888. }
  4889. /**
  4890. * Encrypt the value before storing it in the database
  4891. */
  4892. public function GetSQLValues($value)
  4893. {
  4894. return array();
  4895. }
  4896. public function IsWritable()
  4897. {
  4898. return false;
  4899. }
  4900. public function IsDirectField()
  4901. {
  4902. return false;
  4903. }
  4904. public function SetFixedValue($sValue)
  4905. {
  4906. $this->m_sValue = $sValue;
  4907. }
  4908. public function GetDefaultValue()
  4909. {
  4910. return $this->m_sValue;
  4911. }
  4912. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  4913. {
  4914. return Str::pure2html((string)$sValue);
  4915. }
  4916. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  4917. {
  4918. $sFrom = array("\r\n", $sTextQualifier);
  4919. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4920. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  4921. return $sTextQualifier.$sEscaped.$sTextQualifier;
  4922. }
  4923. // Do not display friendly names in the history of change
  4924. public function DescribeChangeAsHTML($sOldValue, $sNewValue, $sLabel = null)
  4925. {
  4926. return '';
  4927. }
  4928. public function GetBasicFilterLooseOperator()
  4929. {
  4930. return "Contains";
  4931. }
  4932. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4933. {
  4934. $sQValue = CMDBSource::Quote($value);
  4935. switch ($sOpCode)
  4936. {
  4937. case '=':
  4938. case '!=':
  4939. return $this->GetSQLExpr()." $sOpCode $sQValue";
  4940. case 'Contains':
  4941. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  4942. case 'NotLike':
  4943. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  4944. case 'Like':
  4945. default:
  4946. return $this->GetSQLExpr()." LIKE $sQValue";
  4947. }
  4948. }
  4949. public function IsPartOfFingerprint() { return false; }
  4950. }
  4951. /**
  4952. * Holds the setting for the redundancy on a specific relation
  4953. * Its value is a string, containing either:
  4954. * - 'disabled'
  4955. * - 'n', where n is a positive integer value giving the minimum count of items upstream
  4956. * - 'n%', where n is a positive integer value, giving the minimum as a percentage of the total count of items upstream
  4957. *
  4958. * @package iTopORM
  4959. */
  4960. class AttributeRedundancySettings extends AttributeDBField
  4961. {
  4962. static public function ListExpectedParams()
  4963. {
  4964. return array('sql', 'relation_code', 'from_class', 'neighbour_id', 'enabled', 'enabled_mode', 'min_up', 'min_up_type', 'min_up_mode');
  4965. }
  4966. public function GetValuesDef() {return null;}
  4967. public function GetPrerequisiteAttributes() {return array();}
  4968. public function GetEditClass() {return "RedundancySetting";}
  4969. protected function GetSQLCol($bFullSpec = false)
  4970. {
  4971. return "VARCHAR(20)".($bFullSpec ? $this->GetSQLColSpec() : '');
  4972. }
  4973. public function GetValidationPattern()
  4974. {
  4975. return "^[0-9]{1,3}|[0-9]{1,2}%|disabled$";
  4976. }
  4977. public function GetMaxSize()
  4978. {
  4979. return 20;
  4980. }
  4981. public function GetDefaultValue($aArgs = array())
  4982. {
  4983. $sRet = 'disabled';
  4984. if ($this->Get('enabled'))
  4985. {
  4986. if ($this->Get('min_up_type') == 'count')
  4987. {
  4988. $sRet = (string) $this->Get('min_up');
  4989. }
  4990. else // percent
  4991. {
  4992. $sRet = $this->Get('min_up').'%';
  4993. }
  4994. }
  4995. return $sRet;
  4996. }
  4997. public function IsNullAllowed()
  4998. {
  4999. return false;
  5000. }
  5001. public function GetNullValue()
  5002. {
  5003. return '';
  5004. }
  5005. public function IsNull($proposedValue)
  5006. {
  5007. return ($proposedValue == '');
  5008. }
  5009. public function MakeRealValue($proposedValue, $oHostObj)
  5010. {
  5011. if (is_null($proposedValue)) return '';
  5012. return (string)$proposedValue;
  5013. }
  5014. public function ScalarToSQL($value)
  5015. {
  5016. if (!is_string($value))
  5017. {
  5018. throw new CoreException('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetHostClass(), 'attribute' => $this->GetCode()));
  5019. }
  5020. return $value;
  5021. }
  5022. public function GetRelationQueryData()
  5023. {
  5024. foreach (MetaModel::EnumRelationQueries($this->GetHostClass(), $this->Get('relation_code'), false) as $sDummy => $aQueryInfo)
  5025. {
  5026. if ($aQueryInfo['sFromClass'] == $this->Get('from_class'))
  5027. {
  5028. if ($aQueryInfo['sNeighbour'] == $this->Get('neighbour_id'))
  5029. {
  5030. return $aQueryInfo;
  5031. }
  5032. }
  5033. }
  5034. }
  5035. /**
  5036. * Find the user option label
  5037. * @param user option : disabled|cout|percent
  5038. */
  5039. public function GetUserOptionFormat($sUserOption, $sDefault = null)
  5040. {
  5041. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, null, true /*user lang*/);
  5042. if (is_null($sLabel))
  5043. {
  5044. // If no default value is specified, let's define the most relevant one for developping purposes
  5045. if (is_null($sDefault))
  5046. {
  5047. $sDefault = str_replace('_', ' ', $this->m_sCode.':'.$sUserOption.'(%1$s)');
  5048. }
  5049. // Browse the hierarchy again, accepting default (english) translations
  5050. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, $sDefault, false);
  5051. }
  5052. return $sLabel;
  5053. }
  5054. /**
  5055. * Override to display the value in the GUI
  5056. */
  5057. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  5058. {
  5059. $sCurrentOption = $this->GetCurrentOption($sValue);
  5060. $sClass = $oHostObject ? get_class($oHostObject) : $this->m_sHostClass;
  5061. return sprintf($this->GetUserOptionFormat($sCurrentOption), $this->GetMinUpValue($sValue), MetaModel::GetName($sClass));
  5062. }
  5063. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true)
  5064. {
  5065. $sFrom = array("\r\n", $sTextQualifier);
  5066. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5067. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  5068. return $sTextQualifier.$sEscaped.$sTextQualifier;
  5069. }
  5070. /**
  5071. * Helper to interpret the value, given the current settings and string representation of the attribute
  5072. */
  5073. public function IsEnabled($sValue)
  5074. {
  5075. if ($this->get('enabled_mode') == 'fixed')
  5076. {
  5077. $bRet = $this->get('enabled');
  5078. }
  5079. else
  5080. {
  5081. $bRet = ($sValue != 'disabled');
  5082. }
  5083. return $bRet;
  5084. }
  5085. /**
  5086. * Helper to interpret the value, given the current settings and string representation of the attribute
  5087. */
  5088. public function GetMinUpType($sValue)
  5089. {
  5090. if ($this->get('min_up_mode') == 'fixed')
  5091. {
  5092. $sRet = $this->get('min_up_type');
  5093. }
  5094. else
  5095. {
  5096. $sRet = 'count';
  5097. if (substr(trim($sValue), -1, 1) == '%')
  5098. {
  5099. $sRet = 'percent';
  5100. }
  5101. }
  5102. return $sRet;
  5103. }
  5104. /**
  5105. * Helper to interpret the value, given the current settings and string representation of the attribute
  5106. */
  5107. public function GetMinUpValue($sValue)
  5108. {
  5109. if ($this->get('min_up_mode') == 'fixed')
  5110. {
  5111. $iRet = (int) $this->Get('min_up');
  5112. }
  5113. else
  5114. {
  5115. $sRefValue = $sValue;
  5116. if (substr(trim($sValue), -1, 1) == '%')
  5117. {
  5118. $sRefValue = substr(trim($sValue), 0, -1);
  5119. }
  5120. $iRet = (int) trim($sRefValue);
  5121. }
  5122. return $iRet;
  5123. }
  5124. /**
  5125. * Helper to determine if the redundancy can be viewed/edited by the end-user
  5126. */
  5127. public function IsVisible()
  5128. {
  5129. $bRet = false;
  5130. if ($this->Get('enabled_mode') == 'fixed')
  5131. {
  5132. $bRet = $this->Get('enabled');
  5133. }
  5134. elseif ($this->Get('enabled_mode') == 'user')
  5135. {
  5136. $bRet = true;
  5137. }
  5138. return $bRet;
  5139. }
  5140. public function IsWritable()
  5141. {
  5142. if (($this->Get('enabled_mode') == 'fixed') && ($this->Get('min_up_mode') == 'fixed'))
  5143. {
  5144. return false;
  5145. }
  5146. return true;
  5147. }
  5148. /**
  5149. * Returns an HTML form that can be read by ReadValueFromPostedForm
  5150. */
  5151. public function GetDisplayForm($sCurrentValue, $oPage, $bEditMode = false, $sFormPrefix = '')
  5152. {
  5153. $sRet = '';
  5154. $aUserOptions = $this->GetUserOptions($sCurrentValue);
  5155. if (count($aUserOptions) < 2)
  5156. {
  5157. $bEditOption = false;
  5158. }
  5159. else
  5160. {
  5161. $bEditOption = $bEditMode;
  5162. }
  5163. $sCurrentOption = $this->GetCurrentOption($sCurrentValue);
  5164. foreach($aUserOptions as $sUserOption)
  5165. {
  5166. $bSelected = ($sUserOption == $sCurrentOption);
  5167. $sRet .= '<div>';
  5168. $sRet .= $this->GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditOption, $sUserOption, $bSelected);
  5169. $sRet .= '</div>';
  5170. }
  5171. return $sRet;
  5172. }
  5173. const USER_OPTION_DISABLED = 'disabled';
  5174. const USER_OPTION_ENABLED_COUNT = 'count';
  5175. const USER_OPTION_ENABLED_PERCENT = 'percent';
  5176. /**
  5177. * Depending on the xxx_mode parameters, build the list of options that are allowed to the end-user
  5178. */
  5179. protected function GetUserOptions($sValue)
  5180. {
  5181. $aRet = array();
  5182. if ($this->Get('enabled_mode') == 'user')
  5183. {
  5184. $aRet[] = self::USER_OPTION_DISABLED;
  5185. }
  5186. if ($this->Get('min_up_mode') == 'user')
  5187. {
  5188. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  5189. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  5190. }
  5191. else
  5192. {
  5193. if ($this->GetMinUpType($sValue) == 'count')
  5194. {
  5195. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  5196. }
  5197. else
  5198. {
  5199. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  5200. }
  5201. }
  5202. return $aRet;
  5203. }
  5204. /**
  5205. * Convert the string representation into one of the existing options
  5206. */
  5207. protected function GetCurrentOption($sValue)
  5208. {
  5209. $sRet = self::USER_OPTION_DISABLED;
  5210. if ($this->IsEnabled($sValue))
  5211. {
  5212. if ($this->GetMinUpType($sValue) == 'count')
  5213. {
  5214. $sRet = self::USER_OPTION_ENABLED_COUNT;
  5215. }
  5216. else
  5217. {
  5218. $sRet = self::USER_OPTION_ENABLED_PERCENT;
  5219. }
  5220. }
  5221. return $sRet;
  5222. }
  5223. /**
  5224. * Display an option (form, or current value)
  5225. */
  5226. protected function GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditMode, $sUserOption, $bSelected = true)
  5227. {
  5228. $sRet = '';
  5229. $iCurrentValue = $this->GetMinUpValue($sCurrentValue);
  5230. if ($bEditMode)
  5231. {
  5232. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  5233. switch ($sUserOption)
  5234. {
  5235. case self::USER_OPTION_DISABLED:
  5236. $sValue = ''; // Empty placeholder
  5237. break;
  5238. case self::USER_OPTION_ENABLED_COUNT:
  5239. if ($bEditMode)
  5240. {
  5241. $sName = $sHtmlNamesPrefix.'_min_up_count';
  5242. $sEditValue = $bSelected ? $iCurrentValue : '';
  5243. $sValue = '<input class="redundancy-min-up-count" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  5244. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  5245. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  5246. }
  5247. else
  5248. {
  5249. $sValue = $iCurrentValue;
  5250. }
  5251. break;
  5252. case self::USER_OPTION_ENABLED_PERCENT:
  5253. if ($bEditMode)
  5254. {
  5255. $sName = $sHtmlNamesPrefix.'_min_up_percent';
  5256. $sEditValue = $bSelected ? $iCurrentValue : '';
  5257. $sValue = '<input class="redundancy-min-up-percent" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  5258. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  5259. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  5260. }
  5261. else
  5262. {
  5263. $sValue = $iCurrentValue;
  5264. }
  5265. break;
  5266. }
  5267. $sLabel = sprintf($this->GetUserOptionFormat($sUserOption), $sValue, MetaModel::GetName($this->GetHostClass()));
  5268. $sOptionName = $sHtmlNamesPrefix.'_user_option';
  5269. $sOptionId = $sOptionName.'_'.$sUserOption;
  5270. $sChecked = $bSelected ? 'checked' : '';
  5271. $sRet = '<input type="radio" name="'.$sOptionName.'" id="'.$sOptionId.'" value="'.$sUserOption.'"'.$sChecked.'> <label for="'.$sOptionId.'">'.$sLabel.'</label>';
  5272. }
  5273. else
  5274. {
  5275. // Read-only: display only the currently selected option
  5276. if ($bSelected)
  5277. {
  5278. $sRet = sprintf($this->GetUserOptionFormat($sUserOption), $iCurrentValue, MetaModel::GetName($this->GetHostClass()));
  5279. }
  5280. }
  5281. return $sRet;
  5282. }
  5283. /**
  5284. * Makes the string representation out of the values given by the form defined in GetDisplayForm
  5285. */
  5286. public function ReadValueFromPostedForm($sFormPrefix)
  5287. {
  5288. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  5289. $iMinUpCount = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_count', null, 'raw_data');
  5290. $iMinUpPercent = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_percent', null, 'raw_data');
  5291. $sSelectedOption = utils::ReadPostedParam($sHtmlNamesPrefix.'_user_option', null, 'raw_data');
  5292. switch ($sSelectedOption)
  5293. {
  5294. case self::USER_OPTION_ENABLED_COUNT:
  5295. $sRet = $iMinUpCount;
  5296. break;
  5297. case self::USER_OPTION_ENABLED_PERCENT:
  5298. $sRet = $iMinUpPercent.'%';
  5299. break;
  5300. case self::USER_OPTION_DISABLED:
  5301. default:
  5302. $sRet = 'disabled';
  5303. break;
  5304. }
  5305. return $sRet;
  5306. }
  5307. }