attributedef.class.inc.php 189 KB

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