attributedef.class.inc.php 211 KB

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