attributedef.class.inc.php 202 KB

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