attributedef.class.inc.php 215 KB

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