attributedef.class.inc.php 201 KB

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