attributedef.class.inc.php 196 KB

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