attributedef.class.inc.php 163 KB

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