attributedef.class.inc.php 217 KB

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