attributedef.class.inc.php 174 KB

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