attributedef.class.inc.php 201 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230
  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. if (($sValue !== null) && ($sValue !== ''))
  2242. {
  2243. $sValue = HTMLSanitizer::Sanitize($sValue);
  2244. }
  2245. break;
  2246. case 'text':
  2247. default:
  2248. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  2249. {
  2250. foreach($aAllMatches as $iPos => $aMatches)
  2251. {
  2252. $sClassLabel = $aMatches[1];
  2253. $sName = $aMatches[2];
  2254. if (!MetaModel::IsValidClass($sClassLabel))
  2255. {
  2256. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  2257. if ($sClass)
  2258. {
  2259. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  2260. }
  2261. }
  2262. }
  2263. }
  2264. }
  2265. return $sValue;
  2266. }
  2267. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2268. {
  2269. return Str::pure2xml($value);
  2270. }
  2271. public function GetWidth()
  2272. {
  2273. return $this->GetOptional('width', '');
  2274. }
  2275. public function GetHeight()
  2276. {
  2277. return $this->GetOptional('height', '');
  2278. }
  2279. static public function GetFormFieldClass()
  2280. {
  2281. return '\\Combodo\\iTop\\Form\\Field\\TextAreaField';
  2282. }
  2283. public function MakeFormField(DBObject $oObject, $oFormField = null)
  2284. {
  2285. if ($oFormField === null)
  2286. {
  2287. $sFormFieldClass = static::GetFormFieldClass();
  2288. $oFormField = new $sFormFieldClass($this->GetCode(), null, $oObject);
  2289. $oFormField->SetFormat($this->GetFormat());
  2290. }
  2291. parent::MakeFormField($oObject, $oFormField);
  2292. return $oFormField;
  2293. }
  2294. /**
  2295. * The actual formatting of the field: either text (=plain text) or html (= text with HTML markup)
  2296. * @return string
  2297. */
  2298. public function GetFormat()
  2299. {
  2300. return $this->GetOptional('format', 'text');
  2301. }
  2302. /**
  2303. * Read the value from the row returned by the SQL query and transorms it to the appropriate
  2304. * internal format (either text or html)
  2305. * @see AttributeDBFieldVoid::FromSQLToValue()
  2306. */
  2307. public function FromSQLToValue($aCols, $sPrefix = '')
  2308. {
  2309. $value = $aCols[$sPrefix.''];
  2310. if ($this->GetOptional('format', null) != null )
  2311. {
  2312. // Read from the extra column only if the property 'format' is specified for the attribute
  2313. $sFormat = $aCols[$sPrefix.'_format'];
  2314. }
  2315. else
  2316. {
  2317. $sFormat = $this->GetFormat();
  2318. }
  2319. switch($sFormat)
  2320. {
  2321. case 'text':
  2322. if ($this->GetFormat() == 'html')
  2323. {
  2324. $value = utils::TextToHtml($value);
  2325. }
  2326. break;
  2327. case 'html':
  2328. if ($this->GetFormat() == 'text')
  2329. {
  2330. $value = utils::HtmlToText($value);
  2331. }
  2332. else
  2333. {
  2334. $value = InlineImage::FixUrls((string)$value);
  2335. }
  2336. break;
  2337. default:
  2338. // unknown format ??
  2339. }
  2340. return $value;
  2341. }
  2342. public function GetSQLValues($value)
  2343. {
  2344. $aValues = array();
  2345. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  2346. if ($this->GetOptional('format', null) != null )
  2347. {
  2348. // Add the extra column only if the property 'format' is specified for the attribute
  2349. $aValues[$this->Get("sql").'_format'] = $this->GetFormat();
  2350. }
  2351. return $aValues;
  2352. }
  2353. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  2354. {
  2355. switch($this->GetFormat())
  2356. {
  2357. case 'html':
  2358. if ($bConvertToPlainText)
  2359. {
  2360. $sValue = utils::HtmlToText((string)$sValue);
  2361. }
  2362. $sFrom = array("\r\n", $sTextQualifier);
  2363. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  2364. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  2365. return $sTextQualifier.$sEscaped.$sTextQualifier;
  2366. break;
  2367. case 'text':
  2368. default:
  2369. return parent::GetAsCSV($sValue, $sSeparator, $sTextQualifier, $oHostObject, $bLocalize, $bConvertToPlainText);
  2370. }
  2371. }
  2372. }
  2373. /**
  2374. * Map a log to an attribute
  2375. *
  2376. * @package iTopORM
  2377. */
  2378. class AttributeLongText extends AttributeText
  2379. {
  2380. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  2381. public function GetMaxSize()
  2382. {
  2383. // Is there a way to know the current limitation for mysql?
  2384. // See mysql_field_len()
  2385. return 65535*1024; // Limited... still 64 Mb!
  2386. }
  2387. }
  2388. /**
  2389. * An attibute that stores a case log (i.e journal)
  2390. *
  2391. * @package iTopORM
  2392. */
  2393. class AttributeCaseLog extends AttributeLongText
  2394. {
  2395. public function GetNullValue()
  2396. {
  2397. return '';
  2398. }
  2399. public function IsNull($proposedValue)
  2400. {
  2401. if (!($proposedValue instanceof ormCaseLog))
  2402. {
  2403. return ($proposedValue == '');
  2404. }
  2405. return ($proposedValue->GetText() == '');
  2406. }
  2407. public function ScalarToSQL($value)
  2408. {
  2409. if (!is_string($value) && !is_null($value))
  2410. {
  2411. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  2412. }
  2413. return $value;
  2414. }
  2415. public function GetEditClass() {return "CaseLog";}
  2416. public function GetEditValue($sValue, $oHostObj = null)
  2417. {
  2418. if (!($sValue instanceOf ormCaseLog))
  2419. {
  2420. return '';
  2421. }
  2422. return $sValue->GetModifiedEntry();
  2423. }
  2424. /**
  2425. * For fields containing a potential markup, return the value without this markup
  2426. * @return string
  2427. */
  2428. public function GetAsPlainText($value, $oHostObj = null)
  2429. {
  2430. $value = $oObj->Get($sAttCode);
  2431. if ($value instanceOf ormCaseLog)
  2432. {
  2433. return $value->GetAsPlainText();
  2434. }
  2435. else
  2436. {
  2437. return (string) $value;
  2438. }
  2439. }
  2440. public function GetDefaultValue(DBObject $oHostObject = null) {return new ormCaseLog();}
  2441. public function Equals($val1, $val2) {return ($val1->GetText() == $val2->GetText());}
  2442. // Facilitate things: allow the user to Set the value from a string
  2443. public function MakeRealValue($proposedValue, $oHostObj)
  2444. {
  2445. if ($proposedValue instanceof ormCaseLog)
  2446. {
  2447. // Passthrough
  2448. $ret = $proposedValue;
  2449. }
  2450. else
  2451. {
  2452. // Append the new value if an instance of the object is supplied
  2453. //
  2454. $oPreviousLog = null;
  2455. if ($oHostObj != null)
  2456. {
  2457. $oPreviousLog = $oHostObj->Get($this->GetCode());
  2458. if (!is_object($oPreviousLog))
  2459. {
  2460. $oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
  2461. }
  2462. }
  2463. if (is_object($oPreviousLog))
  2464. {
  2465. $oCaseLog = clone($oPreviousLog);
  2466. }
  2467. else
  2468. {
  2469. $oCaseLog = new ormCaseLog();
  2470. }
  2471. if ($proposedValue instanceof stdClass)
  2472. {
  2473. $oCaseLog->AddLogEntryFromJSON($proposedValue);
  2474. }
  2475. else
  2476. {
  2477. if (strlen($proposedValue) > 0)
  2478. {
  2479. $oCaseLog->AddLogEntry($proposedValue);
  2480. }
  2481. }
  2482. $ret = $oCaseLog;
  2483. }
  2484. return $ret;
  2485. }
  2486. public function GetSQLExpressions($sPrefix = '')
  2487. {
  2488. if ($sPrefix == '')
  2489. {
  2490. $sPrefix = $this->Get('sql');
  2491. }
  2492. $aColumns = array();
  2493. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2494. $aColumns[''] = $sPrefix;
  2495. $aColumns['_index'] = $sPrefix.'_index';
  2496. return $aColumns;
  2497. }
  2498. public function FromSQLToValue($aCols, $sPrefix = '')
  2499. {
  2500. if (!array_key_exists($sPrefix, $aCols))
  2501. {
  2502. $sAvailable = implode(', ', array_keys($aCols));
  2503. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2504. }
  2505. $sLog = $aCols[$sPrefix];
  2506. if (isset($aCols[$sPrefix.'_index']))
  2507. {
  2508. $sIndex = $aCols[$sPrefix.'_index'];
  2509. }
  2510. else
  2511. {
  2512. // For backward compatibility, allow the current state to be: 1 log, no index
  2513. $sIndex = '';
  2514. }
  2515. if (strlen($sIndex) > 0)
  2516. {
  2517. $aIndex = unserialize($sIndex);
  2518. $value = new ormCaseLog($sLog, $aIndex);
  2519. }
  2520. else
  2521. {
  2522. $value = new ormCaseLog($sLog);
  2523. }
  2524. return $value;
  2525. }
  2526. public function GetSQLValues($value)
  2527. {
  2528. if (!($value instanceOf ormCaseLog))
  2529. {
  2530. $value = new ormCaseLog('');
  2531. }
  2532. $aValues = array();
  2533. $aValues[$this->GetCode()] = $value->GetText();
  2534. $aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
  2535. return $aValues;
  2536. }
  2537. public function GetSQLColumns($bFullSpec = false)
  2538. {
  2539. $aColumns = array();
  2540. $aColumns[$this->GetCode()] = 'LONGTEXT'; // 2^32 (4 Gb)
  2541. $aColumns[$this->GetCode().'_index'] = 'BLOB';
  2542. return $aColumns;
  2543. }
  2544. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2545. {
  2546. if ($value instanceOf ormCaseLog)
  2547. {
  2548. $sContent = $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
  2549. }
  2550. else
  2551. {
  2552. $sContent = '';
  2553. }
  2554. $aStyles = array();
  2555. if ($this->GetWidth() != '')
  2556. {
  2557. $aStyles[] = 'width:'.$this->GetWidth();
  2558. }
  2559. if ($this->GetHeight() != '')
  2560. {
  2561. $aStyles[] = 'height:'.$this->GetHeight();
  2562. }
  2563. $sStyle = '';
  2564. if (count($aStyles) > 0)
  2565. {
  2566. $sStyle = 'style="'.implode(';', $aStyles).'"';
  2567. }
  2568. return "<div class=\"caselog\" $sStyle>".$sContent.'</div>'; }
  2569. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  2570. {
  2571. if ($value instanceOf ormCaseLog)
  2572. {
  2573. return parent::GetAsCSV($value->GetText($bConvertToPlainText), $sSeparator, $sTextQualifier, $oHostObject, $bLocalize, $bConvertToPlainText);
  2574. }
  2575. else
  2576. {
  2577. return '';
  2578. }
  2579. }
  2580. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2581. {
  2582. if ($value instanceOf ormCaseLog)
  2583. {
  2584. return parent::GetAsXML($value->GetText(), $oHostObject, $bLocalize);
  2585. }
  2586. else
  2587. {
  2588. return '';
  2589. }
  2590. }
  2591. /**
  2592. * List the available verbs for 'GetForTemplate'
  2593. */
  2594. public function EnumTemplateVerbs()
  2595. {
  2596. return array(
  2597. '' => 'Plain text representation of all the log entries',
  2598. 'head' => 'Plain text representation of the latest entry',
  2599. 'head_html' => 'HTML representation of the latest entry',
  2600. 'html' => 'HTML representation of all the log entries',
  2601. );
  2602. }
  2603. /**
  2604. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  2605. * @param $value mixed The current value of the field
  2606. * @param $sVerb string The verb specifying the representation of the value
  2607. * @param $oHostObject DBObject The object
  2608. * @param $bLocalize bool Whether or not to localize the value
  2609. */
  2610. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  2611. {
  2612. switch($sVerb)
  2613. {
  2614. case '':
  2615. return $value->GetText();
  2616. case 'head':
  2617. return $value->GetLatestEntry('text');
  2618. case 'head_html':
  2619. return $value->GetLatestEntry('html');
  2620. case 'html':
  2621. return $value->GetAsEmailHtml();
  2622. default:
  2623. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObj));
  2624. }
  2625. }
  2626. /**
  2627. * Helper to get a value that will be JSON encoded
  2628. * The operation is the opposite to FromJSONToValue
  2629. */
  2630. public function GetForJSON($value)
  2631. {
  2632. return $value->GetForJSON();
  2633. }
  2634. /**
  2635. * Helper to form a value, given JSON decoded data
  2636. * The operation is the opposite to GetForJSON
  2637. */
  2638. public function FromJSONToValue($json)
  2639. {
  2640. if (is_string($json))
  2641. {
  2642. // Will be correctly handled in MakeRealValue
  2643. $ret = $json;
  2644. }
  2645. else
  2646. {
  2647. if (isset($json->add_item))
  2648. {
  2649. // Will be correctly handled in MakeRealValue
  2650. $ret = $json->add_item;
  2651. if (!isset($ret->message))
  2652. {
  2653. throw new Exception("Missing mandatory entry: 'message'");
  2654. }
  2655. }
  2656. else
  2657. {
  2658. $ret = ormCaseLog::FromJSON($json);
  2659. }
  2660. }
  2661. return $ret;
  2662. }
  2663. public function Fingerprint($value)
  2664. {
  2665. $sFingerprint = '';
  2666. if ($value instanceOf ormCaseLog)
  2667. {
  2668. $sFingerprint = $value->GetText();
  2669. }
  2670. return $sFingerprint;
  2671. }
  2672. /**
  2673. * The actual formatting of the text: either text (=plain text) or html (= text with HTML markup)
  2674. * @return string
  2675. */
  2676. public function GetFormat()
  2677. {
  2678. return $this->GetOptional('format', 'html'); // default format for case logs is now HTML
  2679. }
  2680. static public function GetFormFieldClass()
  2681. {
  2682. return '\\Combodo\\iTop\\Form\\Field\\CaseLogField';
  2683. }
  2684. public function MakeFormField(DBObject $oObject, $oFormField = null)
  2685. {
  2686. // First we call the parent so the field is build
  2687. $oFormField = parent::MakeFormField($oObject, $oFormField);
  2688. // Then only we set the value
  2689. $oFormField->SetCurrentValue($this->GetEditValue($oObject->Get($this->GetCode())));
  2690. // And we set the entries
  2691. $oFormField->SetEntries($oObject->Get($this->GetCode())->GetAsArray());
  2692. return $oFormField;
  2693. }
  2694. }
  2695. /**
  2696. * Map a text column (size > ?), containing HTML code, to an attribute
  2697. *
  2698. * @package iTopORM
  2699. */
  2700. class AttributeHTML extends AttributeLongText
  2701. {
  2702. public function GetSQLColumns($bFullSpec = false)
  2703. {
  2704. $aColumns = array();
  2705. $aColumns[$this->Get('sql')] = $this->GetSQLCol();
  2706. if ($this->GetOptional('format', null) != null )
  2707. {
  2708. // Add the extra column only if the property 'format' is specified for the attribute
  2709. $aColumns[$this->Get('sql').'_format'] = "ENUM('text','html')";
  2710. if ($bFullSpec)
  2711. {
  2712. $aColumns[$this->Get('sql').'_format'].= " DEFAULT 'html'"; // default 'html' is for migrating old records
  2713. }
  2714. }
  2715. return $aColumns;
  2716. }
  2717. /**
  2718. * The actual formatting of the text: either text (=plain text) or html (= text with HTML markup)
  2719. * @return string
  2720. */
  2721. public function GetFormat()
  2722. {
  2723. return $this->GetOptional('format', 'html'); // Defaults to HTML
  2724. }
  2725. }
  2726. /**
  2727. * Specialization of a string: email
  2728. *
  2729. * @package iTopORM
  2730. */
  2731. class AttributeEmailAddress extends AttributeString
  2732. {
  2733. public function GetValidationPattern()
  2734. {
  2735. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('email_validation_pattern').'$');
  2736. }
  2737. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2738. {
  2739. if (empty($sValue)) return '';
  2740. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  2741. }
  2742. }
  2743. /**
  2744. * Specialization of a string: IP address
  2745. *
  2746. * @package iTopORM
  2747. */
  2748. class AttributeIPAddress extends AttributeString
  2749. {
  2750. public function GetValidationPattern()
  2751. {
  2752. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  2753. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  2754. }
  2755. public function GetOrderBySQLExpressions($sClassAlias)
  2756. {
  2757. // Note: This is the responsibility of this function to place backticks around column aliases
  2758. return array('INET_ATON(`'.$sClassAlias.$this->GetCode().'`)');
  2759. }
  2760. }
  2761. /**
  2762. * Specialization of a string: OQL expression
  2763. *
  2764. * @package iTopORM
  2765. */
  2766. class AttributeOQL extends AttributeText
  2767. {
  2768. public function GetEditClass() {return "OQLExpression";}
  2769. }
  2770. /**
  2771. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2772. *
  2773. * @package iTopORM
  2774. */
  2775. class AttributeTemplateString extends AttributeString
  2776. {
  2777. }
  2778. /**
  2779. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2780. *
  2781. * @package iTopORM
  2782. */
  2783. class AttributeTemplateText extends AttributeText
  2784. {
  2785. }
  2786. /**
  2787. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2788. *
  2789. * @package iTopORM
  2790. */
  2791. class AttributeTemplateHTML extends AttributeText
  2792. {
  2793. public function GetSQLColumns($bFullSpec = false)
  2794. {
  2795. $aColumns = array();
  2796. $aColumns[$this->Get('sql')] = $this->GetSQLCol();
  2797. if ($this->GetOptional('format', null) != null )
  2798. {
  2799. // Add the extra column only if the property 'format' is specified for the attribute
  2800. $aColumns[$this->Get('sql').'_format'] = "ENUM('text','html')";
  2801. if ($bFullSpec)
  2802. {
  2803. $aColumns[$this->Get('sql').'_format'].= " DEFAULT 'html'"; // default 'html' is for migrating old records
  2804. }
  2805. }
  2806. return $aColumns;
  2807. }
  2808. /**
  2809. * The actual formatting of the text: either text (=plain text) or html (= text with HTML markup)
  2810. * @return string
  2811. */
  2812. public function GetFormat()
  2813. {
  2814. return $this->GetOptional('format', 'html'); // Defaults to HTML
  2815. }
  2816. }
  2817. /**
  2818. * Map a enum column to an attribute
  2819. *
  2820. * @package iTopORM
  2821. */
  2822. class AttributeEnum extends AttributeString
  2823. {
  2824. static public function ListExpectedParams()
  2825. {
  2826. return parent::ListExpectedParams();
  2827. //return array_merge(parent::ListExpectedParams(), array());
  2828. }
  2829. public function GetEditClass() {return "String";}
  2830. protected function GetSQLCol($bFullSpec = false)
  2831. {
  2832. $oValDef = $this->GetValuesDef();
  2833. if ($oValDef)
  2834. {
  2835. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  2836. }
  2837. else
  2838. {
  2839. $aValues = array();
  2840. }
  2841. if (count($aValues) > 0)
  2842. {
  2843. // The syntax used here do matters
  2844. // In particular, I had to remove unnecessary spaces to
  2845. // make sure that this string will match the field type returned by the DB
  2846. // (used to perform a comparison between the current DB format and the data model)
  2847. return "ENUM(".implode(",", $aValues).")".($bFullSpec ? $this->GetSQLColSpec() : '');
  2848. }
  2849. else
  2850. {
  2851. return "VARCHAR(255)".($bFullSpec ? " DEFAULT ''" : ""); // ENUM() is not an allowed syntax!
  2852. }
  2853. }
  2854. protected function GetSQLColSpec()
  2855. {
  2856. $default = $this->ScalarToSQL($this->GetDefaultValue());
  2857. if (is_null($default))
  2858. {
  2859. $sRet = '';
  2860. }
  2861. else
  2862. {
  2863. // ENUMs values are strings so the default value must be a string as well,
  2864. // otherwise MySQL interprets the number as the zero-based index of the value in the list (i.e. the nth value in the list)
  2865. $sRet = " DEFAULT ".CMDBSource::Quote($default);
  2866. }
  2867. return $sRet;
  2868. }
  2869. public function ScalarToSQL($value)
  2870. {
  2871. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  2872. // but that wasn't working for enums, because '' is NOT one of the allowed values
  2873. // that's why a null value must be forced to a real null
  2874. $value = parent::ScalarToSQL($value);
  2875. if ($this->IsNull($value))
  2876. {
  2877. return null;
  2878. }
  2879. else
  2880. {
  2881. return $value;
  2882. }
  2883. }
  2884. public function RequiresIndex()
  2885. {
  2886. return false;
  2887. }
  2888. public function GetBasicFilterOperators()
  2889. {
  2890. return parent::GetBasicFilterOperators();
  2891. }
  2892. public function GetBasicFilterLooseOperator()
  2893. {
  2894. return '=';
  2895. }
  2896. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2897. {
  2898. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2899. }
  2900. public function GetValueLabel($sValue)
  2901. {
  2902. if (is_null($sValue))
  2903. {
  2904. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2905. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  2906. }
  2907. else
  2908. {
  2909. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, null, true /*user lang*/);
  2910. if (is_null($sLabel))
  2911. {
  2912. $sDefault = str_replace('_', ' ', $sValue);
  2913. // Browse the hierarchy again, accepting default (english) translations
  2914. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, $sDefault, false);
  2915. }
  2916. }
  2917. return $sLabel;
  2918. }
  2919. public function GetValueDescription($sValue)
  2920. {
  2921. if (is_null($sValue))
  2922. {
  2923. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2924. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', Dict::S('Enum:Undefined'));
  2925. }
  2926. else
  2927. {
  2928. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', '', true /* user language only */);
  2929. if (strlen($sDescription) == 0)
  2930. {
  2931. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  2932. if ($sParentClass)
  2933. {
  2934. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  2935. {
  2936. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  2937. $sDescription = $oAttDef->GetValueDescription($sValue);
  2938. }
  2939. }
  2940. }
  2941. }
  2942. return $sDescription;
  2943. }
  2944. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2945. {
  2946. if ($bLocalize)
  2947. {
  2948. $sLabel = $this->GetValueLabel($sValue);
  2949. $sDescription = $this->GetValueDescription($sValue);
  2950. // later, we could imagine a detailed description in the title
  2951. $sRes = "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  2952. }
  2953. else
  2954. {
  2955. $sRes = parent::GetAsHtml($sValue, $oHostObject, $bLocalize);
  2956. }
  2957. return $sRes;
  2958. }
  2959. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2960. {
  2961. if (is_null($value))
  2962. {
  2963. $sFinalValue = '';
  2964. }
  2965. elseif ($bLocalize)
  2966. {
  2967. $sFinalValue = $this->GetValueLabel($value);
  2968. }
  2969. else
  2970. {
  2971. $sFinalValue = $value;
  2972. }
  2973. $sRes = parent::GetAsXML($sFinalValue, $oHostObject, $bLocalize);
  2974. return $sRes;
  2975. }
  2976. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  2977. {
  2978. if (is_null($sValue))
  2979. {
  2980. $sFinalValue = '';
  2981. }
  2982. elseif ($bLocalize)
  2983. {
  2984. $sFinalValue = $this->GetValueLabel($sValue);
  2985. }
  2986. else
  2987. {
  2988. $sFinalValue = $sValue;
  2989. }
  2990. $sRes = parent::GetAsCSV($sFinalValue, $sSeparator, $sTextQualifier, $oHostObject, $bLocalize);
  2991. return $sRes;
  2992. }
  2993. static public function GetFormFieldClass()
  2994. {
  2995. return '\\Combodo\\iTop\\Form\\Field\\SelectField';
  2996. }
  2997. public function MakeFormField(DBObject $oObject, $oFormField = null)
  2998. {
  2999. if ($oFormField === null)
  3000. {
  3001. // TODO : We should check $this->Get('display_style') and create a Radio / Select / ... regarding its value
  3002. $sFormFieldClass = static::GetFormFieldClass();
  3003. $oFormField = new $sFormFieldClass($this->GetCode());
  3004. }
  3005. $oFormField->SetChoices($this->GetAllowedValues($oObject->ToArgsForQuery()));
  3006. parent::MakeFormField($oObject, $oFormField);
  3007. return $oFormField;
  3008. }
  3009. public function GetEditValue($sValue, $oHostObj = null)
  3010. {
  3011. if (is_null($sValue))
  3012. {
  3013. return '';
  3014. }
  3015. else
  3016. {
  3017. return $this->GetValueLabel($sValue);
  3018. }
  3019. }
  3020. /**
  3021. * Helper to get a value that will be JSON encoded
  3022. * The operation is the opposite to FromJSONToValue
  3023. */
  3024. public function GetForJSON($value)
  3025. {
  3026. return $value;
  3027. }
  3028. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3029. {
  3030. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  3031. if (is_null($aRawValues)) return null;
  3032. $aLocalizedValues = array();
  3033. foreach ($aRawValues as $sKey => $sValue)
  3034. {
  3035. $aLocalizedValues[$sKey] = Str::pure2html($this->GetValueLabel($sKey));
  3036. }
  3037. return $aLocalizedValues;
  3038. }
  3039. /**
  3040. * An enum can be localized
  3041. */
  3042. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  3043. {
  3044. if ($bLocalizedValue)
  3045. {
  3046. // Lookup for the value matching the input
  3047. //
  3048. $sFoundValue = null;
  3049. $aRawValues = parent::GetAllowedValues();
  3050. if (!is_null($aRawValues))
  3051. {
  3052. foreach ($aRawValues as $sKey => $sValue)
  3053. {
  3054. $sRefValue = $this->GetValueLabel($sKey);
  3055. if ($sProposedValue == $sRefValue)
  3056. {
  3057. $sFoundValue = $sKey;
  3058. break;
  3059. }
  3060. }
  3061. }
  3062. if (is_null($sFoundValue))
  3063. {
  3064. return null;
  3065. }
  3066. return $this->MakeRealValue($sFoundValue, null);
  3067. }
  3068. else
  3069. {
  3070. return parent::MakeValueFromString($sProposedValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue, $sAttributeQualifier);
  3071. }
  3072. }
  3073. /**
  3074. * Processes the input value to align it with the values supported
  3075. * by this type of attribute. In this case: turns empty strings into nulls
  3076. * @param mixed $proposedValue The value to be set for the attribute
  3077. * @return mixed The actual value that will be set
  3078. */
  3079. public function MakeRealValue($proposedValue, $oHostObj)
  3080. {
  3081. if ($proposedValue == '') return null;
  3082. return parent::MakeRealValue($proposedValue, $oHostObj);
  3083. }
  3084. public function GetOrderByHint()
  3085. {
  3086. $aValues = $this->GetAllowedValues();
  3087. return Dict::Format('UI:OrderByHint_Values', implode(', ', $aValues));
  3088. }
  3089. }
  3090. /**
  3091. * A meta enum is an aggregation of enum from subclasses into an enum of a base class
  3092. * It has been designed is to cope with the fact that statuses must be defined in leaf classes, while it makes sense to
  3093. * have a superstatus available on the root classe(s)
  3094. *
  3095. * @package iTopORM
  3096. */
  3097. class AttributeMetaEnum extends AttributeEnum
  3098. {
  3099. static public function ListExpectedParams()
  3100. {
  3101. return array('allowed_values', 'sql', 'default_value', 'mapping');
  3102. }
  3103. public function IsNullAllowed()
  3104. {
  3105. return false; // Well... this actually depends on the mapping
  3106. }
  3107. public function IsWritable()
  3108. {
  3109. return false;
  3110. }
  3111. public function RequiresIndex()
  3112. {
  3113. return true;
  3114. }
  3115. public function GetPrerequisiteAttributes($sClass = null)
  3116. {
  3117. if (is_null($sClass))
  3118. {
  3119. $sClass = $this->GetHostClass();
  3120. }
  3121. $aMappingData = $this->GetMapRule($sClass);
  3122. if ($aMappingData == null)
  3123. {
  3124. $aRet = array();
  3125. }
  3126. else
  3127. {
  3128. $aRet = array($aMappingData['attcode']);
  3129. }
  3130. return $aRet;
  3131. }
  3132. /**
  3133. * Overload the standard so as to leave the data unsorted
  3134. *
  3135. * @param array $aArgs
  3136. * @param string $sContains
  3137. * @return array|null
  3138. */
  3139. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3140. {
  3141. $oValSetDef = $this->GetValuesDef();
  3142. if (!$oValSetDef) return null;
  3143. $aRawValues = $oValSetDef->GetValueList();
  3144. if (is_null($aRawValues)) return null;
  3145. $aLocalizedValues = array();
  3146. foreach ($aRawValues as $sKey => $sValue)
  3147. {
  3148. $aLocalizedValues[$sKey] = Str::pure2html($this->GetValueLabel($sKey));
  3149. }
  3150. return $aLocalizedValues;
  3151. }
  3152. /**
  3153. * Returns the meta value for the given object.
  3154. * See also MetaModel::RebuildMetaEnums() that must be maintained when MapValue changes
  3155. *
  3156. * @param $oObject
  3157. * @return mixed
  3158. * @throws Exception
  3159. */
  3160. public function MapValue($oObject)
  3161. {
  3162. $aMappingData = $this->GetMapRule(get_class($oObject));
  3163. if ($aMappingData == null)
  3164. {
  3165. $sRet = $this->GetDefaultValue();
  3166. }
  3167. else
  3168. {
  3169. $sAttCode = $aMappingData['attcode'];
  3170. $value = $oObject->Get($sAttCode);
  3171. if (array_key_exists($value, $aMappingData['values']))
  3172. {
  3173. $sRet = $aMappingData['values'][$value];
  3174. }
  3175. elseif ($this->GetDefaultValue() != '')
  3176. {
  3177. $sRet = $this->GetDefaultValue();
  3178. }
  3179. else
  3180. {
  3181. 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());
  3182. }
  3183. }
  3184. return $sRet;
  3185. }
  3186. public function GetMapRule($sClass)
  3187. {
  3188. $aMappings = $this->Get('mapping');
  3189. if (array_key_exists($sClass, $aMappings))
  3190. {
  3191. $aMappingData = $aMappings[$sClass];
  3192. }
  3193. else
  3194. {
  3195. $sParent = MetaModel::GetParentClass($sClass);
  3196. $aMappingData = $this->GetMapRule($sParent);
  3197. }
  3198. return $aMappingData;
  3199. }
  3200. }
  3201. /**
  3202. * Map a date+time column to an attribute
  3203. *
  3204. * @package iTopORM
  3205. */
  3206. class AttributeDateTime extends AttributeDBField
  3207. {
  3208. static $oFormat = null;
  3209. static public function GetFormat()
  3210. {
  3211. if (self::$oFormat == null)
  3212. {
  3213. static::LoadFormatFromConfig();
  3214. }
  3215. return self::$oFormat;
  3216. }
  3217. /**
  3218. * Load the 3 settings: date format, time format and data_time format from the configuration
  3219. */
  3220. protected static function LoadFormatFromConfig()
  3221. {
  3222. $aFormats = MetaModel::GetConfig()->Get('date_and_time_format');
  3223. $sLang = Dict::GetUserLanguage();
  3224. $sDateFormat = isset($aFormats[$sLang]['date']) ? $aFormats[$sLang]['date'] : (isset($aFormats['default']['date']) ? $aFormats['default']['date'] : 'Y-m-d');
  3225. $sTimeFormat = isset($aFormats[$sLang]['time']) ? $aFormats[$sLang]['time'] : (isset($aFormats['default']['time']) ? $aFormats['default']['time'] : 'H:i:s');
  3226. $sDateAndTimeFormat = isset($aFormats[$sLang]['date_time']) ? $aFormats[$sLang]['date_time'] : (isset($aFormats['default']['date_time']) ? $aFormats['default']['date_time'] : '$date $time');
  3227. $sFullFormat = str_replace(array('$date', '$time'), array($sDateFormat, $sTimeFormat), $sDateAndTimeFormat);
  3228. self::SetFormat(new DateTimeFormat($sFullFormat));
  3229. AttributeDate::SetFormat(new DateTimeFormat($sDateFormat));
  3230. }
  3231. /**
  3232. * Returns the format string used for the date & time stored in memory
  3233. * @return string
  3234. */
  3235. static public function GetInternalFormat()
  3236. {
  3237. return 'Y-m-d H:i:s';
  3238. }
  3239. /**
  3240. * Returns the format string used for the date & time written to MySQL
  3241. * @return string
  3242. */
  3243. static public function GetSQLFormat()
  3244. {
  3245. return 'Y-m-d H:i:s';
  3246. }
  3247. static public function SetFormat(DateTimeFormat $oDateTimeFormat)
  3248. {
  3249. self::$oFormat = $oDateTimeFormat;
  3250. }
  3251. static public function GetSQLTimeFormat()
  3252. {
  3253. return 'H:i:s';
  3254. }
  3255. /**
  3256. * Parses a search string coming from user input
  3257. * @param string $sSearchString
  3258. * @return string
  3259. */
  3260. public function ParseSearchString($sSearchString)
  3261. {
  3262. try
  3263. {
  3264. $oDateTime = $this->GetFormat()->Parse($sSearchString);
  3265. $sSearchString = $oDateTime->format($this->GetInternalFormat());
  3266. }
  3267. catch(Exception $e)
  3268. {
  3269. $sFormatString = '!'.(string)AttributeDate::GetFormat(); // BEWARE: ! is needed to set non-parsed fields to zero !!!
  3270. $oDateTime = DateTime::createFromFormat($sFormatString, $sSearchString);
  3271. if ($oDateTime !== false)
  3272. {
  3273. $sSearchString = $oDateTime->format($this->GetInternalFormat());
  3274. }
  3275. }
  3276. return $sSearchString;
  3277. }
  3278. static public function GetFormFieldClass()
  3279. {
  3280. return '\\Combodo\\iTop\\Form\\Field\\DateTimeField';
  3281. }
  3282. /**
  3283. * Override to specify Field class
  3284. *
  3285. * 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.
  3286. */
  3287. public function MakeFormField(DBObject $oObject, $oFormField = null)
  3288. {
  3289. if ($oFormField === null)
  3290. {
  3291. $sFormFieldClass = static::GetFormFieldClass();
  3292. $oFormField = new $sFormFieldClass($this->GetCode());
  3293. }
  3294. $oFormField->SetPHPDateTimeFormat((string) $this->GetFormat());
  3295. $oFormField->SetJSDateTimeFormat($this->GetFormat()->ToMomentJS());
  3296. $oFormField = parent::MakeFormField($oObject, $oFormField);
  3297. // After call to the parent as it sets the current value
  3298. $oFormField->SetCurrentValue($this->GetFormat()->Format($oObject->Get($this->GetCode())));
  3299. return $oFormField;
  3300. }
  3301. static public function ListExpectedParams()
  3302. {
  3303. return parent::ListExpectedParams();
  3304. //return array_merge(parent::ListExpectedParams(), array());
  3305. }
  3306. public function GetEditClass() {return "DateTime";}
  3307. public function GetEditValue($sValue, $oHostObj = null)
  3308. {
  3309. return (string)static::GetFormat()->format($sValue);
  3310. }
  3311. public function GetValueLabel($sValue, $oHostObj = null)
  3312. {
  3313. return (string)static::GetFormat()->format($sValue);
  3314. }
  3315. protected function GetSQLCol($bFullSpec = false) {return "DATETIME";}
  3316. public static function GetAsUnixSeconds($value)
  3317. {
  3318. $oDeadlineDateTime = new DateTime($value);
  3319. $iUnixSeconds = $oDeadlineDateTime->format('U');
  3320. return $iUnixSeconds;
  3321. }
  3322. public function GetDefaultValue(DBObject $oHostObject = null)
  3323. {
  3324. // null value will be replaced by the current date, if not already set, in DoComputeValues
  3325. return $this->GetNullValue();
  3326. }
  3327. public function GetValidationPattern()
  3328. {
  3329. return static::GetFormat()->ToRegExpr();
  3330. }
  3331. public function GetBasicFilterOperators()
  3332. {
  3333. return array(
  3334. "="=>"equals",
  3335. "!="=>"differs from",
  3336. "<"=>"before",
  3337. "<="=>"before",
  3338. ">"=>"after (strictly)",
  3339. ">="=>"after",
  3340. "SameDay"=>"same day (strip time)",
  3341. "SameMonth"=>"same year/month",
  3342. "SameYear"=>"same year",
  3343. "Today"=>"today",
  3344. ">|"=>"after today + N days",
  3345. "<|"=>"before today + N days",
  3346. "=|"=>"equals today + N days",
  3347. );
  3348. }
  3349. public function GetBasicFilterLooseOperator()
  3350. {
  3351. // Unless we implement a "same xxx, depending on given precision" !
  3352. return "=";
  3353. }
  3354. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3355. {
  3356. $sQValue = CMDBSource::Quote($value);
  3357. switch ($sOpCode)
  3358. {
  3359. case '=':
  3360. case '!=':
  3361. case '<':
  3362. case '<=':
  3363. case '>':
  3364. case '>=':
  3365. return $this->GetSQLExpr()." $sOpCode $sQValue";
  3366. case 'SameDay':
  3367. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  3368. case 'SameMonth':
  3369. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  3370. case 'SameYear':
  3371. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  3372. case 'Today':
  3373. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  3374. case '>|':
  3375. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  3376. case '<|':
  3377. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  3378. case '=|':
  3379. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  3380. default:
  3381. return $this->GetSQLExpr()." = $sQValue";
  3382. }
  3383. }
  3384. public function MakeRealValue($proposedValue, $oHostObj)
  3385. {
  3386. if (is_null($proposedValue))
  3387. {
  3388. return null;
  3389. }
  3390. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  3391. {
  3392. return null;
  3393. }
  3394. if (!is_numeric($proposedValue))
  3395. {
  3396. return $proposedValue;
  3397. }
  3398. return date(static::GetInternalFormat(), $proposedValue);
  3399. }
  3400. public function ScalarToSQL($value)
  3401. {
  3402. if (is_null($value))
  3403. {
  3404. return null;
  3405. }
  3406. elseif (empty($value))
  3407. {
  3408. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  3409. return '0000-00-00 00:00:00';
  3410. }
  3411. return $value;
  3412. }
  3413. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3414. {
  3415. return Str::pure2html(static::GetFormat()->format($value));
  3416. }
  3417. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3418. {
  3419. return Str::pure2xml($value);
  3420. }
  3421. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  3422. {
  3423. if (empty($sValue) || ($sValue === '0000-00-00 00:00:00') || ($sValue === '0000-00-00'))
  3424. {
  3425. return '';
  3426. }
  3427. else if ((string)static::GetFormat() !== static::GetInternalFormat())
  3428. {
  3429. // Format conversion
  3430. $oDate = new DateTime($sValue);
  3431. if ($oDate !== false)
  3432. {
  3433. $sValue = static::GetFormat()->format($oDate);
  3434. }
  3435. }
  3436. $sFrom = array("\r\n", $sTextQualifier);
  3437. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  3438. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  3439. return $sTextQualifier.$sEscaped.$sTextQualifier;
  3440. }
  3441. /**
  3442. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  3443. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  3444. * does nothing special, and just calls the default (loose) operator
  3445. * @param string $sSearchText The search string to analyze for smart patterns
  3446. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  3447. * @param Hash $aParams Values of the query parameters
  3448. * @return Expression The search condition to be added (AND) to the current search
  3449. */
  3450. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams, $bParseSearchString = false)
  3451. {
  3452. // Possible smart patterns
  3453. $aPatterns = array(
  3454. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  3455. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  3456. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  3457. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  3458. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  3459. );
  3460. $sPatternFound = '';
  3461. $aMatches = array();
  3462. foreach($aPatterns as $sPatName => $sPattern)
  3463. {
  3464. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  3465. {
  3466. $sPatternFound = $sPatName;
  3467. break;
  3468. }
  3469. }
  3470. switch($sPatternFound)
  3471. {
  3472. case 'between':
  3473. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  3474. $oRightExpr = new VariableExpression($sParamName1);
  3475. if ($bParseSearchString)
  3476. {
  3477. $aParams[$sParamName1] = $this->ParseSearchString($aMatches[1]);
  3478. }
  3479. else
  3480. {
  3481. $aParams[$sParamName1] = $aMatches[1];
  3482. }
  3483. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  3484. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  3485. $oRightExpr = new VariableExpression($sParamName2);
  3486. $sOperator = $this->GetBasicFilterLooseOperator();
  3487. if ($bParseSearchString)
  3488. {
  3489. $aParams[$sParamName2] = $this->ParseSearchString($aMatches[2]);
  3490. }
  3491. else
  3492. {
  3493. $aParams[$sParamName2] = $aMatches[2];
  3494. }
  3495. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  3496. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  3497. break;
  3498. case 'greater than':
  3499. case 'greater than or equal':
  3500. case 'less than':
  3501. case 'less than or equal':
  3502. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  3503. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  3504. $oRightExpr = new VariableExpression($sParamName);
  3505. if ($bParseSearchString)
  3506. {
  3507. $aParams[$sParamName] = $this->ParseSearchString($aMatches[1]);
  3508. }
  3509. else
  3510. {
  3511. $aParams[$sParamName] = $aMatches[1];
  3512. }
  3513. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  3514. break;
  3515. default:
  3516. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams, $bParseSearchString);
  3517. }
  3518. return $oNewCondition;
  3519. }
  3520. public function GetHelpOnSmartSearch()
  3521. {
  3522. $sDict = parent::GetHelpOnSmartSearch();
  3523. $oFormat = static::GetFormat();
  3524. $sExample = $oFormat->Format(new DateTime('2015-07-19 18:40:00'));
  3525. return vsprintf($sDict, array($oFormat->ToPlaceholder(), $sExample));
  3526. }
  3527. }
  3528. /**
  3529. * Store a duration as a number of seconds
  3530. *
  3531. * @package iTopORM
  3532. */
  3533. class AttributeDuration extends AttributeInteger
  3534. {
  3535. public function GetEditClass() {return "Duration";}
  3536. protected function GetSQLCol($bFullSpec = false) {return "INT(11) UNSIGNED";}
  3537. public function GetNullValue() {return '0';}
  3538. public function MakeRealValue($proposedValue, $oHostObj)
  3539. {
  3540. if (is_null($proposedValue)) return null;
  3541. if (!is_numeric($proposedValue)) return null;
  3542. if ( ((int)$proposedValue) < 0) return null;
  3543. return (int)$proposedValue;
  3544. }
  3545. public function ScalarToSQL($value)
  3546. {
  3547. if (is_null($value))
  3548. {
  3549. return null;
  3550. }
  3551. return $value;
  3552. }
  3553. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3554. {
  3555. return Str::pure2html(self::FormatDuration($value));
  3556. }
  3557. public static function FormatDuration($duration)
  3558. {
  3559. $aDuration = self::SplitDuration($duration);
  3560. $sResult = '';
  3561. if ($duration < 60)
  3562. {
  3563. // Less than 1 min
  3564. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  3565. }
  3566. else if ($duration < 3600)
  3567. {
  3568. // less than 1 hour, display it in minutes/seconds
  3569. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  3570. }
  3571. else if ($duration < 86400)
  3572. {
  3573. // Less than 1 day, display it in hours/minutes/seconds
  3574. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  3575. }
  3576. else
  3577. {
  3578. // more than 1 day, display it in days/hours/minutes/seconds
  3579. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  3580. }
  3581. return $sResult;
  3582. }
  3583. static function SplitDuration($duration)
  3584. {
  3585. $duration = (int) $duration;
  3586. $days = floor($duration / 86400);
  3587. $hours = floor(($duration - (86400*$days)) / 3600);
  3588. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  3589. $seconds = ($duration % 60); // modulo
  3590. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  3591. }
  3592. static public function GetFormFieldClass()
  3593. {
  3594. return '\\Combodo\\iTop\\Form\\Field\\LabelField';
  3595. }
  3596. public function MakeFormField(DBObject $oObject, $oFormField = null)
  3597. {
  3598. if ($oFormField === null)
  3599. {
  3600. $sFormFieldClass = static::GetFormFieldClass();
  3601. $oFormField = new $sFormFieldClass($this->GetCode());
  3602. }
  3603. parent::MakeFormField($oObject, $oFormField);
  3604. // Note : As of today, this attribute is -by nature- only supported in readonly mode, not edition
  3605. $sAttCode = $this->GetCode();
  3606. $oFormField->SetCurrentValue(html_entity_decode($oObject->GetAsHTML($sAttCode), ENT_QUOTES, 'UTF-8'));
  3607. $oFormField->SetReadOnly(true);
  3608. return $oFormField;
  3609. }
  3610. }
  3611. /**
  3612. * Map a date+time column to an attribute
  3613. *
  3614. * @package iTopORM
  3615. */
  3616. class AttributeDate extends AttributeDateTime
  3617. {
  3618. static $oDateFormat = null;
  3619. static public function GetFormat()
  3620. {
  3621. if (self::$oDateFormat == null)
  3622. {
  3623. AttributeDateTime::LoadFormatFromConfig();
  3624. }
  3625. return self::$oDateFormat;
  3626. }
  3627. static public function SetFormat(DateTimeFormat $oDateFormat)
  3628. {
  3629. self::$oDateFormat = $oDateFormat;
  3630. }
  3631. /**
  3632. * Returns the format string used for the date & time stored in memory
  3633. * @return string
  3634. */
  3635. static public function GetInternalFormat()
  3636. {
  3637. return 'Y-m-d';
  3638. }
  3639. /**
  3640. * Returns the format string used for the date & time written to MySQL
  3641. * @return string
  3642. */
  3643. static public function GetSQLFormat()
  3644. {
  3645. return 'Y-m-d';
  3646. }
  3647. static public function ListExpectedParams()
  3648. {
  3649. return parent::ListExpectedParams();
  3650. //return array_merge(parent::ListExpectedParams(), array());
  3651. }
  3652. public function GetEditClass() {return "Date";}
  3653. protected function GetSQLCol($bFullSpec = false) {return "DATE";}
  3654. /**
  3655. * Override to specify Field class
  3656. *
  3657. * 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.
  3658. */
  3659. public function MakeFormField(DBObject $oObject, $oFormField = null)
  3660. {
  3661. $oFormField = parent::MakeFormField($oObject, $oFormField);
  3662. $oFormField->SetDateOnly(true);
  3663. return $oFormField;
  3664. }
  3665. }
  3666. /**
  3667. * A dead line stored as a date & time
  3668. * The only difference with the DateTime attribute is the display:
  3669. * relative to the current time
  3670. */
  3671. class AttributeDeadline extends AttributeDateTime
  3672. {
  3673. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3674. {
  3675. $sResult = self::FormatDeadline($value);
  3676. return $sResult;
  3677. }
  3678. public static function FormatDeadline($value)
  3679. {
  3680. $sResult = '';
  3681. if ($value !== null)
  3682. {
  3683. $iValue = AttributeDateTime::GetAsUnixSeconds($value);
  3684. $sDate = AttributeDateTime::GetFormat()->Format($value);
  3685. $difference = $iValue - time();
  3686. if ($difference >= 0)
  3687. {
  3688. $sDifference = self::FormatDuration($difference);
  3689. }
  3690. else
  3691. {
  3692. $sDifference = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  3693. }
  3694. $sFormat = MetaModel::GetConfig()->Get('deadline_format', '$difference$');
  3695. $sResult = str_replace(array('$date$', '$difference$'), array($sDate, $sDifference), $sFormat);
  3696. }
  3697. return $sResult;
  3698. }
  3699. static function FormatDuration($duration)
  3700. {
  3701. $days = floor($duration / 86400);
  3702. $hours = floor(($duration - (86400*$days)) / 3600);
  3703. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  3704. $sResult = '';
  3705. if ($duration < 60)
  3706. {
  3707. // Less than 1 min
  3708. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  3709. }
  3710. else if ($duration < 3600)
  3711. {
  3712. // less than 1 hour, display it in minutes
  3713. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  3714. }
  3715. else if ($duration < 86400)
  3716. {
  3717. // Less that 1 day, display it in hours/minutes
  3718. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  3719. }
  3720. else
  3721. {
  3722. // Less that 1 day, display it in hours/minutes
  3723. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  3724. }
  3725. return $sResult;
  3726. }
  3727. }
  3728. /**
  3729. * Map a foreign key to an attribute
  3730. * AttributeExternalKey and AttributeExternalField may be an external key
  3731. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  3732. * where an AttributeExternalField corresponds to a column into another table (class)
  3733. *
  3734. * @package iTopORM
  3735. */
  3736. class AttributeExternalKey extends AttributeDBFieldVoid
  3737. {
  3738. static public function ListExpectedParams()
  3739. {
  3740. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  3741. }
  3742. public function GetEditClass() {return "ExtKey";}
  3743. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? " DEFAULT 0" : "");}
  3744. public function RequiresIndex()
  3745. {
  3746. return true;
  3747. }
  3748. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  3749. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  3750. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  3751. public function GetKeyAttCode() {return $this->GetCode();}
  3752. public function GetDisplayStyle() { return $this->GetOptional('display_style', 'select'); }
  3753. public function GetDefaultValue(DBObject $oHostObject = null) {return 0;}
  3754. public function IsNullAllowed()
  3755. {
  3756. if (MetaModel::GetConfig()->Get('disable_mandatory_ext_keys'))
  3757. {
  3758. return true;
  3759. }
  3760. return $this->Get("is_null_allowed");
  3761. }
  3762. public function GetBasicFilterOperators()
  3763. {
  3764. return parent::GetBasicFilterOperators();
  3765. }
  3766. public function GetBasicFilterLooseOperator()
  3767. {
  3768. return parent::GetBasicFilterLooseOperator();
  3769. }
  3770. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3771. {
  3772. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  3773. }
  3774. // overloaded here so that an ext key always have the answer to
  3775. // "what are your possible values?"
  3776. public function GetValuesDef()
  3777. {
  3778. $oValSetDef = $this->Get("allowed_values");
  3779. if (!$oValSetDef)
  3780. {
  3781. // Let's propose every existing value
  3782. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  3783. }
  3784. return $oValSetDef;
  3785. }
  3786. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3787. {
  3788. //throw new Exception("GetAllowedValues on ext key has been deprecated");
  3789. try
  3790. {
  3791. return parent::GetAllowedValues($aArgs, $sContains);
  3792. }
  3793. catch (MissingQueryArgument $e)
  3794. {
  3795. // Some required arguments could not be found, enlarge to any existing value
  3796. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  3797. return $oValSetDef->GetValues($aArgs, $sContains);
  3798. }
  3799. }
  3800. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  3801. {
  3802. $oValSetDef = $this->GetValuesDef();
  3803. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  3804. return $oSet;
  3805. }
  3806. public function GetDeletionPropagationOption()
  3807. {
  3808. return $this->Get("on_target_delete");
  3809. }
  3810. public function GetNullValue()
  3811. {
  3812. return 0;
  3813. }
  3814. public function IsNull($proposedValue)
  3815. {
  3816. return ($proposedValue == 0);
  3817. }
  3818. public function MakeRealValue($proposedValue, $oHostObj)
  3819. {
  3820. if (is_null($proposedValue)) return 0;
  3821. if ($proposedValue === '') return 0;
  3822. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  3823. return (int)$proposedValue;
  3824. }
  3825. public function GetMaximumComboLength()
  3826. {
  3827. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  3828. }
  3829. public function GetMinAutoCompleteChars()
  3830. {
  3831. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  3832. }
  3833. public function AllowTargetCreation()
  3834. {
  3835. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  3836. }
  3837. /**
  3838. * Find the corresponding "link" attribute on the target class
  3839. *
  3840. * @return string The attribute code on the target class, or null if none has been found
  3841. */
  3842. public function GetMirrorLinkAttribute()
  3843. {
  3844. $oRet = null;
  3845. $sRemoteClass = $this->GetTargetClass();
  3846. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  3847. {
  3848. if (!$oRemoteAttDef->IsLinkSet()) continue;
  3849. if (!is_subclass_of($this->GetHostClass(), $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $this->GetHostClass()) continue;
  3850. if ($oRemoteAttDef->GetExtKeyToMe() != $this->GetCode()) continue;
  3851. $oRet = $oRemoteAttDef;
  3852. break;
  3853. }
  3854. return $oRet;
  3855. }
  3856. static public function GetFormFieldClass()
  3857. {
  3858. return '\\Combodo\\iTop\\Form\\Field\\SelectObjectField';
  3859. }
  3860. public function MakeFormField(DBObject $oObject, $oFormField = null)
  3861. {
  3862. if ($oFormField === null)
  3863. {
  3864. // TODO : We should check $this->Get('display_style') and create a Radio / Select / ... regarding its value
  3865. $sFormFieldClass = static::GetFormFieldClass();
  3866. $oFormField = new $sFormFieldClass($this->GetCode());
  3867. }
  3868. // Setting params
  3869. $oFormField->SetMaximumComboLength($this->GetMaximumComboLength());
  3870. $oFormField->SetMinAutoCompleteChars($this->GetMinAutoCompleteChars());
  3871. $oFormField->SetHierarchical(MetaModel::IsHierarchicalClass($this->GetTargetClass()));
  3872. // Setting choices regarding the field dependencies
  3873. $aFieldDependencies = $this->GetPrerequisiteAttributes();
  3874. if (!empty($aFieldDependencies))
  3875. {
  3876. $oTmpAttDef = $this;
  3877. $oTmpField = $oFormField;
  3878. $oFormField->SetOnFinalizeCallback(function() use ($oTmpField, $oTmpAttDef, $oObject)
  3879. {
  3880. $oSearch = DBSearch::FromOQL($oTmpAttDef->GetValuesDef()->GetFilterExpression());
  3881. $oSearch->SetInternalParams(array('this' => $oObject));
  3882. $oTmpField->SetSearch($oSearch);
  3883. });
  3884. }
  3885. else
  3886. {
  3887. $oSearch = DBSearch::FromOQL($this->GetValuesDef()->GetFilterExpression());
  3888. $oSearch->SetInternalParams(array('this' => $oObject));
  3889. $oFormField->SetSearch($oSearch);
  3890. }
  3891. // If ExtKey is mandatory, we add a validator to ensure that the value 0 is not selected
  3892. if ($oObject->GetAttributeFlags($this->GetCode()) & OPT_ATT_MANDATORY)
  3893. {
  3894. $oFormField->AddValidator(new \Combodo\iTop\Form\Validator\NotEmptyExtKeyValidator());
  3895. }
  3896. parent::MakeFormField($oObject, $oFormField);
  3897. return $oFormField;
  3898. }
  3899. }
  3900. /**
  3901. * Special kind of External Key to manage a hierarchy of objects
  3902. */
  3903. class AttributeHierarchicalKey extends AttributeExternalKey
  3904. {
  3905. protected $m_sTargetClass;
  3906. static public function ListExpectedParams()
  3907. {
  3908. $aParams = parent::ListExpectedParams();
  3909. $idx = array_search('targetclass', $aParams);
  3910. unset($aParams[$idx]);
  3911. $idx = array_search('jointype', $aParams);
  3912. unset($aParams[$idx]);
  3913. return $aParams; // TODO: mettre les bons parametres ici !!
  3914. }
  3915. public function GetEditClass() {return "ExtKey";}
  3916. public function RequiresIndex()
  3917. {
  3918. return true;
  3919. }
  3920. /*
  3921. * The target class is the class for which the attribute has been defined first
  3922. */
  3923. public function SetHostClass($sHostClass)
  3924. {
  3925. if (!isset($this->m_sTargetClass))
  3926. {
  3927. $this->m_sTargetClass = $sHostClass;
  3928. }
  3929. parent::SetHostClass($sHostClass);
  3930. }
  3931. public function IsHierarchicalKey() {return true;}
  3932. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->m_sTargetClass;}
  3933. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  3934. public function GetKeyAttCode() {return $this->GetCode();}
  3935. public function GetBasicFilterOperators()
  3936. {
  3937. return parent::GetBasicFilterOperators();
  3938. }
  3939. public function GetBasicFilterLooseOperator()
  3940. {
  3941. return parent::GetBasicFilterLooseOperator();
  3942. }
  3943. public function GetSQLColumns($bFullSpec = false)
  3944. {
  3945. $aColumns = array();
  3946. $aColumns[$this->GetCode()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3947. $aColumns[$this->GetSQLLeft()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3948. $aColumns[$this->GetSQLRight()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3949. return $aColumns;
  3950. }
  3951. public function GetSQLRight()
  3952. {
  3953. return $this->GetCode().'_right';
  3954. }
  3955. public function GetSQLLeft()
  3956. {
  3957. return $this->GetCode().'_left';
  3958. }
  3959. public function GetSQLValues($value)
  3960. {
  3961. if (!is_array($value))
  3962. {
  3963. $aValues[$this->GetCode()] = $value;
  3964. }
  3965. else
  3966. {
  3967. $aValues = array();
  3968. $aValues[$this->GetCode()] = $value[$this->GetCode()];
  3969. $aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
  3970. $aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
  3971. }
  3972. return $aValues;
  3973. }
  3974. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3975. {
  3976. if (array_key_exists('this', $aArgs))
  3977. {
  3978. // Hierarchical keys have one more constraint: the "parent value" cannot be
  3979. // "under" themselves
  3980. $iRootId = $aArgs['this']->GetKey();
  3981. if ($iRootId > 0) // ignore objects that do no exist in the database...
  3982. {
  3983. $oValSetDef = $this->GetValuesDef();
  3984. $sClass = $this->m_sTargetClass;
  3985. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  3986. $oValSetDef->AddCondition($oFilter);
  3987. }
  3988. }
  3989. else
  3990. {
  3991. return parent::GetAllowedValues($aArgs, $sContains);
  3992. }
  3993. }
  3994. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  3995. {
  3996. $oValSetDef = $this->GetValuesDef();
  3997. if (array_key_exists('this', $aArgs))
  3998. {
  3999. // Hierarchical keys have one more constraint: the "parent value" cannot be
  4000. // "under" themselves
  4001. $iRootId = $aArgs['this']->GetKey();
  4002. if ($iRootId > 0) // ignore objects that do no exist in the database...
  4003. {
  4004. $aValuesSetDef = $this->GetValuesDef();
  4005. $sClass = $this->m_sTargetClass;
  4006. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  4007. $oValSetDef->AddCondition($oFilter);
  4008. }
  4009. }
  4010. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  4011. return $oSet;
  4012. }
  4013. /**
  4014. * Find the corresponding "link" attribute on the target class
  4015. *
  4016. * @return string The attribute code on the target class, or null if none has been found
  4017. */
  4018. public function GetMirrorLinkAttribute()
  4019. {
  4020. return null;
  4021. }
  4022. }
  4023. /**
  4024. * An attribute which corresponds to an external key (direct or indirect)
  4025. *
  4026. * @package iTopORM
  4027. */
  4028. class AttributeExternalField extends AttributeDefinition
  4029. {
  4030. static public function ListExpectedParams()
  4031. {
  4032. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  4033. }
  4034. public function GetEditClass() {return "ExtField";}
  4035. public function GetFinalAttDef()
  4036. {
  4037. $oExtAttDef = $this->GetExtAttDef();
  4038. return $oExtAttDef->GetFinalAttDef();
  4039. }
  4040. protected function GetSQLCol($bFullSpec = false)
  4041. {
  4042. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  4043. $oExtAttDef = $this->GetExtAttDef();
  4044. return $oExtAttDef->GetSQLCol($bFullSpec);
  4045. }
  4046. public function GetSQLExpressions($sPrefix = '')
  4047. {
  4048. if ($sPrefix == '')
  4049. {
  4050. return array('' => $this->GetCode()); // Warning: Use GetCode() since AttributeExternalField does not have any 'sql' property
  4051. }
  4052. else
  4053. {
  4054. return $sPrefix;
  4055. }
  4056. }
  4057. public function GetLabel($sDefault = null)
  4058. {
  4059. $sLabel = parent::GetLabel('');
  4060. if (strlen($sLabel) == 0)
  4061. {
  4062. $oRemoteAtt = $this->GetExtAttDef();
  4063. $sLabel = $oRemoteAtt->GetLabel($this->m_sCode);
  4064. }
  4065. return $sLabel;
  4066. }
  4067. public function GetDescription($sDefault = null)
  4068. {
  4069. $sLabel = parent::GetDescription('');
  4070. if (strlen($sLabel) == 0)
  4071. {
  4072. $oRemoteAtt = $this->GetExtAttDef();
  4073. $sLabel = $oRemoteAtt->GetDescription('');
  4074. }
  4075. return $sLabel;
  4076. }
  4077. public function GetHelpOnEdition($sDefault = null)
  4078. {
  4079. $sLabel = parent::GetHelpOnEdition('');
  4080. if (strlen($sLabel) == 0)
  4081. {
  4082. $oRemoteAtt = $this->GetExtAttDef();
  4083. $sLabel = $oRemoteAtt->GetHelpOnEdition('');
  4084. }
  4085. return $sLabel;
  4086. }
  4087. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  4088. {
  4089. switch($iType)
  4090. {
  4091. case EXTKEY_ABSOLUTE:
  4092. // see further
  4093. $oRemoteAtt = $this->GetExtAttDef();
  4094. return $oRemoteAtt->IsExternalKey($iType);
  4095. case EXTKEY_RELATIVE:
  4096. return false;
  4097. default:
  4098. throw new CoreException("Unexpected value for argument iType: '$iType'");
  4099. }
  4100. }
  4101. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  4102. {
  4103. return $this->GetKeyAttDef($iType)->GetTargetClass();
  4104. }
  4105. public function IsExternalField() {return true;}
  4106. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  4107. public function GetExtAttCode() {return $this->Get("target_attcode");}
  4108. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  4109. {
  4110. switch($iType)
  4111. {
  4112. case EXTKEY_ABSOLUTE:
  4113. // see further
  4114. $oRemoteAtt = $this->GetExtAttDef();
  4115. if ($oRemoteAtt->IsExternalField())
  4116. {
  4117. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  4118. }
  4119. else if ($oRemoteAtt->IsExternalKey())
  4120. {
  4121. return $oRemoteAtt;
  4122. }
  4123. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  4124. case EXTKEY_RELATIVE:
  4125. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  4126. default:
  4127. throw new CoreException("Unexpected value for argument iType: '$iType'");
  4128. }
  4129. }
  4130. public function GetPrerequisiteAttributes($sClass = null)
  4131. {
  4132. return array($this->Get("extkey_attcode"));
  4133. }
  4134. public function GetExtAttDef()
  4135. {
  4136. $oKeyAttDef = $this->GetKeyAttDef();
  4137. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $this->Get("target_attcode"));
  4138. 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"));
  4139. return $oExtAttDef;
  4140. }
  4141. public function GetSQLExpr()
  4142. {
  4143. $oExtAttDef = $this->GetExtAttDef();
  4144. return $oExtAttDef->GetSQLExpr();
  4145. }
  4146. public function GetDefaultValue(DBObject $oHostObject = null)
  4147. {
  4148. $oExtAttDef = $this->GetExtAttDef();
  4149. return $oExtAttDef->GetDefaultValue();
  4150. }
  4151. public function IsNullAllowed()
  4152. {
  4153. $oExtAttDef = $this->GetExtAttDef();
  4154. return $oExtAttDef->IsNullAllowed();
  4155. }
  4156. public function IsScalar()
  4157. {
  4158. $oExtAttDef = $this->GetExtAttDef();
  4159. return $oExtAttDef->IsScalar();
  4160. }
  4161. public function GetFilterDefinitions()
  4162. {
  4163. return array($this->GetCode() => new FilterFromAttribute($this));
  4164. }
  4165. public function GetBasicFilterOperators()
  4166. {
  4167. $oExtAttDef = $this->GetExtAttDef();
  4168. return $oExtAttDef->GetBasicFilterOperators();
  4169. }
  4170. public function GetBasicFilterLooseOperator()
  4171. {
  4172. $oExtAttDef = $this->GetExtAttDef();
  4173. return $oExtAttDef->GetBasicFilterLooseOperator();
  4174. }
  4175. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4176. {
  4177. $oExtAttDef = $this->GetExtAttDef();
  4178. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  4179. }
  4180. public function GetNullValue()
  4181. {
  4182. $oExtAttDef = $this->GetExtAttDef();
  4183. return $oExtAttDef->GetNullValue();
  4184. }
  4185. public function IsNull($proposedValue)
  4186. {
  4187. $oExtAttDef = $this->GetExtAttDef();
  4188. return $oExtAttDef->IsNull($proposedValue);
  4189. }
  4190. public function MakeRealValue($proposedValue, $oHostObj)
  4191. {
  4192. $oExtAttDef = $this->GetExtAttDef();
  4193. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  4194. }
  4195. public function ScalarToSQL($value)
  4196. {
  4197. // This one could be used in case of filtering only
  4198. $oExtAttDef = $this->GetExtAttDef();
  4199. return $oExtAttDef->ScalarToSQL($value);
  4200. }
  4201. // Do not overload GetSQLExpression here because this is handled in the joins
  4202. //public function GetSQLExpressions($sPrefix = '') {return array();}
  4203. // Here, we get the data...
  4204. public function FromSQLToValue($aCols, $sPrefix = '')
  4205. {
  4206. $oExtAttDef = $this->GetExtAttDef();
  4207. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  4208. }
  4209. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4210. {
  4211. $oExtAttDef = $this->GetExtAttDef();
  4212. return $oExtAttDef->GetAsHTML($value, null, $bLocalize);
  4213. }
  4214. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4215. {
  4216. $oExtAttDef = $this->GetExtAttDef();
  4217. return $oExtAttDef->GetAsXML($value, null, $bLocalize);
  4218. }
  4219. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  4220. {
  4221. $oExtAttDef = $this->GetExtAttDef();
  4222. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier, null, $bLocalize, $bConvertToPlainText);
  4223. }
  4224. static public function GetFormFieldClass()
  4225. {
  4226. return '\\Combodo\\iTop\\Form\\Field\\LabelField';
  4227. }
  4228. public function MakeFormField(DBObject $oObject, $oFormField = null)
  4229. {
  4230. if ($oFormField === null)
  4231. {
  4232. $sFormFieldClass = static::GetFormFieldClass();
  4233. $oFormField = new $sFormFieldClass($this->GetCode());
  4234. }
  4235. parent::MakeFormField($oObject, $oFormField);
  4236. // Note : As of today, this attribute is -by nature- only supported in readonly mode, not edition
  4237. $sAttCode = $this->GetCode();
  4238. $sAttCodeFriendlyname = $sAttCode . '_friendlyname';
  4239. if ($this->IsExternalKey(EXTKEY_ABSOLUTE) && MetaModel::IsValidAttCode(get_class($oObject), $sAttCodeFriendlyname))
  4240. {
  4241. $sAttCode = $sAttCodeFriendlyname;
  4242. }
  4243. $oFormField->SetCurrentValue(html_entity_decode($oObject->GetAsHTML($sAttCode), ENT_QUOTES, 'UTF-8'));
  4244. return $oFormField;
  4245. }
  4246. public function IsPartOfFingerprint()
  4247. {
  4248. return false;
  4249. }
  4250. }
  4251. /**
  4252. * Map a varchar column to an URL (formats the ouput in HMTL)
  4253. *
  4254. * @package iTopORM
  4255. */
  4256. class AttributeURL extends AttributeString
  4257. {
  4258. static public function ListExpectedParams()
  4259. {
  4260. //return parent::ListExpectedParams();
  4261. return array_merge(parent::ListExpectedParams(), array("target"));
  4262. }
  4263. protected function GetSQLCol($bFullSpec = false) {return "VARCHAR(2048)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  4264. public function GetMaxSize()
  4265. {
  4266. return 2048;
  4267. }
  4268. public function GetEditClass() {return "String";}
  4269. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  4270. {
  4271. $sTarget = $this->Get("target");
  4272. if (empty($sTarget)) $sTarget = "_blank";
  4273. $sLabel = Str::pure2html($sValue);
  4274. if (strlen($sLabel) > 128)
  4275. {
  4276. // Truncate the length to 128 characters, by removing the middle
  4277. $sLabel = substr($sLabel, 0, 100).'.....'.substr($sLabel, -20);
  4278. }
  4279. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  4280. }
  4281. public function GetValidationPattern()
  4282. {
  4283. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('url_validation_pattern').'$');
  4284. }
  4285. }
  4286. /**
  4287. * A blob is an ormDocument, it is stored as several columns in the database
  4288. *
  4289. * @package iTopORM
  4290. */
  4291. class AttributeBlob extends AttributeDefinition
  4292. {
  4293. static public function ListExpectedParams()
  4294. {
  4295. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  4296. }
  4297. public function GetEditClass() {return "Document";}
  4298. public function IsDirectField() {return true;}
  4299. public function IsScalar() {return true;}
  4300. public function IsWritable() {return true;}
  4301. public function GetDefaultValue(DBObject $oHostObject = null) {return "";}
  4302. public function IsNullAllowed(DBObject $oHostObject = null) {return $this->GetOptional("is_null_allowed", false);}
  4303. public function GetEditValue($sValue, $oHostObj = null)
  4304. {
  4305. return '';
  4306. }
  4307. // Facilitate things: allow administrators to upload a document
  4308. // from a CSV by specifying its path/URL
  4309. public function MakeRealValue($proposedValue, $oHostObj)
  4310. {
  4311. if (!is_object($proposedValue))
  4312. {
  4313. if (file_exists($proposedValue) && UserRights::IsAdministrator())
  4314. {
  4315. $sContent = file_get_contents($proposedValue);
  4316. $sExtension = strtolower(pathinfo($proposedValue, PATHINFO_EXTENSION));
  4317. $sMimeType = "application/x-octet-stream";
  4318. $aKnownExtensions = array(
  4319. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  4320. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  4321. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  4322. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  4323. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  4324. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  4325. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  4326. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  4327. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  4328. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12.xlsx',
  4329. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  4330. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  4331. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  4332. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  4333. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  4334. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  4335. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  4336. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  4337. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  4338. 'jpg' => 'image/jpeg',
  4339. 'jpeg' => 'image/jpeg',
  4340. 'gif' => 'image/gif',
  4341. 'png' => 'image/png',
  4342. 'pdf' => 'application/pdf',
  4343. 'doc' => 'application/msword',
  4344. 'dot' => 'application/msword',
  4345. 'xls' => 'application/vnd.ms-excel',
  4346. 'ppt' => 'application/vnd.ms-powerpoint',
  4347. 'vsd' => 'application/x-visio',
  4348. 'vdx' => 'application/visio.drawing',
  4349. 'odt' => 'application/vnd.oasis.opendocument.text',
  4350. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  4351. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  4352. 'zip' => 'application/zip',
  4353. 'txt' => 'text/plain',
  4354. 'htm' => 'text/html',
  4355. 'html' => 'text/html',
  4356. 'exe' => 'application/octet-stream'
  4357. );
  4358. if (!array_key_exists($sExtension, $aKnownExtensions) && extension_loaded('fileinfo'))
  4359. {
  4360. $finfo = new finfo(FILEINFO_MIME);
  4361. $sMimeType = $finfo->file($proposedValue);
  4362. }
  4363. return new ormDocument($sContent, $sMimeType);
  4364. }
  4365. else
  4366. {
  4367. return new ormDocument($proposedValue, 'text/plain');
  4368. }
  4369. }
  4370. return $proposedValue;
  4371. }
  4372. public function GetSQLExpressions($sPrefix = '')
  4373. {
  4374. if ($sPrefix == '')
  4375. {
  4376. $sPrefix = $this->GetCode();
  4377. }
  4378. $aColumns = array();
  4379. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  4380. $aColumns[''] = $sPrefix.'_mimetype';
  4381. $aColumns['_data'] = $sPrefix.'_data';
  4382. $aColumns['_filename'] = $sPrefix.'_filename';
  4383. return $aColumns;
  4384. }
  4385. public function FromSQLToValue($aCols, $sPrefix = '')
  4386. {
  4387. if (!array_key_exists($sPrefix, $aCols))
  4388. {
  4389. $sAvailable = implode(', ', array_keys($aCols));
  4390. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4391. }
  4392. $sMimeType = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  4393. if (!array_key_exists($sPrefix.'_data', $aCols))
  4394. {
  4395. $sAvailable = implode(', ', array_keys($aCols));
  4396. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  4397. }
  4398. $data = isset($aCols[$sPrefix.'_data']) ? $aCols[$sPrefix.'_data'] : null;
  4399. if (!array_key_exists($sPrefix.'_filename', $aCols))
  4400. {
  4401. $sAvailable = implode(', ', array_keys($aCols));
  4402. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  4403. }
  4404. $sFileName = isset($aCols[$sPrefix.'_filename']) ? $aCols[$sPrefix.'_filename'] : '';
  4405. $value = new ormDocument($data, $sMimeType, $sFileName);
  4406. return $value;
  4407. }
  4408. public function GetSQLValues($value)
  4409. {
  4410. // #@# Optimization: do not load blobs anytime
  4411. // As per mySQL doc, selecting blob columns will prevent mySQL from
  4412. // using memory in case a temporary table has to be created
  4413. // (temporary tables created on disk)
  4414. // We will have to remove the blobs from the list of attributes when doing the select
  4415. // then the use of Get() should finalize the load
  4416. if ($value instanceOf ormDocument && !$value->IsEmpty())
  4417. {
  4418. $aValues = array();
  4419. $aValues[$this->GetCode().'_data'] = $value->GetData();
  4420. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  4421. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  4422. }
  4423. else
  4424. {
  4425. $aValues = array();
  4426. $aValues[$this->GetCode().'_data'] = '';
  4427. $aValues[$this->GetCode().'_mimetype'] = '';
  4428. $aValues[$this->GetCode().'_filename'] = '';
  4429. }
  4430. return $aValues;
  4431. }
  4432. public function GetSQLColumns($bFullSpec = false)
  4433. {
  4434. $aColumns = array();
  4435. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  4436. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  4437. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  4438. return $aColumns;
  4439. }
  4440. public function GetFilterDefinitions()
  4441. {
  4442. return array();
  4443. // still not working... see later...
  4444. return array(
  4445. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  4446. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  4447. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  4448. );
  4449. }
  4450. public function GetBasicFilterOperators()
  4451. {
  4452. return array();
  4453. }
  4454. public function GetBasicFilterLooseOperator()
  4455. {
  4456. return '=';
  4457. }
  4458. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4459. {
  4460. return 'true';
  4461. }
  4462. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4463. {
  4464. if (is_object($value))
  4465. {
  4466. return $value->GetAsHTML();
  4467. }
  4468. }
  4469. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  4470. {
  4471. return ''; // Not exportable in CSV !
  4472. }
  4473. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4474. {
  4475. $sRet = '';
  4476. if (is_object($value))
  4477. {
  4478. if (!$value->IsEmpty())
  4479. {
  4480. $sRet = '<mimetype>'.$value->GetMimeType().'</mimetype>';
  4481. $sRet .= '<filename>'.$value->GetFileName().'</filename>';
  4482. $sRet .= '<data>'.base64_encode($value->GetData()).'</data>';
  4483. }
  4484. }
  4485. return $sRet;
  4486. }
  4487. /**
  4488. * Helper to get a value that will be JSON encoded
  4489. * The operation is the opposite to FromJSONToValue
  4490. */
  4491. public function GetForJSON($value)
  4492. {
  4493. if ($value instanceOf ormDocument)
  4494. {
  4495. $aValues = array();
  4496. $aValues['data'] = base64_encode($value->GetData());
  4497. $aValues['mimetype'] = $value->GetMimeType();
  4498. $aValues['filename'] = $value->GetFileName();
  4499. }
  4500. else
  4501. {
  4502. $aValues = null;
  4503. }
  4504. return $aValues;
  4505. }
  4506. /**
  4507. * Helper to form a value, given JSON decoded data
  4508. * The operation is the opposite to GetForJSON
  4509. */
  4510. public function FromJSONToValue($json)
  4511. {
  4512. if (isset($json->data))
  4513. {
  4514. $data = base64_decode($json->data);
  4515. $value = new ormDocument($data, $json->mimetype, $json->filename);
  4516. }
  4517. else
  4518. {
  4519. $value = null;
  4520. }
  4521. return $value;
  4522. }
  4523. public function Fingerprint($value)
  4524. {
  4525. $sFingerprint = '';
  4526. if ($value instanceOf ormDocument)
  4527. {
  4528. $sFingerprint = md5($value->GetData());
  4529. }
  4530. return $sFingerprint;
  4531. }
  4532. }
  4533. /**
  4534. * An image is a specific type of document, it is stored as several columns in the database
  4535. *
  4536. * @package iTopORM
  4537. */
  4538. class AttributeImage extends AttributeBlob
  4539. {
  4540. public function GetEditClass() {return "Image";}
  4541. // Facilitate things: allow administrators to upload a document
  4542. // from a CSV by specifying its path/URL
  4543. public function MakeRealValue($proposedValue, $oHostObj)
  4544. {
  4545. if (!is_object($proposedValue))
  4546. {
  4547. if (file_exists($proposedValue) && UserRights::IsAdministrator())
  4548. {
  4549. $sContent = file_get_contents($proposedValue);
  4550. $sExtension = strtolower(pathinfo($proposedValue, PATHINFO_EXTENSION));
  4551. $sMimeType = "application/x-octet-stream";
  4552. $aKnownExtensions = array(
  4553. 'jpg' => 'image/jpeg',
  4554. 'jpeg' => 'image/jpeg',
  4555. 'gif' => 'image/gif',
  4556. 'png' => 'image/png'
  4557. );
  4558. if (!array_key_exists($sExtension, $aKnownExtensions) && extension_loaded('fileinfo'))
  4559. {
  4560. $finfo = new finfo(FILEINFO_MIME);
  4561. $sMimeType = $finfo->file($proposedValue);
  4562. }
  4563. return new ormDocument($sContent, $sMimeType);
  4564. }
  4565. }
  4566. return $proposedValue;
  4567. }
  4568. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4569. {
  4570. $iMaxWidthPx = $this->Get('display_max_width');
  4571. $iMaxHeightPx = $this->Get('display_max_height');
  4572. $sUrl = $this->Get('default_image');
  4573. $sRet = '<img src="'.$sUrl.'" style="max-width: '.$iMaxWidthPx.'px; max-height: '.$iMaxHeightPx.'px">';
  4574. if (is_object($value) && !$value->IsEmpty())
  4575. {
  4576. $sUrl = $value->GetDownloadURL(get_class($oHostObject), $oHostObject->GetKey(), $this->GetCode());
  4577. $sRet = '<img src="'.$sUrl.'" style="max-width: '.$iMaxWidthPx.'px; max-height: '.$iMaxHeightPx.'px">';
  4578. }
  4579. return '<div class="view-image" style="width: '.$iMaxWidthPx.'px; height: '.$iMaxHeightPx.'px;"><span class="helper-middle"></span>'.$sRet.'</div>';
  4580. }
  4581. }
  4582. /**
  4583. * A stop watch is an ormStopWatch object, it is stored as several columns in the database
  4584. *
  4585. * @package iTopORM
  4586. */
  4587. class AttributeStopWatch extends AttributeDefinition
  4588. {
  4589. static public function ListExpectedParams()
  4590. {
  4591. // The list of thresholds must be an array of iPercent => array of 'option' => value
  4592. return array_merge(parent::ListExpectedParams(), array("states", "goal_computing", "working_time_computing", "thresholds"));
  4593. }
  4594. public function GetEditClass() {return "StopWatch";}
  4595. public function IsDirectField() {return true;}
  4596. public function IsScalar() {return true;}
  4597. public function IsWritable() {return false;}
  4598. public function GetDefaultValue(DBObject $oHostObject = null) {return $this->NewStopWatch();}
  4599. public function GetEditValue($value, $oHostObj = null)
  4600. {
  4601. return $value->GetTimeSpent();
  4602. }
  4603. public function GetStates()
  4604. {
  4605. return $this->Get('states');
  4606. }
  4607. public function AlwaysLoadInTables()
  4608. {
  4609. // Each and every stop watch is accessed for computing the highlight code (DBObject::GetHighlightCode())
  4610. return true;
  4611. }
  4612. /**
  4613. * Construct a brand new (but configured) stop watch
  4614. */
  4615. public function NewStopWatch()
  4616. {
  4617. $oSW = new ormStopWatch();
  4618. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4619. {
  4620. $oSW->DefineThreshold($iThreshold);
  4621. }
  4622. return $oSW;
  4623. }
  4624. // Facilitate things: allow the user to Set the value from a string
  4625. public function MakeRealValue($proposedValue, $oHostObj)
  4626. {
  4627. if (!$proposedValue instanceof ormStopWatch)
  4628. {
  4629. return $this->NewStopWatch();
  4630. }
  4631. return $proposedValue;
  4632. }
  4633. public function GetSQLExpressions($sPrefix = '')
  4634. {
  4635. if ($sPrefix == '')
  4636. {
  4637. $sPrefix = $this->GetCode(); // Warning: a stopwatch does not have any 'sql' property, so its SQL column is equal to its attribute code !!
  4638. }
  4639. $aColumns = array();
  4640. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  4641. $aColumns[''] = $sPrefix.'_timespent';
  4642. $aColumns['_started'] = $sPrefix.'_started';
  4643. $aColumns['_laststart'] = $sPrefix.'_laststart';
  4644. $aColumns['_stopped'] = $sPrefix.'_stopped';
  4645. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4646. {
  4647. $sThPrefix = '_'.$iThreshold;
  4648. $aColumns[$sThPrefix.'_deadline'] = $sPrefix.$sThPrefix.'_deadline';
  4649. $aColumns[$sThPrefix.'_passed'] = $sPrefix.$sThPrefix.'_passed';
  4650. $aColumns[$sThPrefix.'_triggered'] = $sPrefix.$sThPrefix.'_triggered';
  4651. $aColumns[$sThPrefix.'_overrun'] = $sPrefix.$sThPrefix.'_overrun';
  4652. }
  4653. return $aColumns;
  4654. }
  4655. public static function DateToSeconds($sDate)
  4656. {
  4657. if (is_null($sDate))
  4658. {
  4659. return null;
  4660. }
  4661. $oDateTime = new DateTime($sDate);
  4662. $iSeconds = $oDateTime->format('U');
  4663. return $iSeconds;
  4664. }
  4665. public static function SecondsToDate($iSeconds)
  4666. {
  4667. if (is_null($iSeconds))
  4668. {
  4669. return null;
  4670. }
  4671. return date("Y-m-d H:i:s", $iSeconds);
  4672. }
  4673. public function FromSQLToValue($aCols, $sPrefix = '')
  4674. {
  4675. $aExpectedCols = array($sPrefix, $sPrefix.'_started', $sPrefix.'_laststart', $sPrefix.'_stopped');
  4676. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4677. {
  4678. $sThPrefix = '_'.$iThreshold;
  4679. $aExpectedCols[] = $sPrefix.$sThPrefix.'_deadline';
  4680. $aExpectedCols[] = $sPrefix.$sThPrefix.'_passed';
  4681. $aExpectedCols[] = $sPrefix.$sThPrefix.'_triggered';
  4682. $aExpectedCols[] = $sPrefix.$sThPrefix.'_overrun';
  4683. }
  4684. foreach ($aExpectedCols as $sExpectedCol)
  4685. {
  4686. if (!array_key_exists($sExpectedCol, $aCols))
  4687. {
  4688. $sAvailable = implode(', ', array_keys($aCols));
  4689. throw new MissingColumnException("Missing column '$sExpectedCol' from {$sAvailable}");
  4690. }
  4691. }
  4692. $value = new ormStopWatch(
  4693. $aCols[$sPrefix],
  4694. self::DateToSeconds($aCols[$sPrefix.'_started']),
  4695. self::DateToSeconds($aCols[$sPrefix.'_laststart']),
  4696. self::DateToSeconds($aCols[$sPrefix.'_stopped'])
  4697. );
  4698. $aThresholds = array();
  4699. foreach ($this->ListThresholds() as $iThreshold => $aDefinition)
  4700. {
  4701. $sThPrefix = '_'.$iThreshold;
  4702. $value->DefineThreshold(
  4703. $iThreshold,
  4704. self::DateToSeconds($aCols[$sPrefix.$sThPrefix.'_deadline']),
  4705. (bool)($aCols[$sPrefix.$sThPrefix.'_passed'] == 1),
  4706. (bool)($aCols[$sPrefix.$sThPrefix.'_triggered'] == 1),
  4707. $aCols[$sPrefix.$sThPrefix.'_overrun'],
  4708. array_key_exists('highlight', $aDefinition) ? $aDefinition['highlight'] : null
  4709. );
  4710. }
  4711. return $value;
  4712. }
  4713. public function GetSQLValues($value)
  4714. {
  4715. if ($value instanceOf ormStopWatch)
  4716. {
  4717. $aValues = array();
  4718. $aValues[$this->GetCode().'_timespent'] = $value->GetTimeSpent();
  4719. $aValues[$this->GetCode().'_started'] = self::SecondsToDate($value->GetStartDate());
  4720. $aValues[$this->GetCode().'_laststart'] = self::SecondsToDate($value->GetLastStartDate());
  4721. $aValues[$this->GetCode().'_stopped'] = self::SecondsToDate($value->GetStopDate());
  4722. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4723. {
  4724. $sPrefix = $this->GetCode().'_'.$iThreshold;
  4725. $aValues[$sPrefix.'_deadline'] = self::SecondsToDate($value->GetThresholdDate($iThreshold));
  4726. $aValues[$sPrefix.'_passed'] = $value->IsThresholdPassed($iThreshold) ? '1' : '0';
  4727. $aValues[$sPrefix.'_triggered'] = $value->IsThresholdTriggered($iThreshold) ? '1' : '0';
  4728. $aValues[$sPrefix.'_overrun'] = $value->GetOverrun($iThreshold);
  4729. }
  4730. }
  4731. else
  4732. {
  4733. $aValues = array();
  4734. $aValues[$this->GetCode().'_timespent'] = '';
  4735. $aValues[$this->GetCode().'_started'] = '';
  4736. $aValues[$this->GetCode().'_laststart'] = '';
  4737. $aValues[$this->GetCode().'_stopped'] = '';
  4738. }
  4739. return $aValues;
  4740. }
  4741. public function GetSQLColumns($bFullSpec = false)
  4742. {
  4743. $aColumns = array();
  4744. $aColumns[$this->GetCode().'_timespent'] = 'INT(11) UNSIGNED';
  4745. $aColumns[$this->GetCode().'_started'] = 'DATETIME';
  4746. $aColumns[$this->GetCode().'_laststart'] = 'DATETIME';
  4747. $aColumns[$this->GetCode().'_stopped'] = 'DATETIME';
  4748. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4749. {
  4750. $sPrefix = $this->GetCode().'_'.$iThreshold;
  4751. $aColumns[$sPrefix.'_deadline'] = 'DATETIME';
  4752. $aColumns[$sPrefix.'_passed'] = 'TINYINT(1) UNSIGNED';
  4753. $aColumns[$sPrefix.'_triggered'] = 'TINYINT(1)';
  4754. $aColumns[$sPrefix.'_overrun'] = 'INT(11) UNSIGNED';
  4755. }
  4756. return $aColumns;
  4757. }
  4758. public function GetFilterDefinitions()
  4759. {
  4760. $aRes = array(
  4761. $this->GetCode() => new FilterFromAttribute($this),
  4762. $this->GetCode().'_started' => new FilterFromAttribute($this, '_started'),
  4763. $this->GetCode().'_laststart' => new FilterFromAttribute($this, '_laststart'),
  4764. $this->GetCode().'_stopped' => new FilterFromAttribute($this, '_stopped')
  4765. );
  4766. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4767. {
  4768. $sPrefix = $this->GetCode().'_'.$iThreshold;
  4769. $aRes[$sPrefix.'_deadline'] = new FilterFromAttribute($this, '_deadline');
  4770. $aRes[$sPrefix.'_passed'] = new FilterFromAttribute($this, '_passed');
  4771. $aRes[$sPrefix.'_triggered'] = new FilterFromAttribute($this, '_triggered');
  4772. $aRes[$sPrefix.'_overrun'] = new FilterFromAttribute($this, '_overrun');
  4773. }
  4774. return $aRes;
  4775. }
  4776. public function GetBasicFilterOperators()
  4777. {
  4778. return array();
  4779. }
  4780. public function GetBasicFilterLooseOperator()
  4781. {
  4782. return '=';
  4783. }
  4784. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4785. {
  4786. return 'true';
  4787. }
  4788. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4789. {
  4790. if (is_object($value))
  4791. {
  4792. return $value->GetAsHTML($this, $oHostObject);
  4793. }
  4794. }
  4795. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  4796. {
  4797. return $value->GetTimeSpent();
  4798. }
  4799. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4800. {
  4801. return $value->GetTimeSpent();
  4802. }
  4803. public function ListThresholds()
  4804. {
  4805. return $this->Get('thresholds');
  4806. }
  4807. public function Fingerprint($value)
  4808. {
  4809. $sFingerprint = '';
  4810. if (is_object($value))
  4811. {
  4812. $sFingerprint = $value->GetAsHTML($this);
  4813. }
  4814. return $sFingerprint;
  4815. }
  4816. /**
  4817. * To expose internal values: Declare an attribute AttributeSubItem
  4818. * and implement the GetSubItemXXXX verbs
  4819. */
  4820. public function GetSubItemSQLExpression($sItemCode)
  4821. {
  4822. $sPrefix = $this->GetCode();
  4823. switch($sItemCode)
  4824. {
  4825. case 'timespent':
  4826. return array('' => $sPrefix.'_timespent');
  4827. case 'started':
  4828. return array('' => $sPrefix.'_started');
  4829. case 'laststart':
  4830. return array('' => $sPrefix.'_laststart');
  4831. case 'stopped':
  4832. return array('' => $sPrefix.'_stopped');
  4833. }
  4834. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4835. {
  4836. $sThPrefix = $iThreshold.'_';
  4837. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4838. {
  4839. // The current threshold is concerned
  4840. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4841. switch($sThresholdCode)
  4842. {
  4843. case 'deadline':
  4844. return array('' => $sPrefix.'_'.$iThreshold.'_deadline');
  4845. case 'passed':
  4846. return array('' => $sPrefix.'_'.$iThreshold.'_passed');
  4847. case 'triggered':
  4848. return array('' => $sPrefix.'_'.$iThreshold.'_triggered');
  4849. case 'overrun':
  4850. return array('' => $sPrefix.'_'.$iThreshold.'_overrun');
  4851. }
  4852. }
  4853. }
  4854. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  4855. }
  4856. public function GetSubItemValue($sItemCode, $value, $oHostObject = null)
  4857. {
  4858. $oStopWatch = $value;
  4859. switch($sItemCode)
  4860. {
  4861. case 'timespent':
  4862. return $oStopWatch->GetTimeSpent();
  4863. case 'started':
  4864. return $oStopWatch->GetStartDate();
  4865. case 'laststart':
  4866. return $oStopWatch->GetLastStartDate();
  4867. case 'stopped':
  4868. return $oStopWatch->GetStopDate();
  4869. }
  4870. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4871. {
  4872. $sThPrefix = $iThreshold.'_';
  4873. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4874. {
  4875. // The current threshold is concerned
  4876. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4877. switch($sThresholdCode)
  4878. {
  4879. case 'deadline':
  4880. return $oStopWatch->GetThresholdDate($iThreshold);
  4881. case 'passed':
  4882. return $oStopWatch->IsThresholdPassed($iThreshold);
  4883. case 'triggered':
  4884. return $oStopWatch->IsThresholdTriggered($iThreshold);
  4885. case 'overrun':
  4886. return $oStopWatch->GetOverrun($iThreshold);
  4887. }
  4888. }
  4889. }
  4890. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  4891. }
  4892. protected function GetBooleanLabel($bValue)
  4893. {
  4894. $sDictKey = $bValue ? 'yes' : 'no';
  4895. return Dict::S('BooleanLabel:'.$sDictKey, 'def:'.$sDictKey);
  4896. }
  4897. public function GetSubItemAsHTMLForHistory($sItemCode, $sValue)
  4898. {
  4899. switch($sItemCode)
  4900. {
  4901. case 'timespent':
  4902. $sHtml = (int)$sValue ? Str::pure2html(AttributeDuration::FormatDuration($sValue)) : null;
  4903. break;
  4904. case 'started':
  4905. case 'laststart':
  4906. case 'stopped':
  4907. $sHtml = (int)$sValue ? date(self::GetDateFormat(), (int)$sValue) : null;
  4908. break;
  4909. default:
  4910. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4911. {
  4912. $sThPrefix = $iThreshold.'_';
  4913. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4914. {
  4915. // The current threshold is concerned
  4916. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4917. switch($sThresholdCode)
  4918. {
  4919. case 'deadline':
  4920. $sHtml = (int)$sValue ? date(self::GetDateFormat(true /*full*/), (int)$sValue) : null;
  4921. break;
  4922. case 'passed':
  4923. $sHtml = $this->GetBooleanLabel((int)$sValue);
  4924. break;
  4925. case 'triggered':
  4926. $sHtml = $this->GetBooleanLabel((int)$sValue);
  4927. break;
  4928. case 'overrun':
  4929. $sHtml = (int)$sValue > 0 ? Str::pure2html(AttributeDuration::FormatDuration((int)$sValue)) : '';
  4930. }
  4931. }
  4932. }
  4933. }
  4934. return $sHtml;
  4935. }
  4936. static protected function GetDateFormat($bFull = false)
  4937. {
  4938. if ($bFull)
  4939. {
  4940. return "Y-m-d H:i:s";
  4941. }
  4942. else
  4943. {
  4944. return "Y-m-d H:i";
  4945. }
  4946. }
  4947. public function GetSubItemAsHTML($sItemCode, $value)
  4948. {
  4949. $sHtml = $value;
  4950. switch($sItemCode)
  4951. {
  4952. case 'timespent':
  4953. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  4954. break;
  4955. case 'started':
  4956. case 'laststart':
  4957. case 'stopped':
  4958. if (is_null($value))
  4959. {
  4960. $sHtml = ''; // Undefined
  4961. }
  4962. else
  4963. {
  4964. $sHtml = date(self::GetDateFormat(), $value);
  4965. }
  4966. break;
  4967. default:
  4968. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4969. {
  4970. $sThPrefix = $iThreshold.'_';
  4971. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4972. {
  4973. // The current threshold is concerned
  4974. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4975. switch($sThresholdCode)
  4976. {
  4977. case 'deadline':
  4978. if ($value)
  4979. {
  4980. $sDate = date(self::GetDateFormat(true /*full*/), $value);
  4981. $sHtml = Str::pure2html(AttributeDeadline::FormatDeadline($sDate));
  4982. }
  4983. else
  4984. {
  4985. $sHtml = '';
  4986. }
  4987. break;
  4988. case 'passed':
  4989. case 'triggered':
  4990. $sHtml = $this->GetBooleanLabel($value);
  4991. break;
  4992. case 'overrun':
  4993. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  4994. break;
  4995. }
  4996. }
  4997. }
  4998. }
  4999. return $sHtml;
  5000. }
  5001. public function GetSubItemAsCSV($sItemCode, $value, $sSeparator = ',', $sTextQualifier = '"', $bConvertToPlainText = false)
  5002. {
  5003. $sFrom = array("\r\n", $sTextQualifier);
  5004. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5005. $sEscaped = str_replace($sFrom, $sTo, (string)$value);
  5006. $sRet = $sTextQualifier.$sEscaped.$sTextQualifier;
  5007. switch($sItemCode)
  5008. {
  5009. case 'timespent':
  5010. case 'started':
  5011. case 'laststart':
  5012. case 'stopped':
  5013. break;
  5014. default:
  5015. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  5016. {
  5017. $sThPrefix = $iThreshold.'_';
  5018. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  5019. {
  5020. // The current threshold is concerned
  5021. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  5022. switch($sThresholdCode)
  5023. {
  5024. case 'deadline':
  5025. if ($value != '')
  5026. {
  5027. $sRet = $sTextQualifier.date(self::GetDateFormat(true /*full*/), $value).$sTextQualifier;
  5028. }
  5029. break;
  5030. case 'passed':
  5031. case 'triggered':
  5032. $sRet = $sTextQualifier.$this->GetBooleanLabel($value).$sTextQualifier;
  5033. break;
  5034. case 'overrun':
  5035. break;
  5036. }
  5037. }
  5038. }
  5039. }
  5040. return $sRet;
  5041. }
  5042. public function GetSubItemAsXML($sItemCode, $value)
  5043. {
  5044. $sRet = Str::pure2xml((string)$value);
  5045. switch($sItemCode)
  5046. {
  5047. case 'timespent':
  5048. case 'started':
  5049. case 'laststart':
  5050. case 'stopped':
  5051. break;
  5052. default:
  5053. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  5054. {
  5055. $sThPrefix = $iThreshold.'_';
  5056. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  5057. {
  5058. // The current threshold is concerned
  5059. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  5060. switch($sThresholdCode)
  5061. {
  5062. case 'deadline':
  5063. break;
  5064. case 'passed':
  5065. case 'triggered':
  5066. $sRet = $this->GetBooleanLabel($value);
  5067. break;
  5068. case 'overrun':
  5069. break;
  5070. }
  5071. }
  5072. }
  5073. }
  5074. return $sRet;
  5075. }
  5076. /**
  5077. * Implemented for the HTML spreadsheet format!
  5078. */
  5079. public function GetSubItemAsEditValue($sItemCode, $value)
  5080. {
  5081. $sRet = $value;
  5082. switch($sItemCode)
  5083. {
  5084. case 'timespent':
  5085. break;
  5086. case 'started':
  5087. case 'laststart':
  5088. case 'stopped':
  5089. if (is_null($value))
  5090. {
  5091. $sRet = ''; // Undefined
  5092. }
  5093. else
  5094. {
  5095. $sRet = date(self::GetDateFormat(), $value);
  5096. }
  5097. break;
  5098. default:
  5099. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  5100. {
  5101. $sThPrefix = $iThreshold.'_';
  5102. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  5103. {
  5104. // The current threshold is concerned
  5105. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  5106. switch($sThresholdCode)
  5107. {
  5108. case 'deadline':
  5109. if ($value)
  5110. {
  5111. $sRet = date(self::GetDateFormat(true /*full*/), $value);
  5112. }
  5113. else
  5114. {
  5115. $sRet = '';
  5116. }
  5117. break;
  5118. case 'passed':
  5119. case 'triggered':
  5120. $sRet = $this->GetBooleanLabel($value);
  5121. break;
  5122. case 'overrun':
  5123. break;
  5124. }
  5125. }
  5126. }
  5127. }
  5128. return $sRet;
  5129. }
  5130. }
  5131. /**
  5132. * View of a subvalue of another attribute
  5133. * If an attribute implements the verbs GetSubItem.... then it can expose
  5134. * internal values, each of them being an attribute and therefore they
  5135. * can be displayed at different times in the object lifecycle, and used for
  5136. * reporting (as a condition in OQL, or as an additional column in an export)
  5137. * Known usages: Stop Watches can expose threshold statuses
  5138. */
  5139. class AttributeSubItem extends AttributeDefinition
  5140. {
  5141. static public function ListExpectedParams()
  5142. {
  5143. return array_merge(parent::ListExpectedParams(), array('target_attcode', 'item_code'));
  5144. }
  5145. public function GetParentAttCode() {return $this->Get("target_attcode");}
  5146. /**
  5147. * Helper : get the attribute definition to which the execution will be forwarded
  5148. */
  5149. public function GetTargetAttDef()
  5150. {
  5151. $sClass = $this->GetHostClass();
  5152. $oParentAttDef = MetaModel::GetAttributeDef($sClass, $this->Get('target_attcode'));
  5153. return $oParentAttDef;
  5154. }
  5155. public function GetEditClass() {return "";}
  5156. public function GetValuesDef() {return null;}
  5157. public function IsDirectField() {return true;}
  5158. public function IsScalar() {return true;}
  5159. public function IsWritable() {return false;}
  5160. public function GetDefaultValue(DBObject $oHostObject = null) {return null;}
  5161. // public function IsNullAllowed() {return false;}
  5162. public function LoadInObject() {return false;} // if this verb returns false, then GetValue must be implemented
  5163. /**
  5164. * Used by DBOBject::Get()
  5165. */
  5166. public function GetValue($oHostObject, $bOriginal = false)
  5167. {
  5168. $oParent = $this->GetTargetAttDef();
  5169. $parentValue = $oHostObject->GetStrict($oParent->GetCode());
  5170. $res = $oParent->GetSubItemValue($this->Get('item_code'), $parentValue, $oHostObject);
  5171. return $res;
  5172. }
  5173. //
  5174. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  5175. public function FromSQLToValue($aCols, $sPrefix = '')
  5176. {
  5177. }
  5178. public function GetSQLColumns($bFullSpec = false)
  5179. {
  5180. return array();
  5181. }
  5182. public function GetFilterDefinitions()
  5183. {
  5184. return array($this->GetCode() => new FilterFromAttribute($this));
  5185. }
  5186. public function GetBasicFilterOperators()
  5187. {
  5188. return array();
  5189. }
  5190. public function GetBasicFilterLooseOperator()
  5191. {
  5192. return "=";
  5193. }
  5194. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5195. {
  5196. $sQValue = CMDBSource::Quote($value);
  5197. switch ($sOpCode)
  5198. {
  5199. case '!=':
  5200. return $this->GetSQLExpr()." != $sQValue";
  5201. break;
  5202. case '=':
  5203. default:
  5204. return $this->GetSQLExpr()." = $sQValue";
  5205. }
  5206. }
  5207. public function GetSQLExpressions($sPrefix = '')
  5208. {
  5209. $oParent = $this->GetTargetAttDef();
  5210. $res = $oParent->GetSubItemSQLExpression($this->Get('item_code'));
  5211. return $res;
  5212. }
  5213. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5214. {
  5215. $oParent = $this->GetTargetAttDef();
  5216. $res = $oParent->GetSubItemAsHTML($this->Get('item_code'), $value);
  5217. return $res;
  5218. }
  5219. public function GetAsHTMLForHistory($value, $oHostObject = null, $bLocalize = true)
  5220. {
  5221. $oParent = $this->GetTargetAttDef();
  5222. $res = $oParent->GetSubItemAsHTMLForHistory($this->Get('item_code'), $value);
  5223. return $res;
  5224. }
  5225. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5226. {
  5227. $oParent = $this->GetTargetAttDef();
  5228. $res = $oParent->GetSubItemAsCSV($this->Get('item_code'), $value, $sSeparator, $sTextQualifier, $bConvertToPlainText);
  5229. return $res;
  5230. }
  5231. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5232. {
  5233. $oParent = $this->GetTargetAttDef();
  5234. $res = $oParent->GetSubItemAsXML($this->Get('item_code'), $value);
  5235. return $res;
  5236. }
  5237. /**
  5238. * As of now, this function must be implemented to have the value in spreadsheet format
  5239. */
  5240. public function GetEditValue($value, $oHostObj = null)
  5241. {
  5242. $oParent = $this->GetTargetAttDef();
  5243. $res = $oParent->GetSubItemAsEditValue($this->Get('item_code'), $value);
  5244. return $res;
  5245. }
  5246. public function IsPartOfFingerprint()
  5247. {
  5248. return false;
  5249. }
  5250. static public function GetFormFieldClass()
  5251. {
  5252. return '\\Combodo\\iTop\\Form\\Field\\LabelField';
  5253. }
  5254. public function MakeFormField(DBObject $oObject, $oFormField = null)
  5255. {
  5256. if ($oFormField === null)
  5257. {
  5258. $sFormFieldClass = static::GetFormFieldClass();
  5259. $oFormField = new $sFormFieldClass($this->GetCode());
  5260. }
  5261. parent::MakeFormField($oObject, $oFormField);
  5262. // Note : As of today, this attribute is -by nature- only supported in readonly mode, not edition
  5263. $sAttCode = $this->GetCode();
  5264. $oFormField->SetCurrentValue(html_entity_decode($oObject->GetAsHTML($sAttCode), ENT_QUOTES, 'UTF-8'));
  5265. $oFormField->SetReadOnly(true);
  5266. return $oFormField;
  5267. }
  5268. }
  5269. /**
  5270. * One way encrypted (hashed) password
  5271. */
  5272. class AttributeOneWayPassword extends AttributeDefinition
  5273. {
  5274. static public function ListExpectedParams()
  5275. {
  5276. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  5277. }
  5278. public function GetEditClass() {return "One Way Password";}
  5279. public function IsDirectField() {return true;}
  5280. public function IsScalar() {return true;}
  5281. public function IsWritable() {return true;}
  5282. public function GetDefaultValue(DBObject $oHostObject = null) {return "";}
  5283. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  5284. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  5285. public function MakeRealValue($proposedValue, $oHostObj)
  5286. {
  5287. $oPassword = $proposedValue;
  5288. if (!is_object($oPassword))
  5289. {
  5290. $oPassword = new ormPassword('', '');
  5291. $oPassword->SetPassword($proposedValue);
  5292. }
  5293. return $oPassword;
  5294. }
  5295. public function GetSQLExpressions($sPrefix = '')
  5296. {
  5297. if ($sPrefix == '')
  5298. {
  5299. $sPrefix = $this->GetCode(); // Warning: AttributeOneWayPassword does not have any sql property so code = sql !
  5300. }
  5301. $aColumns = array();
  5302. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  5303. $aColumns[''] = $sPrefix.'_hash';
  5304. $aColumns['_salt'] = $sPrefix.'_salt';
  5305. return $aColumns;
  5306. }
  5307. public function FromSQLToValue($aCols, $sPrefix = '')
  5308. {
  5309. if (!array_key_exists($sPrefix, $aCols))
  5310. {
  5311. $sAvailable = implode(', ', array_keys($aCols));
  5312. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  5313. }
  5314. $hashed = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  5315. if (!array_key_exists($sPrefix.'_salt', $aCols))
  5316. {
  5317. $sAvailable = implode(', ', array_keys($aCols));
  5318. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  5319. }
  5320. $sSalt = isset($aCols[$sPrefix.'_salt']) ? $aCols[$sPrefix.'_salt'] : '';
  5321. $value = new ormPassword($hashed, $sSalt);
  5322. return $value;
  5323. }
  5324. public function GetSQLValues($value)
  5325. {
  5326. // #@# Optimization: do not load blobs anytime
  5327. // As per mySQL doc, selecting blob columns will prevent mySQL from
  5328. // using memory in case a temporary table has to be created
  5329. // (temporary tables created on disk)
  5330. // We will have to remove the blobs from the list of attributes when doing the select
  5331. // then the use of Get() should finalize the load
  5332. if ($value instanceOf ormPassword)
  5333. {
  5334. $aValues = array();
  5335. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  5336. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  5337. }
  5338. else
  5339. {
  5340. $aValues = array();
  5341. $aValues[$this->GetCode().'_hash'] = '';
  5342. $aValues[$this->GetCode().'_salt'] = '';
  5343. }
  5344. return $aValues;
  5345. }
  5346. public function GetSQLColumns($bFullSpec = false)
  5347. {
  5348. $aColumns = array();
  5349. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  5350. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  5351. return $aColumns;
  5352. }
  5353. public function GetImportColumns()
  5354. {
  5355. $aColumns = array();
  5356. $aColumns[$this->GetCode()] = 'TINYTEXT';
  5357. return $aColumns;
  5358. }
  5359. public function FromImportToValue($aCols, $sPrefix = '')
  5360. {
  5361. if (!isset($aCols[$sPrefix]))
  5362. {
  5363. $sAvailable = implode(', ', array_keys($aCols));
  5364. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  5365. }
  5366. $sClearPwd = $aCols[$sPrefix];
  5367. $oPassword = new ormPassword('', '');
  5368. $oPassword->SetPassword($sClearPwd);
  5369. return $oPassword;
  5370. }
  5371. public function GetFilterDefinitions()
  5372. {
  5373. return array();
  5374. // still not working... see later...
  5375. }
  5376. public function GetBasicFilterOperators()
  5377. {
  5378. return array();
  5379. }
  5380. public function GetBasicFilterLooseOperator()
  5381. {
  5382. return '=';
  5383. }
  5384. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5385. {
  5386. return 'true';
  5387. }
  5388. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5389. {
  5390. if (is_object($value))
  5391. {
  5392. return $value->GetAsHTML();
  5393. }
  5394. }
  5395. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5396. {
  5397. return ''; // Not exportable in CSV
  5398. }
  5399. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5400. {
  5401. return ''; // Not exportable in XML
  5402. }
  5403. public function GetValueLabel($sValue, $oHostObj = null)
  5404. {
  5405. // Don't display anything in "group by" reports
  5406. return '*****';
  5407. }
  5408. }
  5409. // Indexed array having two dimensions
  5410. class AttributeTable extends AttributeDBField
  5411. {
  5412. public function GetEditClass() {return "Table";}
  5413. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  5414. public function GetMaxSize()
  5415. {
  5416. return null;
  5417. }
  5418. public function GetNullValue()
  5419. {
  5420. return array();
  5421. }
  5422. public function IsNull($proposedValue)
  5423. {
  5424. return (count($proposedValue) == 0);
  5425. }
  5426. public function GetEditValue($sValue, $oHostObj = null)
  5427. {
  5428. return '';
  5429. }
  5430. // Facilitate things: allow the user to Set the value from a string
  5431. public function MakeRealValue($proposedValue, $oHostObj)
  5432. {
  5433. if (is_null($proposedValue))
  5434. {
  5435. return array();
  5436. }
  5437. else if (!is_array($proposedValue))
  5438. {
  5439. return array(0 => array(0 => $proposedValue));
  5440. }
  5441. return $proposedValue;
  5442. }
  5443. public function FromSQLToValue($aCols, $sPrefix = '')
  5444. {
  5445. try
  5446. {
  5447. $value = @unserialize($aCols[$sPrefix.'']);
  5448. if ($value === false)
  5449. {
  5450. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  5451. }
  5452. }
  5453. catch(Exception $e)
  5454. {
  5455. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  5456. }
  5457. return $value;
  5458. }
  5459. public function GetSQLValues($value)
  5460. {
  5461. $aValues = array();
  5462. $aValues[$this->Get("sql")] = serialize($value);
  5463. return $aValues;
  5464. }
  5465. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5466. {
  5467. if (!is_array($value))
  5468. {
  5469. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  5470. }
  5471. if (count($value) == 0)
  5472. {
  5473. return "";
  5474. }
  5475. $sRes = "<TABLE class=\"listResults\">";
  5476. $sRes .= "<TBODY>";
  5477. foreach($value as $iRow => $aRawData)
  5478. {
  5479. $sRes .= "<TR>";
  5480. foreach ($aRawData as $iCol => $cell)
  5481. {
  5482. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  5483. $sRes .= "<TD>$sCell</TD>";
  5484. }
  5485. $sRes .= "</TR>";
  5486. }
  5487. $sRes .= "</TBODY>";
  5488. $sRes .= "</TABLE>";
  5489. return $sRes;
  5490. }
  5491. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5492. {
  5493. // Not implemented
  5494. return '';
  5495. }
  5496. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5497. {
  5498. if (count($value) == 0)
  5499. {
  5500. return "";
  5501. }
  5502. $sRes = "";
  5503. foreach($value as $iRow => $aRawData)
  5504. {
  5505. $sRes .= "<row>";
  5506. foreach ($aRawData as $iCol => $cell)
  5507. {
  5508. $sCell = Str::pure2xml((string)$cell);
  5509. $sRes .= "<cell icol=\"$iCol\">$sCell</cell>";
  5510. }
  5511. $sRes .= "</row>";
  5512. }
  5513. return $sRes;
  5514. }
  5515. }
  5516. // The PHP value is a hash array, it is stored as a TEXT column
  5517. class AttributePropertySet extends AttributeTable
  5518. {
  5519. public function GetEditClass() {return "PropertySet";}
  5520. // Facilitate things: allow the user to Set the value from a string
  5521. public function MakeRealValue($proposedValue, $oHostObj)
  5522. {
  5523. if (!is_array($proposedValue))
  5524. {
  5525. return array('?' => (string)$proposedValue);
  5526. }
  5527. return $proposedValue;
  5528. }
  5529. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5530. {
  5531. if (!is_array($value))
  5532. {
  5533. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  5534. }
  5535. if (count($value) == 0)
  5536. {
  5537. return "";
  5538. }
  5539. $sRes = "<TABLE class=\"listResults\">";
  5540. $sRes .= "<TBODY>";
  5541. foreach($value as $sProperty => $sValue)
  5542. {
  5543. if ($sProperty == 'auth_pwd')
  5544. {
  5545. $sValue = '*****';
  5546. }
  5547. $sRes .= "<TR>";
  5548. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  5549. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  5550. $sRes .= "</TR>";
  5551. }
  5552. $sRes .= "</TBODY>";
  5553. $sRes .= "</TABLE>";
  5554. return $sRes;
  5555. }
  5556. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5557. {
  5558. if (count($value) == 0)
  5559. {
  5560. return "";
  5561. }
  5562. $aRes = array();
  5563. foreach($value as $sProperty => $sValue)
  5564. {
  5565. if ($sProperty == 'auth_pwd')
  5566. {
  5567. $sValue = '*****';
  5568. }
  5569. $sFrom = array(',', '=');
  5570. $sTo = array('\,', '\=');
  5571. $aRes[] = $sProperty.'='.str_replace($sFrom, $sTo, (string)$sValue);
  5572. }
  5573. $sRaw = implode(',', $aRes);
  5574. $sFrom = array("\r\n", $sTextQualifier);
  5575. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5576. $sEscaped = str_replace($sFrom, $sTo, $sRaw);
  5577. return $sTextQualifier.$sEscaped.$sTextQualifier;
  5578. }
  5579. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5580. {
  5581. if (count($value) == 0)
  5582. {
  5583. return "";
  5584. }
  5585. $sRes = "";
  5586. foreach($value as $sProperty => $sValue)
  5587. {
  5588. if ($sProperty == 'auth_pwd')
  5589. {
  5590. $sValue = '*****';
  5591. }
  5592. $sRes .= "<property id=\"$sProperty\">";
  5593. $sRes .= Str::pure2xml((string)$sValue);
  5594. $sRes .= "</property>";
  5595. }
  5596. return $sRes;
  5597. }
  5598. }
  5599. /**
  5600. * The attribute dedicated to the friendly name automatic attribute (not written)
  5601. *
  5602. * @package iTopORM
  5603. */
  5604. class AttributeComputedFieldVoid extends AttributeDefinition
  5605. {
  5606. static public function ListExpectedParams()
  5607. {
  5608. return array_merge(parent::ListExpectedParams(), array());
  5609. }
  5610. public function GetEditClass() {return "";}
  5611. public function GetValuesDef() {return null;}
  5612. public function GetPrerequisiteAttributes($sClass = null) {return $this->GetOptional("depends_on", array());}
  5613. public function IsDirectField() {return true;}
  5614. public function IsScalar() {return true;}
  5615. public function IsWritable() {return false;}
  5616. public function GetSQLExpr()
  5617. {
  5618. return null;
  5619. }
  5620. public function GetDefaultValue(DBObject $oHostObject = null) {return $this->MakeRealValue("", $oHostObject);}
  5621. public function IsNullAllowed() {return false;}
  5622. //
  5623. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  5624. public function GetSQLExpressions($sPrefix = '')
  5625. {
  5626. if ($sPrefix == '')
  5627. {
  5628. $sPrefix = $this->GetCode(); // Warning AttributeComputedFieldVoid does not have any sql property
  5629. }
  5630. return array('' => $sPrefix);
  5631. }
  5632. public function FromSQLToValue($aCols, $sPrefix = '')
  5633. {
  5634. return null;
  5635. }
  5636. public function GetSQLValues($value)
  5637. {
  5638. return array();
  5639. }
  5640. public function GetSQLColumns($bFullSpec = false)
  5641. {
  5642. return array();
  5643. }
  5644. public function GetFilterDefinitions()
  5645. {
  5646. return array($this->GetCode() => new FilterFromAttribute($this));
  5647. }
  5648. public function GetBasicFilterOperators()
  5649. {
  5650. return array("="=>"equals", "!="=>"differs from");
  5651. }
  5652. public function GetBasicFilterLooseOperator()
  5653. {
  5654. return "=";
  5655. }
  5656. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5657. {
  5658. $sQValue = CMDBSource::Quote($value);
  5659. switch ($sOpCode)
  5660. {
  5661. case '!=':
  5662. return $this->GetSQLExpr()." != $sQValue";
  5663. break;
  5664. case '=':
  5665. default:
  5666. return $this->GetSQLExpr()." = $sQValue";
  5667. }
  5668. }
  5669. public function IsPartOfFingerprint() { return false; }
  5670. }
  5671. /**
  5672. * The attribute dedicated to the friendly name automatic attribute (not written)
  5673. *
  5674. * @package iTopORM
  5675. */
  5676. class AttributeFriendlyName extends AttributeComputedFieldVoid
  5677. {
  5678. public function __construct($sCode, $sExtKeyAttCode)
  5679. {
  5680. $this->m_sCode = $sCode;
  5681. $aParams = array();
  5682. // $aParams["is_null_allowed"] = false,
  5683. $aParams["default_value"] = '';
  5684. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  5685. parent::__construct($sCode, $aParams);
  5686. $this->m_sValue = $this->Get("default_value");
  5687. }
  5688. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  5689. public function GetExtAttCode() {return 'friendlyname';}
  5690. public function GetLabel($sDefault = null)
  5691. {
  5692. $sLabel = parent::GetLabel('');
  5693. if (strlen($sLabel) == 0)
  5694. {
  5695. $sKeyAttCode = $this->Get("extkey_attcode");
  5696. if ($sKeyAttCode == 'id')
  5697. {
  5698. return Dict::S('Core:FriendlyName-Label');
  5699. }
  5700. else
  5701. {
  5702. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  5703. $sLabel = $oExtKeyAttDef->GetLabel($this->m_sCode);
  5704. }
  5705. }
  5706. return $sLabel;
  5707. }
  5708. public function GetDescription($sDefault = null)
  5709. {
  5710. $sLabel = parent::GetDescription('');
  5711. if (strlen($sLabel) == 0)
  5712. {
  5713. $sKeyAttCode = $this->Get("extkey_attcode");
  5714. if ($sKeyAttCode == 'id')
  5715. {
  5716. return Dict::S('Core:FriendlyName-Description');
  5717. }
  5718. else
  5719. {
  5720. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  5721. $sLabel = $oExtKeyAttDef->GetDescription('');
  5722. }
  5723. }
  5724. return $sLabel;
  5725. }
  5726. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  5727. protected function GetSQLCol($bFullSpec = false) {return "";}
  5728. public function FromSQLToValue($aCols, $sPrefix = '')
  5729. {
  5730. $sValue = $aCols[$sPrefix];
  5731. return $sValue;
  5732. }
  5733. /**
  5734. * Encrypt the value before storing it in the database
  5735. */
  5736. public function GetSQLValues($value)
  5737. {
  5738. return array();
  5739. }
  5740. public function IsWritable()
  5741. {
  5742. return false;
  5743. }
  5744. public function IsDirectField()
  5745. {
  5746. return false;
  5747. }
  5748. public function SetFixedValue($sValue)
  5749. {
  5750. $this->m_sValue = $sValue;
  5751. }
  5752. public function GetDefaultValue(DBObject $oHostObject = null)
  5753. {
  5754. return $this->m_sValue;
  5755. }
  5756. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  5757. {
  5758. return Str::pure2html((string)$sValue);
  5759. }
  5760. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5761. {
  5762. $sFrom = array("\r\n", $sTextQualifier);
  5763. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5764. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  5765. return $sTextQualifier.$sEscaped.$sTextQualifier;
  5766. }
  5767. static function GetFormFieldClass()
  5768. {
  5769. return '\\Combodo\\iTop\\Form\\Field\\StringField';
  5770. }
  5771. public function MakeFormField(DBObject $oObject, $oFormField = null)
  5772. {
  5773. if ($oFormField === null)
  5774. {
  5775. $sFormFieldClass = static::GetFormFieldClass();
  5776. $oFormField = new $sFormFieldClass($this->GetCode());
  5777. }
  5778. $oFormField->SetReadOnly(true);
  5779. parent::MakeFormField($oObject, $oFormField);
  5780. return $oFormField;
  5781. }
  5782. // Do not display friendly names in the history of change
  5783. public function DescribeChangeAsHTML($sOldValue, $sNewValue, $sLabel = null)
  5784. {
  5785. return '';
  5786. }
  5787. public function GetBasicFilterLooseOperator()
  5788. {
  5789. return "Contains";
  5790. }
  5791. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5792. {
  5793. $sQValue = CMDBSource::Quote($value);
  5794. switch ($sOpCode)
  5795. {
  5796. case '=':
  5797. case '!=':
  5798. return $this->GetSQLExpr()." $sOpCode $sQValue";
  5799. case 'Contains':
  5800. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  5801. case 'NotLike':
  5802. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  5803. case 'Like':
  5804. default:
  5805. return $this->GetSQLExpr()." LIKE $sQValue";
  5806. }
  5807. }
  5808. public function IsPartOfFingerprint() { return false; }
  5809. }
  5810. /**
  5811. * Holds the setting for the redundancy on a specific relation
  5812. * Its value is a string, containing either:
  5813. * - 'disabled'
  5814. * - 'n', where n is a positive integer value giving the minimum count of items upstream
  5815. * - 'n%', where n is a positive integer value, giving the minimum as a percentage of the total count of items upstream
  5816. *
  5817. * @package iTopORM
  5818. */
  5819. class AttributeRedundancySettings extends AttributeDBField
  5820. {
  5821. static public function ListExpectedParams()
  5822. {
  5823. return array('sql', 'relation_code', 'from_class', 'neighbour_id', 'enabled', 'enabled_mode', 'min_up', 'min_up_type', 'min_up_mode');
  5824. }
  5825. public function GetValuesDef() {return null;}
  5826. public function GetPrerequisiteAttributes($sClass = null) {return array();}
  5827. public function GetEditClass() {return "RedundancySetting";}
  5828. protected function GetSQLCol($bFullSpec = false)
  5829. {
  5830. return "VARCHAR(20)".($bFullSpec ? $this->GetSQLColSpec() : '');
  5831. }
  5832. public function GetValidationPattern()
  5833. {
  5834. return "^[0-9]{1,3}|[0-9]{1,2}%|disabled$";
  5835. }
  5836. public function GetMaxSize()
  5837. {
  5838. return 20;
  5839. }
  5840. public function GetDefaultValue(DBObject $oHostObject = null)
  5841. {
  5842. $sRet = 'disabled';
  5843. if ($this->Get('enabled'))
  5844. {
  5845. if ($this->Get('min_up_type') == 'count')
  5846. {
  5847. $sRet = (string) $this->Get('min_up');
  5848. }
  5849. else // percent
  5850. {
  5851. $sRet = $this->Get('min_up').'%';
  5852. }
  5853. }
  5854. return $sRet;
  5855. }
  5856. public function IsNullAllowed()
  5857. {
  5858. return false;
  5859. }
  5860. public function GetNullValue()
  5861. {
  5862. return '';
  5863. }
  5864. public function IsNull($proposedValue)
  5865. {
  5866. return ($proposedValue == '');
  5867. }
  5868. public function MakeRealValue($proposedValue, $oHostObj)
  5869. {
  5870. if (is_null($proposedValue)) return '';
  5871. return (string)$proposedValue;
  5872. }
  5873. public function ScalarToSQL($value)
  5874. {
  5875. if (!is_string($value))
  5876. {
  5877. throw new CoreException('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetHostClass(), 'attribute' => $this->GetCode()));
  5878. }
  5879. return $value;
  5880. }
  5881. public function GetRelationQueryData()
  5882. {
  5883. foreach (MetaModel::EnumRelationQueries($this->GetHostClass(), $this->Get('relation_code'), false) as $sDummy => $aQueryInfo)
  5884. {
  5885. if ($aQueryInfo['sFromClass'] == $this->Get('from_class'))
  5886. {
  5887. if ($aQueryInfo['sNeighbour'] == $this->Get('neighbour_id'))
  5888. {
  5889. return $aQueryInfo;
  5890. }
  5891. }
  5892. }
  5893. }
  5894. /**
  5895. * Find the user option label
  5896. * @param user option : disabled|cout|percent
  5897. */
  5898. public function GetUserOptionFormat($sUserOption, $sDefault = null)
  5899. {
  5900. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, null, true /*user lang*/);
  5901. if (is_null($sLabel))
  5902. {
  5903. // If no default value is specified, let's define the most relevant one for developping purposes
  5904. if (is_null($sDefault))
  5905. {
  5906. $sDefault = str_replace('_', ' ', $this->m_sCode.':'.$sUserOption.'(%1$s)');
  5907. }
  5908. // Browse the hierarchy again, accepting default (english) translations
  5909. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, $sDefault, false);
  5910. }
  5911. return $sLabel;
  5912. }
  5913. /**
  5914. * Override to display the value in the GUI
  5915. */
  5916. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  5917. {
  5918. $sCurrentOption = $this->GetCurrentOption($sValue);
  5919. $sClass = $oHostObject ? get_class($oHostObject) : $this->m_sHostClass;
  5920. return sprintf($this->GetUserOptionFormat($sCurrentOption), $this->GetMinUpValue($sValue), MetaModel::GetName($sClass));
  5921. }
  5922. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5923. {
  5924. $sFrom = array("\r\n", $sTextQualifier);
  5925. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5926. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  5927. return $sTextQualifier.$sEscaped.$sTextQualifier;
  5928. }
  5929. /**
  5930. * Helper to interpret the value, given the current settings and string representation of the attribute
  5931. */
  5932. public function IsEnabled($sValue)
  5933. {
  5934. if ($this->get('enabled_mode') == 'fixed')
  5935. {
  5936. $bRet = $this->get('enabled');
  5937. }
  5938. else
  5939. {
  5940. $bRet = ($sValue != 'disabled');
  5941. }
  5942. return $bRet;
  5943. }
  5944. /**
  5945. * Helper to interpret the value, given the current settings and string representation of the attribute
  5946. */
  5947. public function GetMinUpType($sValue)
  5948. {
  5949. if ($this->get('min_up_mode') == 'fixed')
  5950. {
  5951. $sRet = $this->get('min_up_type');
  5952. }
  5953. else
  5954. {
  5955. $sRet = 'count';
  5956. if (substr(trim($sValue), -1, 1) == '%')
  5957. {
  5958. $sRet = 'percent';
  5959. }
  5960. }
  5961. return $sRet;
  5962. }
  5963. /**
  5964. * Helper to interpret the value, given the current settings and string representation of the attribute
  5965. */
  5966. public function GetMinUpValue($sValue)
  5967. {
  5968. if ($this->get('min_up_mode') == 'fixed')
  5969. {
  5970. $iRet = (int) $this->Get('min_up');
  5971. }
  5972. else
  5973. {
  5974. $sRefValue = $sValue;
  5975. if (substr(trim($sValue), -1, 1) == '%')
  5976. {
  5977. $sRefValue = substr(trim($sValue), 0, -1);
  5978. }
  5979. $iRet = (int) trim($sRefValue);
  5980. }
  5981. return $iRet;
  5982. }
  5983. /**
  5984. * Helper to determine if the redundancy can be viewed/edited by the end-user
  5985. */
  5986. public function IsVisible()
  5987. {
  5988. $bRet = false;
  5989. if ($this->Get('enabled_mode') == 'fixed')
  5990. {
  5991. $bRet = $this->Get('enabled');
  5992. }
  5993. elseif ($this->Get('enabled_mode') == 'user')
  5994. {
  5995. $bRet = true;
  5996. }
  5997. return $bRet;
  5998. }
  5999. public function IsWritable()
  6000. {
  6001. if (($this->Get('enabled_mode') == 'fixed') && ($this->Get('min_up_mode') == 'fixed'))
  6002. {
  6003. return false;
  6004. }
  6005. return true;
  6006. }
  6007. /**
  6008. * Returns an HTML form that can be read by ReadValueFromPostedForm
  6009. */
  6010. public function GetDisplayForm($sCurrentValue, $oPage, $bEditMode = false, $sFormPrefix = '')
  6011. {
  6012. $sRet = '';
  6013. $aUserOptions = $this->GetUserOptions($sCurrentValue);
  6014. if (count($aUserOptions) < 2)
  6015. {
  6016. $bEditOption = false;
  6017. }
  6018. else
  6019. {
  6020. $bEditOption = $bEditMode;
  6021. }
  6022. $sCurrentOption = $this->GetCurrentOption($sCurrentValue);
  6023. foreach($aUserOptions as $sUserOption)
  6024. {
  6025. $bSelected = ($sUserOption == $sCurrentOption);
  6026. $sRet .= '<div>';
  6027. $sRet .= $this->GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditOption, $sUserOption, $bSelected);
  6028. $sRet .= '</div>';
  6029. }
  6030. return $sRet;
  6031. }
  6032. const USER_OPTION_DISABLED = 'disabled';
  6033. const USER_OPTION_ENABLED_COUNT = 'count';
  6034. const USER_OPTION_ENABLED_PERCENT = 'percent';
  6035. /**
  6036. * Depending on the xxx_mode parameters, build the list of options that are allowed to the end-user
  6037. */
  6038. protected function GetUserOptions($sValue)
  6039. {
  6040. $aRet = array();
  6041. if ($this->Get('enabled_mode') == 'user')
  6042. {
  6043. $aRet[] = self::USER_OPTION_DISABLED;
  6044. }
  6045. if ($this->Get('min_up_mode') == 'user')
  6046. {
  6047. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  6048. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  6049. }
  6050. else
  6051. {
  6052. if ($this->GetMinUpType($sValue) == 'count')
  6053. {
  6054. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  6055. }
  6056. else
  6057. {
  6058. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  6059. }
  6060. }
  6061. return $aRet;
  6062. }
  6063. /**
  6064. * Convert the string representation into one of the existing options
  6065. */
  6066. protected function GetCurrentOption($sValue)
  6067. {
  6068. $sRet = self::USER_OPTION_DISABLED;
  6069. if ($this->IsEnabled($sValue))
  6070. {
  6071. if ($this->GetMinUpType($sValue) == 'count')
  6072. {
  6073. $sRet = self::USER_OPTION_ENABLED_COUNT;
  6074. }
  6075. else
  6076. {
  6077. $sRet = self::USER_OPTION_ENABLED_PERCENT;
  6078. }
  6079. }
  6080. return $sRet;
  6081. }
  6082. /**
  6083. * Display an option (form, or current value)
  6084. */
  6085. protected function GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditMode, $sUserOption, $bSelected = true)
  6086. {
  6087. $sRet = '';
  6088. $iCurrentValue = $this->GetMinUpValue($sCurrentValue);
  6089. if ($bEditMode)
  6090. {
  6091. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  6092. switch ($sUserOption)
  6093. {
  6094. case self::USER_OPTION_DISABLED:
  6095. $sValue = ''; // Empty placeholder
  6096. break;
  6097. case self::USER_OPTION_ENABLED_COUNT:
  6098. if ($bEditMode)
  6099. {
  6100. $sName = $sHtmlNamesPrefix.'_min_up_count';
  6101. $sEditValue = $bSelected ? $iCurrentValue : '';
  6102. $sValue = '<input class="redundancy-min-up-count" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  6103. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  6104. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  6105. }
  6106. else
  6107. {
  6108. $sValue = $iCurrentValue;
  6109. }
  6110. break;
  6111. case self::USER_OPTION_ENABLED_PERCENT:
  6112. if ($bEditMode)
  6113. {
  6114. $sName = $sHtmlNamesPrefix.'_min_up_percent';
  6115. $sEditValue = $bSelected ? $iCurrentValue : '';
  6116. $sValue = '<input class="redundancy-min-up-percent" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  6117. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  6118. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  6119. }
  6120. else
  6121. {
  6122. $sValue = $iCurrentValue;
  6123. }
  6124. break;
  6125. }
  6126. $sLabel = sprintf($this->GetUserOptionFormat($sUserOption), $sValue, MetaModel::GetName($this->GetHostClass()));
  6127. $sOptionName = $sHtmlNamesPrefix.'_user_option';
  6128. $sOptionId = $sOptionName.'_'.$sUserOption;
  6129. $sChecked = $bSelected ? 'checked' : '';
  6130. $sRet = '<input type="radio" name="'.$sOptionName.'" id="'.$sOptionId.'" value="'.$sUserOption.'"'.$sChecked.'> <label for="'.$sOptionId.'">'.$sLabel.'</label>';
  6131. }
  6132. else
  6133. {
  6134. // Read-only: display only the currently selected option
  6135. if ($bSelected)
  6136. {
  6137. $sRet = sprintf($this->GetUserOptionFormat($sUserOption), $iCurrentValue, MetaModel::GetName($this->GetHostClass()));
  6138. }
  6139. }
  6140. return $sRet;
  6141. }
  6142. /**
  6143. * Makes the string representation out of the values given by the form defined in GetDisplayForm
  6144. */
  6145. public function ReadValueFromPostedForm($sFormPrefix)
  6146. {
  6147. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  6148. $iMinUpCount = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_count', null, 'raw_data');
  6149. $iMinUpPercent = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_percent', null, 'raw_data');
  6150. $sSelectedOption = utils::ReadPostedParam($sHtmlNamesPrefix.'_user_option', null, 'raw_data');
  6151. switch ($sSelectedOption)
  6152. {
  6153. case self::USER_OPTION_ENABLED_COUNT:
  6154. $sRet = $iMinUpCount;
  6155. break;
  6156. case self::USER_OPTION_ENABLED_PERCENT:
  6157. $sRet = $iMinUpPercent.'%';
  6158. break;
  6159. case self::USER_OPTION_DISABLED:
  6160. default:
  6161. $sRet = 'disabled';
  6162. break;
  6163. }
  6164. return $sRet;
  6165. }
  6166. }
  6167. /**
  6168. * Custom fields managed by an external implementation
  6169. *
  6170. * @package iTopORM
  6171. */
  6172. class AttributeCustomFields extends AttributeDefinition
  6173. {
  6174. static public function ListExpectedParams()
  6175. {
  6176. return array_merge(parent::ListExpectedParams(), array("handler_class"));
  6177. }
  6178. public function GetEditClass() {return "CustomFields";}
  6179. public function IsWritable() {return true;}
  6180. public function LoadFromDB() {return false;} // See ReadValue...
  6181. public function GetDefaultValue(DBObject $oHostObject = null)
  6182. {
  6183. return new ormCustomFieldsValue($oHostObject, $this->GetCode());
  6184. }
  6185. public function GetBasicFilterOperators() {return array();}
  6186. public function GetBasicFilterLooseOperator() {return '';}
  6187. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  6188. /**
  6189. * @param DBObject $oHostObject
  6190. * @param array|null $aValues
  6191. * @return CustomFieldsHandler
  6192. */
  6193. public function GetHandler($aValues = null)
  6194. {
  6195. $sHandlerClass = $this->Get('handler_class');
  6196. $oHandler = new $sHandlerClass($this->GetCode());
  6197. if (!is_null($aValues))
  6198. {
  6199. $oHandler->SetCurrentValues($aValues);
  6200. }
  6201. return $oHandler;
  6202. }
  6203. public function GetPrerequisiteAttributes($sClass = null)
  6204. {
  6205. $sHandlerClass = $this->Get('handler_class');
  6206. return $sHandlerClass::GetPrerequisiteAttributes($sClass);
  6207. }
  6208. public function GetEditValue($sValue, $oHostObj = null)
  6209. {
  6210. return 'GetEditValueNotImplemented for '.get_class($this);
  6211. }
  6212. /**
  6213. * Makes the string representation out of the values given by the form defined in GetDisplayForm
  6214. */
  6215. public function ReadValueFromPostedForm($oHostObject, $sFormPrefix)
  6216. {
  6217. $aRawData = json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$this->GetCode()}", '{}', 'raw_data'), true);
  6218. return new ormCustomFieldsValue($oHostObject, $this->GetCode(), $aRawData);
  6219. }
  6220. public function MakeRealValue($proposedValue, $oHostObject)
  6221. {
  6222. if (is_object($proposedValue) && ($proposedValue instanceof ormCustomFieldsValue))
  6223. {
  6224. return $proposedValue;
  6225. }
  6226. elseif (is_string($proposedValue))
  6227. {
  6228. $aValues = json_decode($proposedValue, true);
  6229. return new ormCustomFieldsValue($oHostObject, $this->GetCode(), $aValues);
  6230. }
  6231. elseif (is_array($proposedValue))
  6232. {
  6233. return new ormCustomFieldsValue($oHostObject, $this->GetCode(), $proposedValue);
  6234. }
  6235. throw new Exception('Unexpected type for the value of a custom fields attribute: '.gettype($proposedValue));
  6236. }
  6237. static public function GetFormFieldClass()
  6238. {
  6239. return '\\Combodo\\iTop\\Form\\Field\\SubFormField';
  6240. }
  6241. /**
  6242. * Override to build the relevant form field
  6243. *
  6244. * 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.
  6245. */
  6246. public function MakeFormField(DBObject $oObject, $oFormField = null)
  6247. {
  6248. if ($oFormField === null)
  6249. {
  6250. $sFormFieldClass = static::GetFormFieldClass();
  6251. $oFormField = new $sFormFieldClass($this->GetCode());
  6252. $oFormField->SetForm($this->GetForm($oObject));
  6253. }
  6254. parent::MakeFormField($oObject, $oFormField);
  6255. return $oFormField;
  6256. }
  6257. /**
  6258. * @param DBObject $oHostObject
  6259. * @return Combodo\iTop\Form\Form
  6260. */
  6261. public function GetForm(DBObject $oHostObject, $sFormPrefix = null)
  6262. {
  6263. try
  6264. {
  6265. $oValue = $oHostObject->Get($this->GetCode());
  6266. $oHandler = $this->GetHandler($oValue->GetValues());
  6267. $sFormId = is_null($sFormPrefix) ? 'cf_'.$this->GetCode() : $sFormPrefix.'_cf_'.$this->GetCode();
  6268. $oHandler->BuildForm($oHostObject, $sFormId);
  6269. $oForm = $oHandler->GetForm();
  6270. }
  6271. catch (Exception $e)
  6272. {
  6273. $oForm = new \Combodo\iTop\Form\Form('');
  6274. $oField = new \Combodo\iTop\Form\Field\LabelField('');
  6275. $oField->SetLabel('Custom field error: '.$e->getMessage());
  6276. $oForm->AddField($oField);
  6277. $oForm->Finalize();
  6278. }
  6279. return $oForm;
  6280. }
  6281. /**
  6282. * Read the data from where it has been stored. This verb must be implemented as soon as LoadFromDB returns false and LoadInObject returns true
  6283. * @param $oHostObject
  6284. * @return ormCustomFieldsValue
  6285. */
  6286. public function ReadValue($oHostObject)
  6287. {
  6288. try
  6289. {
  6290. $oHandler = $this->GetHandler();
  6291. $aValues = $oHandler->ReadValues($oHostObject);
  6292. $oRet = new ormCustomFieldsValue($oHostObject, $this->GetCode(), $aValues);
  6293. }
  6294. catch (Exception $e)
  6295. {
  6296. $oRet = new ormCustomFieldsValue($oHostObject, $this->GetCode());
  6297. }
  6298. return $oRet;
  6299. }
  6300. /**
  6301. * Record the data (currently in the processing of recording the host object)
  6302. * It is assumed that the data has been checked prior to calling Write()
  6303. * @param DBObject $oHostObject
  6304. * @param ormCustomFieldsValue|null $oValue (null is the default value)
  6305. */
  6306. public function WriteValue(DBObject $oHostObject, ormCustomFieldsValue $oValue = null)
  6307. {
  6308. if (is_null($oValue))
  6309. {
  6310. $oHandler = $this->GetHandler();
  6311. $aValues = array();
  6312. }
  6313. else
  6314. {
  6315. // Pass the values through the form to make sure that they are correct
  6316. $oHandler = $this->GetHandler($oValue->GetValues());
  6317. $oHandler->BuildForm($oHostObject, '');
  6318. $oForm = $oHandler->GetForm();
  6319. $aValues = $oForm->GetCurrentValues();
  6320. }
  6321. return $oHandler->WriteValues($oHostObject, $aValues);
  6322. }
  6323. /**
  6324. * The part of the current attribute in the object's signature, for the supplied value
  6325. * @param $value The value of this attribute for the object
  6326. * @return string The "signature" for this field/attribute
  6327. */
  6328. public function Fingerprint($value)
  6329. {
  6330. $oHandler = $this->GetHandler($value->GetValues());
  6331. return $oHandler->GetValueFingerprint();
  6332. }
  6333. /**
  6334. * Check the validity of the data
  6335. * @param DBObject $oHostObject
  6336. * @param $value
  6337. * @return bool|string true or error message
  6338. */
  6339. public function CheckValue(DBObject $oHostObject, $value)
  6340. {
  6341. try
  6342. {
  6343. $oHandler = $this->GetHandler($value->GetValues());
  6344. $oHandler->BuildForm($oHostObject, '');
  6345. $oForm = $oHandler->GetForm();
  6346. $oForm->Validate();
  6347. if ($oForm->GetValid())
  6348. {
  6349. $ret = true;
  6350. }
  6351. else
  6352. {
  6353. $aMessages = array();
  6354. foreach ($oForm->GetErrorMessages() as $sFieldId => $aFieldMessages)
  6355. {
  6356. $aMessages[] = $sFieldId.': '.implode(', ', $aFieldMessages);
  6357. }
  6358. $ret = 'Invalid value: '.implode(', ', $aMessages);
  6359. }
  6360. }
  6361. catch (Exception $e)
  6362. {
  6363. $ret = $e->getMessage();
  6364. }
  6365. return $ret;
  6366. }
  6367. /**
  6368. * Cleanup data upon object deletion (object id still available here)
  6369. * @param DBObject $oHostObject
  6370. */
  6371. public function DeleteValue(DBObject $oHostObject)
  6372. {
  6373. $oValue = $oHostObject->Get($this->GetCode());
  6374. $oHandler = $this->GetHandler($oValue->GetValues());
  6375. return $oHandler->DeleteValues($oHostObject);
  6376. }
  6377. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  6378. {
  6379. try
  6380. {
  6381. $sRet = $value->GetAsHTML($bLocalize);
  6382. }
  6383. catch (Exception $e)
  6384. {
  6385. $sRet = 'Custom field error: '.htmlentities($e->getMessage(), ENT_QUOTES, 'UTF-8');
  6386. }
  6387. return $sRet;
  6388. }
  6389. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  6390. {
  6391. try
  6392. {
  6393. $sRet = $value->GetAsXML($bLocalize);
  6394. }
  6395. catch (Exception $e)
  6396. {
  6397. $sRet = Str::pure2xml('Custom field error: '.$e->getMessage());
  6398. }
  6399. return $sRet;
  6400. }
  6401. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  6402. {
  6403. try
  6404. {
  6405. $sRet = $value->GetAsCSV($sSeparator, $sTextQualifier, $bLocalize, $bConvertToPlainText);
  6406. }
  6407. catch (Exception $e)
  6408. {
  6409. $sFrom = array("\r\n", $sTextQualifier);
  6410. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  6411. $sEscaped = str_replace($sFrom, $sTo, 'Custom field error: '.$e->getMessage());
  6412. $sRet = $sTextQualifier.$sEscaped.$sTextQualifier;
  6413. }
  6414. return $sRet;
  6415. }
  6416. /**
  6417. * List the available verbs for 'GetForTemplate'
  6418. */
  6419. public function EnumTemplateVerbs()
  6420. {
  6421. $sHandlerClass = $this->Get('handler_class');
  6422. return $sHandlerClass::EnumTemplateVerbs();
  6423. }
  6424. /**
  6425. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  6426. * @param $value mixed The current value of the field
  6427. * @param $sVerb string The verb specifying the representation of the value
  6428. * @param $oHostObject DBObject The object
  6429. * @param $bLocalize bool Whether or not to localize the value
  6430. */
  6431. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  6432. {
  6433. try
  6434. {
  6435. $sRet = $value->GetForTemplate($sVerb, $bLocalize);
  6436. }
  6437. catch (Exception $e)
  6438. {
  6439. $sRet = 'Custom field error: '.$e->getMessage();
  6440. }
  6441. return $sRet;
  6442. }
  6443. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  6444. {
  6445. return null;
  6446. }
  6447. /**
  6448. * Helper to get a value that will be JSON encoded
  6449. * The operation is the opposite to FromJSONToValue
  6450. */
  6451. public function GetForJSON($value)
  6452. {
  6453. return null;
  6454. }
  6455. /**
  6456. * Helper to form a value, given JSON decoded data
  6457. * The operation is the opposite to GetForJSON
  6458. */
  6459. public function FromJSONToValue($json)
  6460. {
  6461. return null;
  6462. }
  6463. public function Equals($val1, $val2)
  6464. {
  6465. try
  6466. {
  6467. $bEquals = $val1->Equals($val2);
  6468. }
  6469. catch (Exception $e)
  6470. {
  6471. false;
  6472. }
  6473. return $bEquals;
  6474. }
  6475. }