attributedef.class.inc.php 214 KB

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