attributedef.class.inc.php 163 KB

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