attributedef.class.inc.php 187 KB

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