attributedef.class.inc.php 187 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722
  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. }
  2617. /**
  2618. * Map a text column (size > ?), containing HTML code, to an attribute
  2619. *
  2620. * @package iTopORM
  2621. */
  2622. class AttributeHTML extends AttributeLongText
  2623. {
  2624. public function GetSQLColumns($bFullSpec = false)
  2625. {
  2626. $aColumns = array();
  2627. $aColumns[$this->GetCode()] = $this->GetSQLCol();
  2628. if ($this->GetOptional('format', null) != null )
  2629. {
  2630. // Add the extra column only if the property 'format' is specified for the attribute
  2631. $aColumns[$this->Get('sql').'_format'] = "ENUM('text','html')";
  2632. if ($bFullSpec)
  2633. {
  2634. $aColumns[$this->Get('sql').'_format'].= " DEFAULT 'html'"; // default 'html' is for migrating old records
  2635. }
  2636. }
  2637. return $aColumns;
  2638. }
  2639. /**
  2640. * The actual formatting of the text: either text (=plain text) or html (= text with HTML markup)
  2641. * @return string
  2642. */
  2643. public function GetFormat()
  2644. {
  2645. return $this->GetOptional('format', 'html'); // Defaults to HTML
  2646. }
  2647. }
  2648. /**
  2649. * Specialization of a string: email
  2650. *
  2651. * @package iTopORM
  2652. */
  2653. class AttributeEmailAddress extends AttributeString
  2654. {
  2655. public function GetValidationPattern()
  2656. {
  2657. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('email_validation_pattern').'$');
  2658. }
  2659. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2660. {
  2661. if (empty($sValue)) return '';
  2662. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  2663. }
  2664. }
  2665. /**
  2666. * Specialization of a string: IP address
  2667. *
  2668. * @package iTopORM
  2669. */
  2670. class AttributeIPAddress extends AttributeString
  2671. {
  2672. public function GetValidationPattern()
  2673. {
  2674. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  2675. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  2676. }
  2677. public function GetOrderBySQLExpressions($sClassAlias)
  2678. {
  2679. // Note: This is the responsibility of this function to place backticks around column aliases
  2680. return array('INET_ATON(`'.$sClassAlias.$this->GetCode().'`)');
  2681. }
  2682. }
  2683. /**
  2684. * Specialization of a string: OQL expression
  2685. *
  2686. * @package iTopORM
  2687. */
  2688. class AttributeOQL extends AttributeText
  2689. {
  2690. public function GetEditClass() {return "OQLExpression";}
  2691. }
  2692. /**
  2693. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2694. *
  2695. * @package iTopORM
  2696. */
  2697. class AttributeTemplateString extends AttributeString
  2698. {
  2699. }
  2700. /**
  2701. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2702. *
  2703. * @package iTopORM
  2704. */
  2705. class AttributeTemplateText extends AttributeText
  2706. {
  2707. }
  2708. /**
  2709. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2710. *
  2711. * @package iTopORM
  2712. */
  2713. class AttributeTemplateHTML extends AttributeText
  2714. {
  2715. public function GetSQLColumns($bFullSpec = false)
  2716. {
  2717. $aColumns = array();
  2718. $aColumns[$this->GetCode()] = $this->GetSQLCol();
  2719. if ($this->GetOptional('format', null) != null )
  2720. {
  2721. // Add the extra column only if the property 'format' is specified for the attribute
  2722. $aColumns[$this->Get('sql').'_format'] = "ENUM('text','html')";
  2723. if ($bFullSpec)
  2724. {
  2725. $aColumns[$this->Get('sql').'_format'].= " DEFAULT 'html'"; // default 'html' is for migrating old records
  2726. }
  2727. }
  2728. return $aColumns;
  2729. }
  2730. /**
  2731. * The actual formatting of the text: either text (=plain text) or html (= text with HTML markup)
  2732. * @return string
  2733. */
  2734. public function GetFormat()
  2735. {
  2736. return $this->GetOptional('format', 'html'); // Defaults to HTML
  2737. }
  2738. }
  2739. /**
  2740. * Map a enum column to an attribute
  2741. *
  2742. * @package iTopORM
  2743. */
  2744. class AttributeEnum extends AttributeString
  2745. {
  2746. static public function ListExpectedParams()
  2747. {
  2748. return parent::ListExpectedParams();
  2749. //return array_merge(parent::ListExpectedParams(), array());
  2750. }
  2751. public function GetEditClass() {return "String";}
  2752. protected function GetSQLCol($bFullSpec = false)
  2753. {
  2754. $oValDef = $this->GetValuesDef();
  2755. if ($oValDef)
  2756. {
  2757. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  2758. }
  2759. else
  2760. {
  2761. $aValues = array();
  2762. }
  2763. if (count($aValues) > 0)
  2764. {
  2765. // The syntax used here do matters
  2766. // In particular, I had to remove unnecessary spaces to
  2767. // make sure that this string will match the field type returned by the DB
  2768. // (used to perform a comparison between the current DB format and the data model)
  2769. return "ENUM(".implode(",", $aValues).")".($bFullSpec ? $this->GetSQLColSpec() : '');
  2770. }
  2771. else
  2772. {
  2773. return "VARCHAR(255)".($bFullSpec ? " DEFAULT ''" : ""); // ENUM() is not an allowed syntax!
  2774. }
  2775. }
  2776. protected function GetSQLColSpec()
  2777. {
  2778. $default = $this->ScalarToSQL($this->GetDefaultValue());
  2779. if (is_null($default))
  2780. {
  2781. $sRet = '';
  2782. }
  2783. else
  2784. {
  2785. // ENUMs values are strings so the default value must be a string as well,
  2786. // otherwise MySQL interprets the number as the zero-based index of the value in the list (i.e. the nth value in the list)
  2787. $sRet = " DEFAULT ".CMDBSource::Quote($default);
  2788. }
  2789. return $sRet;
  2790. }
  2791. public function ScalarToSQL($value)
  2792. {
  2793. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  2794. // but that wasn't working for enums, because '' is NOT one of the allowed values
  2795. // that's why a null value must be forced to a real null
  2796. $value = parent::ScalarToSQL($value);
  2797. if ($this->IsNull($value))
  2798. {
  2799. return null;
  2800. }
  2801. else
  2802. {
  2803. return $value;
  2804. }
  2805. }
  2806. public function RequiresIndex()
  2807. {
  2808. return false;
  2809. }
  2810. public function GetBasicFilterOperators()
  2811. {
  2812. return parent::GetBasicFilterOperators();
  2813. }
  2814. public function GetBasicFilterLooseOperator()
  2815. {
  2816. return '=';
  2817. }
  2818. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2819. {
  2820. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2821. }
  2822. public function GetValueLabel($sValue)
  2823. {
  2824. if (is_null($sValue))
  2825. {
  2826. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2827. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  2828. }
  2829. else
  2830. {
  2831. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, null, true /*user lang*/);
  2832. if (is_null($sLabel))
  2833. {
  2834. $sDefault = str_replace('_', ' ', $sValue);
  2835. // Browse the hierarchy again, accepting default (english) translations
  2836. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, $sDefault, false);
  2837. }
  2838. }
  2839. return $sLabel;
  2840. }
  2841. public function GetValueDescription($sValue)
  2842. {
  2843. if (is_null($sValue))
  2844. {
  2845. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2846. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', Dict::S('Enum:Undefined'));
  2847. }
  2848. else
  2849. {
  2850. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', '', true /* user language only */);
  2851. if (strlen($sDescription) == 0)
  2852. {
  2853. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  2854. if ($sParentClass)
  2855. {
  2856. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  2857. {
  2858. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  2859. $sDescription = $oAttDef->GetValueDescription($sValue);
  2860. }
  2861. }
  2862. }
  2863. }
  2864. return $sDescription;
  2865. }
  2866. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2867. {
  2868. if ($bLocalize)
  2869. {
  2870. $sLabel = $this->GetValueLabel($sValue);
  2871. $sDescription = $this->GetValueDescription($sValue);
  2872. // later, we could imagine a detailed description in the title
  2873. $sRes = "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  2874. }
  2875. else
  2876. {
  2877. $sRes = parent::GetAsHtml($sValue, $oHostObject, $bLocalize);
  2878. }
  2879. return $sRes;
  2880. }
  2881. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2882. {
  2883. if (is_null($value))
  2884. {
  2885. $sFinalValue = '';
  2886. }
  2887. elseif ($bLocalize)
  2888. {
  2889. $sFinalValue = $this->GetValueLabel($value);
  2890. }
  2891. else
  2892. {
  2893. $sFinalValue = $value;
  2894. }
  2895. $sRes = parent::GetAsXML($sFinalValue, $oHostObject, $bLocalize);
  2896. return $sRes;
  2897. }
  2898. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  2899. {
  2900. if (is_null($sValue))
  2901. {
  2902. $sFinalValue = '';
  2903. }
  2904. elseif ($bLocalize)
  2905. {
  2906. $sFinalValue = $this->GetValueLabel($sValue);
  2907. }
  2908. else
  2909. {
  2910. $sFinalValue = $sValue;
  2911. }
  2912. $sRes = parent::GetAsCSV($sFinalValue, $sSeparator, $sTextQualifier, $oHostObject, $bLocalize);
  2913. return $sRes;
  2914. }
  2915. static public function GetFormFieldClass()
  2916. {
  2917. return '\\Combodo\\iTop\\Form\\Field\\RadioField';
  2918. }
  2919. public function MakeFormField(DBObject $oObject, $oFormField = null)
  2920. {
  2921. if ($oFormField === null)
  2922. {
  2923. // TODO : We should check $this->Get('display_style') and create a Radio / Select / ... regarding its value
  2924. $sFormFieldClass = static::GetFormFieldClass();
  2925. $oFormField = new $sFormFieldClass($this->GetCode());
  2926. }
  2927. $oFormField->SetChoices($this->GetAllowedValues($oObject->ToArgsForQuery()));
  2928. parent::MakeFormField($oObject, $oFormField);
  2929. return $oFormField;
  2930. }
  2931. public function GetEditValue($sValue, $oHostObj = null)
  2932. {
  2933. if (is_null($sValue))
  2934. {
  2935. return '';
  2936. }
  2937. else
  2938. {
  2939. return $this->GetValueLabel($sValue);
  2940. }
  2941. }
  2942. /**
  2943. * Helper to get a value that will be JSON encoded
  2944. * The operation is the opposite to FromJSONToValue
  2945. */
  2946. public function GetForJSON($value)
  2947. {
  2948. return $value;
  2949. }
  2950. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2951. {
  2952. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  2953. if (is_null($aRawValues)) return null;
  2954. $aLocalizedValues = array();
  2955. foreach ($aRawValues as $sKey => $sValue)
  2956. {
  2957. $aLocalizedValues[$sKey] = Str::pure2html($this->GetValueLabel($sKey));
  2958. }
  2959. return $aLocalizedValues;
  2960. }
  2961. /**
  2962. * An enum can be localized
  2963. */
  2964. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  2965. {
  2966. if ($bLocalizedValue)
  2967. {
  2968. // Lookup for the value matching the input
  2969. //
  2970. $sFoundValue = null;
  2971. $aRawValues = parent::GetAllowedValues();
  2972. if (!is_null($aRawValues))
  2973. {
  2974. foreach ($aRawValues as $sKey => $sValue)
  2975. {
  2976. $sRefValue = $this->GetValueLabel($sKey);
  2977. if ($sProposedValue == $sRefValue)
  2978. {
  2979. $sFoundValue = $sKey;
  2980. break;
  2981. }
  2982. }
  2983. }
  2984. if (is_null($sFoundValue))
  2985. {
  2986. return null;
  2987. }
  2988. return $this->MakeRealValue($sFoundValue, null);
  2989. }
  2990. else
  2991. {
  2992. return parent::MakeValueFromString($sProposedValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue, $sAttributeQualifier);
  2993. }
  2994. }
  2995. /**
  2996. * Processes the input value to align it with the values supported
  2997. * by this type of attribute. In this case: turns empty strings into nulls
  2998. * @param mixed $proposedValue The value to be set for the attribute
  2999. * @return mixed The actual value that will be set
  3000. */
  3001. public function MakeRealValue($proposedValue, $oHostObj)
  3002. {
  3003. if ($proposedValue == '') return null;
  3004. return parent::MakeRealValue($proposedValue, $oHostObj);
  3005. }
  3006. public function GetOrderByHint()
  3007. {
  3008. $aValues = $this->GetAllowedValues();
  3009. return Dict::Format('UI:OrderByHint_Values', implode(', ', $aValues));
  3010. }
  3011. }
  3012. /**
  3013. * A meta enum is an aggregation of enum from subclasses into an enum of a base class
  3014. * It has been designed is to cope with the fact that statuses must be defined in leaf classes, while it makes sense to
  3015. * have a superstatus available on the root classe(s)
  3016. *
  3017. * @package iTopORM
  3018. */
  3019. class AttributeMetaEnum extends AttributeEnum
  3020. {
  3021. static public function ListExpectedParams()
  3022. {
  3023. return array('allowed_values', 'sql', 'default_value', 'mapping');
  3024. }
  3025. public function IsWritable()
  3026. {
  3027. return false;
  3028. }
  3029. public function RequiresIndex()
  3030. {
  3031. return true;
  3032. }
  3033. public function GetPrerequisiteAttributes($sClass = null)
  3034. {
  3035. if (is_null($sClass))
  3036. {
  3037. $sClass = $this->GetHostClass();
  3038. }
  3039. $aMappingData = $this->GetMapRule($sClass);
  3040. if ($aMappingData == null)
  3041. {
  3042. $aRet = array();
  3043. }
  3044. else
  3045. {
  3046. $aRet = array($aMappingData['attcode']);
  3047. }
  3048. return $aRet;
  3049. }
  3050. /**
  3051. * Overload the standard so as to leave the data unsorted
  3052. *
  3053. * @param array $aArgs
  3054. * @param string $sContains
  3055. * @return array|null
  3056. */
  3057. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3058. {
  3059. $oValSetDef = $this->GetValuesDef();
  3060. if (!$oValSetDef) return null;
  3061. $aRawValues = $oValSetDef->GetValueList();
  3062. if (is_null($aRawValues)) return null;
  3063. $aLocalizedValues = array();
  3064. foreach ($aRawValues as $sKey => $sValue)
  3065. {
  3066. $aLocalizedValues[$sKey] = Str::pure2html($this->GetValueLabel($sKey));
  3067. }
  3068. return $aLocalizedValues;
  3069. }
  3070. /**
  3071. * Returns the meta value for the given object.
  3072. * See also MetaModel::RebuildMetaEnums() that must be maintained when MapValue changes
  3073. *
  3074. * @param $oObject
  3075. * @return mixed
  3076. * @throws Exception
  3077. */
  3078. public function MapValue($oObject)
  3079. {
  3080. $aMappingData = $this->GetMapRule(get_class($oObject));
  3081. if ($aMappingData == null)
  3082. {
  3083. $sRet = $this->GetDefaultValue();
  3084. }
  3085. else
  3086. {
  3087. $sAttCode = $aMappingData['attcode'];
  3088. $value = $oObject->Get($sAttCode);
  3089. if (array_key_exists($value, $aMappingData['values']))
  3090. {
  3091. $sRet = $aMappingData['values'][$value];
  3092. }
  3093. elseif ($this->GetDefaultValue() != '')
  3094. {
  3095. $sRet = $this->GetDefaultValue();
  3096. }
  3097. else
  3098. {
  3099. 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());
  3100. }
  3101. }
  3102. return $sRet;
  3103. }
  3104. public function GetMapRule($sClass)
  3105. {
  3106. $aMappings = $this->Get('mapping');
  3107. if (array_key_exists($sClass, $aMappings))
  3108. {
  3109. $aMappingData = $aMappings[$sClass];
  3110. }
  3111. else
  3112. {
  3113. $sParent = MetaModel::GetParentClass($sClass);
  3114. $aMappingData = $this->GetMapRule($sParent);
  3115. }
  3116. return $aMappingData;
  3117. }
  3118. }
  3119. /**
  3120. * Map a date+time column to an attribute
  3121. *
  3122. * @package iTopORM
  3123. */
  3124. class AttributeDateTime extends AttributeDBField
  3125. {
  3126. static public function GetDateFormat()
  3127. {
  3128. return "Y-m-d H:i:s";
  3129. }
  3130. static public function ListExpectedParams()
  3131. {
  3132. return parent::ListExpectedParams();
  3133. //return array_merge(parent::ListExpectedParams(), array());
  3134. }
  3135. public function GetEditClass() {return "DateTime";}
  3136. protected function GetSQLCol($bFullSpec = false) {return "DATETIME";}
  3137. public static function GetAsUnixSeconds($value)
  3138. {
  3139. $oDeadlineDateTime = new DateTime($value);
  3140. $iUnixSeconds = $oDeadlineDateTime->format('U');
  3141. return $iUnixSeconds;
  3142. }
  3143. // This has been done at the time when itop was using TIMESTAMP columns,
  3144. // now that iTop is using DATETIME columns, it seems possible to have IsNullAllowed returning false... later when this is needed
  3145. public function IsNullAllowed() {return true;}
  3146. public function GetDefaultValue(DBObject $oHostObject = null)
  3147. {
  3148. $default = parent::GetDefaultValue($oHostObject);
  3149. if (!parent::IsNullAllowed())
  3150. {
  3151. if (empty($default))
  3152. {
  3153. $default = date($this->GetDateFormat());
  3154. }
  3155. }
  3156. return $default;
  3157. }
  3158. // END OF THE WORKAROUND
  3159. ///////////////////////////////////////////////////////////////
  3160. public function GetValidationPattern()
  3161. {
  3162. 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)$";
  3163. }
  3164. public function GetBasicFilterOperators()
  3165. {
  3166. return array(
  3167. "="=>"equals",
  3168. "!="=>"differs from",
  3169. "<"=>"before",
  3170. "<="=>"before",
  3171. ">"=>"after (strictly)",
  3172. ">="=>"after",
  3173. "SameDay"=>"same day (strip time)",
  3174. "SameMonth"=>"same year/month",
  3175. "SameYear"=>"same year",
  3176. "Today"=>"today",
  3177. ">|"=>"after today + N days",
  3178. "<|"=>"before today + N days",
  3179. "=|"=>"equals today + N days",
  3180. );
  3181. }
  3182. public function GetBasicFilterLooseOperator()
  3183. {
  3184. // Unless we implement a "same xxx, depending on given precision" !
  3185. return "=";
  3186. }
  3187. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3188. {
  3189. $sQValue = CMDBSource::Quote($value);
  3190. switch ($sOpCode)
  3191. {
  3192. case '=':
  3193. case '!=':
  3194. case '<':
  3195. case '<=':
  3196. case '>':
  3197. case '>=':
  3198. return $this->GetSQLExpr()." $sOpCode $sQValue";
  3199. case 'SameDay':
  3200. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  3201. case 'SameMonth':
  3202. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  3203. case 'SameYear':
  3204. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  3205. case 'Today':
  3206. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  3207. case '>|':
  3208. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  3209. case '<|':
  3210. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  3211. case '=|':
  3212. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  3213. default:
  3214. return $this->GetSQLExpr()." = $sQValue";
  3215. }
  3216. }
  3217. public function MakeRealValue($proposedValue, $oHostObj)
  3218. {
  3219. if (is_null($proposedValue))
  3220. {
  3221. return null;
  3222. }
  3223. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  3224. {
  3225. return null;
  3226. }
  3227. if (!is_numeric($proposedValue))
  3228. {
  3229. return $proposedValue;
  3230. }
  3231. return date(self::GetDateFormat(), $proposedValue);
  3232. }
  3233. public function ScalarToSQL($value)
  3234. {
  3235. if (is_null($value))
  3236. {
  3237. return null;
  3238. }
  3239. elseif (empty($value))
  3240. {
  3241. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  3242. return '0000-00-00 00:00:00';
  3243. }
  3244. return $value;
  3245. }
  3246. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3247. {
  3248. return Str::pure2html($value);
  3249. }
  3250. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3251. {
  3252. return Str::pure2xml($value);
  3253. }
  3254. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  3255. {
  3256. $sFrom = array("\r\n", $sTextQualifier);
  3257. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  3258. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  3259. return $sTextQualifier.$sEscaped.$sTextQualifier;
  3260. }
  3261. /**
  3262. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  3263. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  3264. * does nothing special, and just calls the default (loose) operator
  3265. * @param string $sSearchText The search string to analyze for smart patterns
  3266. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  3267. * @param Hash $aParams Values of the query parameters
  3268. * @return Expression The search condition to be added (AND) to the current search
  3269. */
  3270. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  3271. {
  3272. // Possible smart patterns
  3273. $aPatterns = array(
  3274. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  3275. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  3276. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  3277. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  3278. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  3279. );
  3280. $sPatternFound = '';
  3281. $aMatches = array();
  3282. foreach($aPatterns as $sPatName => $sPattern)
  3283. {
  3284. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  3285. {
  3286. $sPatternFound = $sPatName;
  3287. break;
  3288. }
  3289. }
  3290. switch($sPatternFound)
  3291. {
  3292. case 'between':
  3293. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  3294. $oRightExpr = new VariableExpression($sParamName1);
  3295. $aParams[$sParamName1] = $aMatches[1];
  3296. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  3297. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  3298. $oRightExpr = new VariableExpression($sParamName2);
  3299. $sOperator = $this->GetBasicFilterLooseOperator();
  3300. $aParams[$sParamName2] = $aMatches[2];
  3301. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  3302. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  3303. break;
  3304. case 'greater than':
  3305. case 'greater than or equal':
  3306. case 'less than':
  3307. case 'less than or equal':
  3308. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  3309. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  3310. $oRightExpr = new VariableExpression($sParamName);
  3311. $aParams[$sParamName] = $aMatches[1];
  3312. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  3313. break;
  3314. default:
  3315. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  3316. }
  3317. return $oNewCondition;
  3318. }
  3319. }
  3320. /**
  3321. * Store a duration as a number of seconds
  3322. *
  3323. * @package iTopORM
  3324. */
  3325. class AttributeDuration extends AttributeInteger
  3326. {
  3327. public function GetEditClass() {return "Duration";}
  3328. protected function GetSQLCol($bFullSpec = false) {return "INT(11) UNSIGNED";}
  3329. public function GetNullValue() {return '0';}
  3330. public function MakeRealValue($proposedValue, $oHostObj)
  3331. {
  3332. if (is_null($proposedValue)) return null;
  3333. if (!is_numeric($proposedValue)) return null;
  3334. if ( ((int)$proposedValue) < 0) return null;
  3335. return (int)$proposedValue;
  3336. }
  3337. public function ScalarToSQL($value)
  3338. {
  3339. if (is_null($value))
  3340. {
  3341. return null;
  3342. }
  3343. return $value;
  3344. }
  3345. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3346. {
  3347. return Str::pure2html(self::FormatDuration($value));
  3348. }
  3349. public static function FormatDuration($duration)
  3350. {
  3351. $aDuration = self::SplitDuration($duration);
  3352. $sResult = '';
  3353. if ($duration < 60)
  3354. {
  3355. // Less than 1 min
  3356. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  3357. }
  3358. else if ($duration < 3600)
  3359. {
  3360. // less than 1 hour, display it in minutes/seconds
  3361. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  3362. }
  3363. else if ($duration < 86400)
  3364. {
  3365. // Less than 1 day, display it in hours/minutes/seconds
  3366. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  3367. }
  3368. else
  3369. {
  3370. // more than 1 day, display it in days/hours/minutes/seconds
  3371. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  3372. }
  3373. return $sResult;
  3374. }
  3375. static function SplitDuration($duration)
  3376. {
  3377. $duration = (int) $duration;
  3378. $days = floor($duration / 86400);
  3379. $hours = floor(($duration - (86400*$days)) / 3600);
  3380. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  3381. $seconds = ($duration % 60); // modulo
  3382. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  3383. }
  3384. }
  3385. /**
  3386. * Map a date+time column to an attribute
  3387. *
  3388. * @package iTopORM
  3389. */
  3390. class AttributeDate extends AttributeDateTime
  3391. {
  3392. const MYDATEFORMAT = "Y-m-d";
  3393. static public function GetDateFormat()
  3394. {
  3395. return "Y-m-d";
  3396. }
  3397. static public function ListExpectedParams()
  3398. {
  3399. return parent::ListExpectedParams();
  3400. //return array_merge(parent::ListExpectedParams(), array());
  3401. }
  3402. public function GetEditClass() {return "Date";}
  3403. protected function GetSQLCol($bFullSpec = false) {return "DATE";}
  3404. public function GetValidationPattern()
  3405. {
  3406. 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)))$";
  3407. }
  3408. }
  3409. /**
  3410. * A dead line stored as a date & time
  3411. * The only difference with the DateTime attribute is the display:
  3412. * relative to the current time
  3413. */
  3414. class AttributeDeadline extends AttributeDateTime
  3415. {
  3416. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3417. {
  3418. $sResult = self::FormatDeadline($value);
  3419. return $sResult;
  3420. }
  3421. public static function FormatDeadline($value)
  3422. {
  3423. $sResult = '';
  3424. if ($value !== null)
  3425. {
  3426. $iValue = AttributeDateTime::GetAsUnixSeconds($value);
  3427. $sDate = $value;
  3428. $difference = $iValue - time();
  3429. if ($difference >= 0)
  3430. {
  3431. $sDifference = self::FormatDuration($difference);
  3432. }
  3433. else
  3434. {
  3435. $sDifference = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  3436. }
  3437. $sFormat = MetaModel::GetConfig()->Get('deadline_format', '$difference$');
  3438. $sResult = str_replace(array('$date$', '$difference$'), array($sDate, $sDifference), $sFormat);
  3439. }
  3440. return $sResult;
  3441. }
  3442. static function FormatDuration($duration)
  3443. {
  3444. $days = floor($duration / 86400);
  3445. $hours = floor(($duration - (86400*$days)) / 3600);
  3446. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  3447. $sResult = '';
  3448. if ($duration < 60)
  3449. {
  3450. // Less than 1 min
  3451. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  3452. }
  3453. else if ($duration < 3600)
  3454. {
  3455. // less than 1 hour, display it in minutes
  3456. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  3457. }
  3458. else if ($duration < 86400)
  3459. {
  3460. // Less that 1 day, display it in hours/minutes
  3461. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  3462. }
  3463. else
  3464. {
  3465. // Less that 1 day, display it in hours/minutes
  3466. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  3467. }
  3468. return $sResult;
  3469. }
  3470. }
  3471. /**
  3472. * Map a foreign key to an attribute
  3473. * AttributeExternalKey and AttributeExternalField may be an external key
  3474. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  3475. * where an AttributeExternalField corresponds to a column into another table (class)
  3476. *
  3477. * @package iTopORM
  3478. */
  3479. class AttributeExternalKey extends AttributeDBFieldVoid
  3480. {
  3481. static public function ListExpectedParams()
  3482. {
  3483. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  3484. }
  3485. public function GetEditClass() {return "ExtKey";}
  3486. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? " DEFAULT 0" : "");}
  3487. public function RequiresIndex()
  3488. {
  3489. return true;
  3490. }
  3491. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  3492. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  3493. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  3494. public function GetKeyAttCode() {return $this->GetCode();}
  3495. public function GetDisplayStyle() { return $this->GetOptional('display_style', 'select'); }
  3496. public function GetDefaultValue(DBObject $oHostObject = null) {return 0;}
  3497. public function IsNullAllowed()
  3498. {
  3499. if (MetaModel::GetConfig()->Get('disable_mandatory_ext_keys'))
  3500. {
  3501. return true;
  3502. }
  3503. return $this->Get("is_null_allowed");
  3504. }
  3505. public function GetBasicFilterOperators()
  3506. {
  3507. return parent::GetBasicFilterOperators();
  3508. }
  3509. public function GetBasicFilterLooseOperator()
  3510. {
  3511. return parent::GetBasicFilterLooseOperator();
  3512. }
  3513. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3514. {
  3515. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  3516. }
  3517. // overloaded here so that an ext key always have the answer to
  3518. // "what are your possible values?"
  3519. public function GetValuesDef()
  3520. {
  3521. $oValSetDef = $this->Get("allowed_values");
  3522. if (!$oValSetDef)
  3523. {
  3524. // Let's propose every existing value
  3525. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  3526. }
  3527. return $oValSetDef;
  3528. }
  3529. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3530. {
  3531. //throw new Exception("GetAllowedValues on ext key has been deprecated");
  3532. try
  3533. {
  3534. return parent::GetAllowedValues($aArgs, $sContains);
  3535. }
  3536. catch (MissingQueryArgument $e)
  3537. {
  3538. // Some required arguments could not be found, enlarge to any existing value
  3539. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  3540. return $oValSetDef->GetValues($aArgs, $sContains);
  3541. }
  3542. }
  3543. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  3544. {
  3545. $oValSetDef = $this->GetValuesDef();
  3546. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  3547. return $oSet;
  3548. }
  3549. public function GetDeletionPropagationOption()
  3550. {
  3551. return $this->Get("on_target_delete");
  3552. }
  3553. public function GetNullValue()
  3554. {
  3555. return 0;
  3556. }
  3557. public function IsNull($proposedValue)
  3558. {
  3559. return ($proposedValue == 0);
  3560. }
  3561. public function MakeRealValue($proposedValue, $oHostObj)
  3562. {
  3563. if (is_null($proposedValue)) return 0;
  3564. if ($proposedValue === '') return 0;
  3565. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  3566. return (int)$proposedValue;
  3567. }
  3568. public function GetMaximumComboLength()
  3569. {
  3570. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  3571. }
  3572. public function GetMinAutoCompleteChars()
  3573. {
  3574. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  3575. }
  3576. public function AllowTargetCreation()
  3577. {
  3578. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  3579. }
  3580. /**
  3581. * Find the corresponding "link" attribute on the target class
  3582. *
  3583. * @return string The attribute code on the target class, or null if none has been found
  3584. */
  3585. public function GetMirrorLinkAttribute()
  3586. {
  3587. $oRet = null;
  3588. $sRemoteClass = $this->GetTargetClass();
  3589. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  3590. {
  3591. if (!$oRemoteAttDef->IsLinkSet()) continue;
  3592. if (!is_subclass_of($this->GetHostClass(), $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $this->GetHostClass()) continue;
  3593. if ($oRemoteAttDef->GetExtKeyToMe() != $this->GetCode()) continue;
  3594. $oRet = $oRemoteAttDef;
  3595. break;
  3596. }
  3597. return $oRet;
  3598. }
  3599. static public function GetFormFieldClass()
  3600. {
  3601. return '\\Combodo\\iTop\\Form\\Field\\SelectField';
  3602. }
  3603. public function MakeFormField(DBObject $oObject, $oFormField = null)
  3604. {
  3605. if ($oFormField === null)
  3606. {
  3607. // TODO : We should check $this->Get('display_style') and create a Radio / Select / ... regarding its value
  3608. $sFormFieldClass = static::GetFormFieldClass();
  3609. $oFormField = new $sFormFieldClass($this->GetCode());
  3610. }
  3611. $aFieldDependencies = $this->GetPrerequisiteAttributes();
  3612. // Field dependencies
  3613. if (!empty($aFieldDependencies))
  3614. {
  3615. $oTmpAttDef = $this;
  3616. $oTmpField = $oFormField;
  3617. $oFormField->SetOnFinalizeCallback(function() use ($oTmpField, $oTmpAttDef, $oObject)
  3618. {
  3619. //$oTmpField = $oForm->GetField($sFieldId);
  3620. $oTmpField->SetChoices($oTmpAttDef->GetAllowedValues($oObject->ToArgsForQuery()));
  3621. });
  3622. }
  3623. else
  3624. {
  3625. $oFormField->SetChoices($this->GetAllowedValues($oObject->ToArgsForQuery()));
  3626. }
  3627. // If ExtKey is mandatory, we add a validator to ensure that the value 0 is not selected
  3628. if ($oObject->GetAttributeFlags($this->GetCode()) & OPT_ATT_MANDATORY)
  3629. {
  3630. $oFormField->AddValidator(new \Combodo\iTop\Form\Validator\NotEmptyExtKeyValidator());
  3631. }
  3632. parent::MakeFormField($oObject, $oFormField);
  3633. return $oFormField;
  3634. }
  3635. }
  3636. /**
  3637. * Special kind of External Key to manage a hierarchy of objects
  3638. */
  3639. class AttributeHierarchicalKey extends AttributeExternalKey
  3640. {
  3641. protected $m_sTargetClass;
  3642. static public function ListExpectedParams()
  3643. {
  3644. $aParams = parent::ListExpectedParams();
  3645. $idx = array_search('targetclass', $aParams);
  3646. unset($aParams[$idx]);
  3647. $idx = array_search('jointype', $aParams);
  3648. unset($aParams[$idx]);
  3649. return $aParams; // TODO: mettre les bons parametres ici !!
  3650. }
  3651. public function GetEditClass() {return "ExtKey";}
  3652. public function RequiresIndex()
  3653. {
  3654. return true;
  3655. }
  3656. /*
  3657. * The target class is the class for which the attribute has been defined first
  3658. */
  3659. public function SetHostClass($sHostClass)
  3660. {
  3661. if (!isset($this->m_sTargetClass))
  3662. {
  3663. $this->m_sTargetClass = $sHostClass;
  3664. }
  3665. parent::SetHostClass($sHostClass);
  3666. }
  3667. public function IsHierarchicalKey() {return true;}
  3668. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->m_sTargetClass;}
  3669. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  3670. public function GetKeyAttCode() {return $this->GetCode();}
  3671. public function GetBasicFilterOperators()
  3672. {
  3673. return parent::GetBasicFilterOperators();
  3674. }
  3675. public function GetBasicFilterLooseOperator()
  3676. {
  3677. return parent::GetBasicFilterLooseOperator();
  3678. }
  3679. public function GetSQLColumns($bFullSpec = false)
  3680. {
  3681. $aColumns = array();
  3682. $aColumns[$this->GetCode()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3683. $aColumns[$this->GetSQLLeft()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3684. $aColumns[$this->GetSQLRight()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  3685. return $aColumns;
  3686. }
  3687. public function GetSQLRight()
  3688. {
  3689. return $this->GetCode().'_right';
  3690. }
  3691. public function GetSQLLeft()
  3692. {
  3693. return $this->GetCode().'_left';
  3694. }
  3695. public function GetSQLValues($value)
  3696. {
  3697. if (!is_array($value))
  3698. {
  3699. $aValues[$this->GetCode()] = $value;
  3700. }
  3701. else
  3702. {
  3703. $aValues = array();
  3704. $aValues[$this->GetCode()] = $value[$this->GetCode()];
  3705. $aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
  3706. $aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
  3707. }
  3708. return $aValues;
  3709. }
  3710. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3711. {
  3712. if (array_key_exists('this', $aArgs))
  3713. {
  3714. // Hierarchical keys have one more constraint: the "parent value" cannot be
  3715. // "under" themselves
  3716. $iRootId = $aArgs['this']->GetKey();
  3717. if ($iRootId > 0) // ignore objects that do no exist in the database...
  3718. {
  3719. $oValSetDef = $this->GetValuesDef();
  3720. $sClass = $this->m_sTargetClass;
  3721. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  3722. $oValSetDef->AddCondition($oFilter);
  3723. }
  3724. }
  3725. else
  3726. {
  3727. return parent::GetAllowedValues($aArgs, $sContains);
  3728. }
  3729. }
  3730. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  3731. {
  3732. $oValSetDef = $this->GetValuesDef();
  3733. if (array_key_exists('this', $aArgs))
  3734. {
  3735. // Hierarchical keys have one more constraint: the "parent value" cannot be
  3736. // "under" themselves
  3737. $iRootId = $aArgs['this']->GetKey();
  3738. if ($iRootId > 0) // ignore objects that do no exist in the database...
  3739. {
  3740. $aValuesSetDef = $this->GetValuesDef();
  3741. $sClass = $this->m_sTargetClass;
  3742. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  3743. $oValSetDef->AddCondition($oFilter);
  3744. }
  3745. }
  3746. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  3747. return $oSet;
  3748. }
  3749. /**
  3750. * Find the corresponding "link" attribute on the target class
  3751. *
  3752. * @return string The attribute code on the target class, or null if none has been found
  3753. */
  3754. public function GetMirrorLinkAttribute()
  3755. {
  3756. return null;
  3757. }
  3758. }
  3759. /**
  3760. * An attribute which corresponds to an external key (direct or indirect)
  3761. *
  3762. * @package iTopORM
  3763. */
  3764. class AttributeExternalField extends AttributeDefinition
  3765. {
  3766. static public function ListExpectedParams()
  3767. {
  3768. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  3769. }
  3770. public function GetEditClass() {return "ExtField";}
  3771. public function GetFinalAttDef()
  3772. {
  3773. $oExtAttDef = $this->GetExtAttDef();
  3774. return $oExtAttDef->GetFinalAttDef();
  3775. }
  3776. protected function GetSQLCol($bFullSpec = false)
  3777. {
  3778. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  3779. $oExtAttDef = $this->GetExtAttDef();
  3780. return $oExtAttDef->GetSQLCol($bFullSpec);
  3781. }
  3782. public function GetSQLExpressions($sPrefix = '')
  3783. {
  3784. if ($sPrefix == '')
  3785. {
  3786. return array('' => $this->GetCode()); // Warning: Use GetCode() since AttributeExternalField does not have any 'sql' property
  3787. }
  3788. else
  3789. {
  3790. return $sPrefix;
  3791. }
  3792. }
  3793. public function GetLabel($sDefault = null)
  3794. {
  3795. $sLabel = parent::GetLabel('');
  3796. if (strlen($sLabel) == 0)
  3797. {
  3798. $oRemoteAtt = $this->GetExtAttDef();
  3799. $sLabel = $oRemoteAtt->GetLabel($this->m_sCode);
  3800. }
  3801. return $sLabel;
  3802. }
  3803. public function GetDescription($sDefault = null)
  3804. {
  3805. $sLabel = parent::GetDescription('');
  3806. if (strlen($sLabel) == 0)
  3807. {
  3808. $oRemoteAtt = $this->GetExtAttDef();
  3809. $sLabel = $oRemoteAtt->GetDescription('');
  3810. }
  3811. return $sLabel;
  3812. }
  3813. public function GetHelpOnEdition($sDefault = null)
  3814. {
  3815. $sLabel = parent::GetHelpOnEdition('');
  3816. if (strlen($sLabel) == 0)
  3817. {
  3818. $oRemoteAtt = $this->GetExtAttDef();
  3819. $sLabel = $oRemoteAtt->GetHelpOnEdition('');
  3820. }
  3821. return $sLabel;
  3822. }
  3823. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  3824. {
  3825. switch($iType)
  3826. {
  3827. case EXTKEY_ABSOLUTE:
  3828. // see further
  3829. $oRemoteAtt = $this->GetExtAttDef();
  3830. return $oRemoteAtt->IsExternalKey($iType);
  3831. case EXTKEY_RELATIVE:
  3832. return false;
  3833. default:
  3834. throw new CoreException("Unexpected value for argument iType: '$iType'");
  3835. }
  3836. }
  3837. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  3838. {
  3839. return $this->GetKeyAttDef($iType)->GetTargetClass();
  3840. }
  3841. public function IsExternalField() {return true;}
  3842. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  3843. public function GetExtAttCode() {return $this->Get("target_attcode");}
  3844. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  3845. {
  3846. switch($iType)
  3847. {
  3848. case EXTKEY_ABSOLUTE:
  3849. // see further
  3850. $oRemoteAtt = $this->GetExtAttDef();
  3851. if ($oRemoteAtt->IsExternalField())
  3852. {
  3853. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  3854. }
  3855. else if ($oRemoteAtt->IsExternalKey())
  3856. {
  3857. return $oRemoteAtt;
  3858. }
  3859. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  3860. case EXTKEY_RELATIVE:
  3861. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  3862. default:
  3863. throw new CoreException("Unexpected value for argument iType: '$iType'");
  3864. }
  3865. }
  3866. public function GetPrerequisiteAttributes($sClass = null)
  3867. {
  3868. return array($this->Get("extkey_attcode"));
  3869. }
  3870. public function GetExtAttDef()
  3871. {
  3872. $oKeyAttDef = $this->GetKeyAttDef();
  3873. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $this->Get("target_attcode"));
  3874. 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"));
  3875. return $oExtAttDef;
  3876. }
  3877. public function GetSQLExpr()
  3878. {
  3879. $oExtAttDef = $this->GetExtAttDef();
  3880. return $oExtAttDef->GetSQLExpr();
  3881. }
  3882. public function GetDefaultValue(DBObject $oHostObject = null)
  3883. {
  3884. $oExtAttDef = $this->GetExtAttDef();
  3885. return $oExtAttDef->GetDefaultValue();
  3886. }
  3887. public function IsNullAllowed()
  3888. {
  3889. $oExtAttDef = $this->GetExtAttDef();
  3890. return $oExtAttDef->IsNullAllowed();
  3891. }
  3892. public function IsScalar()
  3893. {
  3894. $oExtAttDef = $this->GetExtAttDef();
  3895. return $oExtAttDef->IsScalar();
  3896. }
  3897. public function GetFilterDefinitions()
  3898. {
  3899. return array($this->GetCode() => new FilterFromAttribute($this));
  3900. }
  3901. public function GetBasicFilterOperators()
  3902. {
  3903. $oExtAttDef = $this->GetExtAttDef();
  3904. return $oExtAttDef->GetBasicFilterOperators();
  3905. }
  3906. public function GetBasicFilterLooseOperator()
  3907. {
  3908. $oExtAttDef = $this->GetExtAttDef();
  3909. return $oExtAttDef->GetBasicFilterLooseOperator();
  3910. }
  3911. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3912. {
  3913. $oExtAttDef = $this->GetExtAttDef();
  3914. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  3915. }
  3916. public function GetNullValue()
  3917. {
  3918. $oExtAttDef = $this->GetExtAttDef();
  3919. return $oExtAttDef->GetNullValue();
  3920. }
  3921. public function IsNull($proposedValue)
  3922. {
  3923. $oExtAttDef = $this->GetExtAttDef();
  3924. return $oExtAttDef->IsNull($proposedValue);
  3925. }
  3926. public function MakeRealValue($proposedValue, $oHostObj)
  3927. {
  3928. $oExtAttDef = $this->GetExtAttDef();
  3929. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  3930. }
  3931. public function ScalarToSQL($value)
  3932. {
  3933. // This one could be used in case of filtering only
  3934. $oExtAttDef = $this->GetExtAttDef();
  3935. return $oExtAttDef->ScalarToSQL($value);
  3936. }
  3937. // Do not overload GetSQLExpression here because this is handled in the joins
  3938. //public function GetSQLExpressions($sPrefix = '') {return array();}
  3939. // Here, we get the data...
  3940. public function FromSQLToValue($aCols, $sPrefix = '')
  3941. {
  3942. $oExtAttDef = $this->GetExtAttDef();
  3943. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  3944. }
  3945. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3946. {
  3947. $oExtAttDef = $this->GetExtAttDef();
  3948. return $oExtAttDef->GetAsHTML($value, null, $bLocalize);
  3949. }
  3950. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3951. {
  3952. $oExtAttDef = $this->GetExtAttDef();
  3953. return $oExtAttDef->GetAsXML($value, null, $bLocalize);
  3954. }
  3955. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  3956. {
  3957. $oExtAttDef = $this->GetExtAttDef();
  3958. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier, null, $bLocalize, $bConvertToPlainText);
  3959. }
  3960. public function IsPartOfFingerprint()
  3961. {
  3962. return false;
  3963. }
  3964. }
  3965. /**
  3966. * Map a varchar column to an URL (formats the ouput in HMTL)
  3967. *
  3968. * @package iTopORM
  3969. */
  3970. class AttributeURL extends AttributeString
  3971. {
  3972. static public function ListExpectedParams()
  3973. {
  3974. //return parent::ListExpectedParams();
  3975. return array_merge(parent::ListExpectedParams(), array("target"));
  3976. }
  3977. public function GetEditClass() {return "String";}
  3978. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  3979. {
  3980. $sTarget = $this->Get("target");
  3981. if (empty($sTarget)) $sTarget = "_blank";
  3982. $sLabel = Str::pure2html($sValue);
  3983. if (strlen($sLabel) > 255)
  3984. {
  3985. // Truncate the length to 128 characters, by removing the middle
  3986. $sLabel = substr($sLabel, 0, 100).'.....'.substr($sLabel, -20);
  3987. }
  3988. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  3989. }
  3990. public function GetValidationPattern()
  3991. {
  3992. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('url_validation_pattern').'$');
  3993. }
  3994. }
  3995. /**
  3996. * A blob is an ormDocument, it is stored as several columns in the database
  3997. *
  3998. * @package iTopORM
  3999. */
  4000. class AttributeBlob extends AttributeDefinition
  4001. {
  4002. static public function ListExpectedParams()
  4003. {
  4004. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  4005. }
  4006. public function GetEditClass() {return "Document";}
  4007. public function IsDirectField() {return true;}
  4008. public function IsScalar() {return true;}
  4009. public function IsWritable() {return true;}
  4010. public function GetDefaultValue(DBObject $oHostObject = null) {return "";}
  4011. public function IsNullAllowed(DBObject $oHostObject = null) {return $this->GetOptional("is_null_allowed", false);}
  4012. public function GetEditValue($sValue, $oHostObj = null)
  4013. {
  4014. return '';
  4015. }
  4016. // Facilitate things: allow administrators to upload a document
  4017. // from a CSV by specifying its path/URL
  4018. public function MakeRealValue($proposedValue, $oHostObj)
  4019. {
  4020. if (!is_object($proposedValue))
  4021. {
  4022. if (file_exists($proposedValue) && UserRights::IsAdministrator())
  4023. {
  4024. $sContent = file_get_contents($proposedValue);
  4025. $sExtension = strtolower(pathinfo($proposedValue, PATHINFO_EXTENSION));
  4026. $sMimeType = "application/x-octet-stream";
  4027. $aKnownExtensions = array(
  4028. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  4029. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  4030. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  4031. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  4032. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  4033. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  4034. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  4035. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  4036. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  4037. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12.xlsx',
  4038. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  4039. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  4040. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  4041. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  4042. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  4043. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  4044. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  4045. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  4046. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  4047. 'jpg' => 'image/jpeg',
  4048. 'jpeg' => 'image/jpeg',
  4049. 'gif' => 'image/gif',
  4050. 'png' => 'image/png',
  4051. 'pdf' => 'application/pdf',
  4052. 'doc' => 'application/msword',
  4053. 'dot' => 'application/msword',
  4054. 'xls' => 'application/vnd.ms-excel',
  4055. 'ppt' => 'application/vnd.ms-powerpoint',
  4056. 'vsd' => 'application/x-visio',
  4057. 'vdx' => 'application/visio.drawing',
  4058. 'odt' => 'application/vnd.oasis.opendocument.text',
  4059. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  4060. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  4061. 'zip' => 'application/zip',
  4062. 'txt' => 'text/plain',
  4063. 'htm' => 'text/html',
  4064. 'html' => 'text/html',
  4065. 'exe' => 'application/octet-stream'
  4066. );
  4067. if (!array_key_exists($sExtension, $aKnownExtensions) && extension_loaded('fileinfo'))
  4068. {
  4069. $finfo = new finfo(FILEINFO_MIME);
  4070. $sMimeType = $finfo->file($proposedValue);
  4071. }
  4072. return new ormDocument($sContent, $sMimeType);
  4073. }
  4074. else
  4075. {
  4076. return new ormDocument($proposedValue, 'text/plain');
  4077. }
  4078. }
  4079. return $proposedValue;
  4080. }
  4081. public function GetSQLExpressions($sPrefix = '')
  4082. {
  4083. if ($sPrefix == '')
  4084. {
  4085. $sPrefix = $this->GetCode();
  4086. }
  4087. $aColumns = array();
  4088. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  4089. $aColumns[''] = $sPrefix.'_mimetype';
  4090. $aColumns['_data'] = $sPrefix.'_data';
  4091. $aColumns['_filename'] = $sPrefix.'_filename';
  4092. return $aColumns;
  4093. }
  4094. public function FromSQLToValue($aCols, $sPrefix = '')
  4095. {
  4096. if (!array_key_exists($sPrefix, $aCols))
  4097. {
  4098. $sAvailable = implode(', ', array_keys($aCols));
  4099. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4100. }
  4101. $sMimeType = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  4102. if (!array_key_exists($sPrefix.'_data', $aCols))
  4103. {
  4104. $sAvailable = implode(', ', array_keys($aCols));
  4105. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  4106. }
  4107. $data = isset($aCols[$sPrefix.'_data']) ? $aCols[$sPrefix.'_data'] : null;
  4108. if (!array_key_exists($sPrefix.'_filename', $aCols))
  4109. {
  4110. $sAvailable = implode(', ', array_keys($aCols));
  4111. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  4112. }
  4113. $sFileName = isset($aCols[$sPrefix.'_filename']) ? $aCols[$sPrefix.'_filename'] : '';
  4114. $value = new ormDocument($data, $sMimeType, $sFileName);
  4115. return $value;
  4116. }
  4117. public function GetSQLValues($value)
  4118. {
  4119. // #@# Optimization: do not load blobs anytime
  4120. // As per mySQL doc, selecting blob columns will prevent mySQL from
  4121. // using memory in case a temporary table has to be created
  4122. // (temporary tables created on disk)
  4123. // We will have to remove the blobs from the list of attributes when doing the select
  4124. // then the use of Get() should finalize the load
  4125. if ($value instanceOf ormDocument)
  4126. {
  4127. $aValues = array();
  4128. $aValues[$this->GetCode().'_data'] = $value->GetData();
  4129. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  4130. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  4131. }
  4132. else
  4133. {
  4134. $aValues = array();
  4135. $aValues[$this->GetCode().'_data'] = '';
  4136. $aValues[$this->GetCode().'_mimetype'] = '';
  4137. $aValues[$this->GetCode().'_filename'] = '';
  4138. }
  4139. return $aValues;
  4140. }
  4141. public function GetSQLColumns($bFullSpec = false)
  4142. {
  4143. $aColumns = array();
  4144. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  4145. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  4146. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  4147. return $aColumns;
  4148. }
  4149. public function GetFilterDefinitions()
  4150. {
  4151. return array();
  4152. // still not working... see later...
  4153. return array(
  4154. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  4155. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  4156. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  4157. );
  4158. }
  4159. public function GetBasicFilterOperators()
  4160. {
  4161. return array();
  4162. }
  4163. public function GetBasicFilterLooseOperator()
  4164. {
  4165. return '=';
  4166. }
  4167. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4168. {
  4169. return 'true';
  4170. }
  4171. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4172. {
  4173. if (is_object($value))
  4174. {
  4175. return $value->GetAsHTML();
  4176. }
  4177. }
  4178. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  4179. {
  4180. return ''; // Not exportable in CSV !
  4181. }
  4182. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4183. {
  4184. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  4185. }
  4186. /**
  4187. * Helper to get a value that will be JSON encoded
  4188. * The operation is the opposite to FromJSONToValue
  4189. */
  4190. public function GetForJSON($value)
  4191. {
  4192. if ($value instanceOf ormDocument)
  4193. {
  4194. $aValues = array();
  4195. $aValues['data'] = base64_encode($value->GetData());
  4196. $aValues['mimetype'] = $value->GetMimeType();
  4197. $aValues['filename'] = $value->GetFileName();
  4198. }
  4199. else
  4200. {
  4201. $aValues = null;
  4202. }
  4203. return $aValues;
  4204. }
  4205. /**
  4206. * Helper to form a value, given JSON decoded data
  4207. * The operation is the opposite to GetForJSON
  4208. */
  4209. public function FromJSONToValue($json)
  4210. {
  4211. if (isset($json->data))
  4212. {
  4213. $data = base64_decode($json->data);
  4214. $value = new ormDocument($data, $json->mimetype, $json->filename);
  4215. }
  4216. else
  4217. {
  4218. $value = null;
  4219. }
  4220. return $value;
  4221. }
  4222. public function Fingerprint($value)
  4223. {
  4224. $sFingerprint = '';
  4225. if ($value instanceOf ormDocument)
  4226. {
  4227. $sFingerprint = md5($value->GetData());
  4228. }
  4229. return $sFingerprint;
  4230. }
  4231. }
  4232. /**
  4233. * A stop watch is an ormStopWatch object, it is stored as several columns in the database
  4234. *
  4235. * @package iTopORM
  4236. */
  4237. class AttributeStopWatch extends AttributeDefinition
  4238. {
  4239. static public function ListExpectedParams()
  4240. {
  4241. // The list of thresholds must be an array of iPercent => array of 'option' => value
  4242. return array_merge(parent::ListExpectedParams(), array("states", "goal_computing", "working_time_computing", "thresholds"));
  4243. }
  4244. public function GetEditClass() {return "StopWatch";}
  4245. public function IsDirectField() {return true;}
  4246. public function IsScalar() {return true;}
  4247. public function IsWritable() {return false;}
  4248. public function GetDefaultValue(DBObject $oHostObject = null) {return $this->NewStopWatch();}
  4249. public function GetEditValue($value, $oHostObj = null)
  4250. {
  4251. return $value->GetTimeSpent();
  4252. }
  4253. public function GetStates()
  4254. {
  4255. return $this->Get('states');
  4256. }
  4257. public function AlwaysLoadInTables()
  4258. {
  4259. // Each and every stop watch is accessed for computing the highlight code (DBObject::GetHighlightCode())
  4260. return true;
  4261. }
  4262. /**
  4263. * Construct a brand new (but configured) stop watch
  4264. */
  4265. public function NewStopWatch()
  4266. {
  4267. $oSW = new ormStopWatch();
  4268. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4269. {
  4270. $oSW->DefineThreshold($iThreshold);
  4271. }
  4272. return $oSW;
  4273. }
  4274. // Facilitate things: allow the user to Set the value from a string
  4275. public function MakeRealValue($proposedValue, $oHostObj)
  4276. {
  4277. if (!$proposedValue instanceof ormStopWatch)
  4278. {
  4279. return $this->NewStopWatch();
  4280. }
  4281. return $proposedValue;
  4282. }
  4283. public function GetSQLExpressions($sPrefix = '')
  4284. {
  4285. if ($sPrefix == '')
  4286. {
  4287. $sPrefix = $this->GetCode(); // Warning: a stopwatch does not have any 'sql' property, so its SQL column is equal to its attribute code !!
  4288. }
  4289. $aColumns = array();
  4290. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  4291. $aColumns[''] = $sPrefix.'_timespent';
  4292. $aColumns['_started'] = $sPrefix.'_started';
  4293. $aColumns['_laststart'] = $sPrefix.'_laststart';
  4294. $aColumns['_stopped'] = $sPrefix.'_stopped';
  4295. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4296. {
  4297. $sThPrefix = '_'.$iThreshold;
  4298. $aColumns[$sThPrefix.'_deadline'] = $sPrefix.$sThPrefix.'_deadline';
  4299. $aColumns[$sThPrefix.'_passed'] = $sPrefix.$sThPrefix.'_passed';
  4300. $aColumns[$sThPrefix.'_triggered'] = $sPrefix.$sThPrefix.'_triggered';
  4301. $aColumns[$sThPrefix.'_overrun'] = $sPrefix.$sThPrefix.'_overrun';
  4302. }
  4303. return $aColumns;
  4304. }
  4305. public static function DateToSeconds($sDate)
  4306. {
  4307. if (is_null($sDate))
  4308. {
  4309. return null;
  4310. }
  4311. $oDateTime = new DateTime($sDate);
  4312. $iSeconds = $oDateTime->format('U');
  4313. return $iSeconds;
  4314. }
  4315. public static function SecondsToDate($iSeconds)
  4316. {
  4317. if (is_null($iSeconds))
  4318. {
  4319. return null;
  4320. }
  4321. return date("Y-m-d H:i:s", $iSeconds);
  4322. }
  4323. public function FromSQLToValue($aCols, $sPrefix = '')
  4324. {
  4325. $aExpectedCols = array($sPrefix, $sPrefix.'_started', $sPrefix.'_laststart', $sPrefix.'_stopped');
  4326. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4327. {
  4328. $sThPrefix = '_'.$iThreshold;
  4329. $aExpectedCols[] = $sPrefix.$sThPrefix.'_deadline';
  4330. $aExpectedCols[] = $sPrefix.$sThPrefix.'_passed';
  4331. $aExpectedCols[] = $sPrefix.$sThPrefix.'_triggered';
  4332. $aExpectedCols[] = $sPrefix.$sThPrefix.'_overrun';
  4333. }
  4334. foreach ($aExpectedCols as $sExpectedCol)
  4335. {
  4336. if (!array_key_exists($sExpectedCol, $aCols))
  4337. {
  4338. $sAvailable = implode(', ', array_keys($aCols));
  4339. throw new MissingColumnException("Missing column '$sExpectedCol' from {$sAvailable}");
  4340. }
  4341. }
  4342. $value = new ormStopWatch(
  4343. $aCols[$sPrefix],
  4344. self::DateToSeconds($aCols[$sPrefix.'_started']),
  4345. self::DateToSeconds($aCols[$sPrefix.'_laststart']),
  4346. self::DateToSeconds($aCols[$sPrefix.'_stopped'])
  4347. );
  4348. $aThresholds = array();
  4349. foreach ($this->ListThresholds() as $iThreshold => $aDefinition)
  4350. {
  4351. $sThPrefix = '_'.$iThreshold;
  4352. $value->DefineThreshold(
  4353. $iThreshold,
  4354. self::DateToSeconds($aCols[$sPrefix.$sThPrefix.'_deadline']),
  4355. (bool)($aCols[$sPrefix.$sThPrefix.'_passed'] == 1),
  4356. (bool)($aCols[$sPrefix.$sThPrefix.'_triggered'] == 1),
  4357. $aCols[$sPrefix.$sThPrefix.'_overrun'],
  4358. array_key_exists('highlight', $aDefinition) ? $aDefinition['highlight'] : null
  4359. );
  4360. }
  4361. return $value;
  4362. }
  4363. public function GetSQLValues($value)
  4364. {
  4365. if ($value instanceOf ormStopWatch)
  4366. {
  4367. $aValues = array();
  4368. $aValues[$this->GetCode().'_timespent'] = $value->GetTimeSpent();
  4369. $aValues[$this->GetCode().'_started'] = self::SecondsToDate($value->GetStartDate());
  4370. $aValues[$this->GetCode().'_laststart'] = self::SecondsToDate($value->GetLastStartDate());
  4371. $aValues[$this->GetCode().'_stopped'] = self::SecondsToDate($value->GetStopDate());
  4372. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4373. {
  4374. $sPrefix = $this->GetCode().'_'.$iThreshold;
  4375. $aValues[$sPrefix.'_deadline'] = self::SecondsToDate($value->GetThresholdDate($iThreshold));
  4376. $aValues[$sPrefix.'_passed'] = $value->IsThresholdPassed($iThreshold) ? '1' : '0';
  4377. $aValues[$sPrefix.'_triggered'] = $value->IsThresholdTriggered($iThreshold) ? '1' : '0';
  4378. $aValues[$sPrefix.'_overrun'] = $value->GetOverrun($iThreshold);
  4379. }
  4380. }
  4381. else
  4382. {
  4383. $aValues = array();
  4384. $aValues[$this->GetCode().'_timespent'] = '';
  4385. $aValues[$this->GetCode().'_started'] = '';
  4386. $aValues[$this->GetCode().'_laststart'] = '';
  4387. $aValues[$this->GetCode().'_stopped'] = '';
  4388. }
  4389. return $aValues;
  4390. }
  4391. public function GetSQLColumns($bFullSpec = false)
  4392. {
  4393. $aColumns = array();
  4394. $aColumns[$this->GetCode().'_timespent'] = 'INT(11) UNSIGNED';
  4395. $aColumns[$this->GetCode().'_started'] = 'DATETIME';
  4396. $aColumns[$this->GetCode().'_laststart'] = 'DATETIME';
  4397. $aColumns[$this->GetCode().'_stopped'] = 'DATETIME';
  4398. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4399. {
  4400. $sPrefix = $this->GetCode().'_'.$iThreshold;
  4401. $aColumns[$sPrefix.'_deadline'] = 'DATETIME';
  4402. $aColumns[$sPrefix.'_passed'] = 'TINYINT(1) UNSIGNED';
  4403. $aColumns[$sPrefix.'_triggered'] = 'TINYINT(1)';
  4404. $aColumns[$sPrefix.'_overrun'] = 'INT(11) UNSIGNED';
  4405. }
  4406. return $aColumns;
  4407. }
  4408. public function GetFilterDefinitions()
  4409. {
  4410. $aRes = array(
  4411. $this->GetCode() => new FilterFromAttribute($this),
  4412. $this->GetCode().'_started' => new FilterFromAttribute($this, '_started'),
  4413. $this->GetCode().'_laststart' => new FilterFromAttribute($this, '_laststart'),
  4414. $this->GetCode().'_stopped' => new FilterFromAttribute($this, '_stopped')
  4415. );
  4416. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4417. {
  4418. $sPrefix = $this->GetCode().'_'.$iThreshold;
  4419. $aRes[$sPrefix.'_deadline'] = new FilterFromAttribute($this, '_deadline');
  4420. $aRes[$sPrefix.'_passed'] = new FilterFromAttribute($this, '_passed');
  4421. $aRes[$sPrefix.'_triggered'] = new FilterFromAttribute($this, '_triggered');
  4422. $aRes[$sPrefix.'_overrun'] = new FilterFromAttribute($this, '_overrun');
  4423. }
  4424. return $aRes;
  4425. }
  4426. public function GetBasicFilterOperators()
  4427. {
  4428. return array();
  4429. }
  4430. public function GetBasicFilterLooseOperator()
  4431. {
  4432. return '=';
  4433. }
  4434. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4435. {
  4436. return 'true';
  4437. }
  4438. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4439. {
  4440. if (is_object($value))
  4441. {
  4442. return $value->GetAsHTML($this, $oHostObject);
  4443. }
  4444. }
  4445. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  4446. {
  4447. return $value->GetTimeSpent();
  4448. }
  4449. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4450. {
  4451. return $value->GetTimeSpent();
  4452. }
  4453. public function ListThresholds()
  4454. {
  4455. return $this->Get('thresholds');
  4456. }
  4457. public function Fingerprint($value)
  4458. {
  4459. $sFingerprint = '';
  4460. if (is_object($value))
  4461. {
  4462. $sFingerprint = $value->GetAsHTML($this);
  4463. }
  4464. return $sFingerprint;
  4465. }
  4466. /**
  4467. * To expose internal values: Declare an attribute AttributeSubItem
  4468. * and implement the GetSubItemXXXX verbs
  4469. */
  4470. public function GetSubItemSQLExpression($sItemCode)
  4471. {
  4472. $sPrefix = $this->GetCode();
  4473. switch($sItemCode)
  4474. {
  4475. case 'timespent':
  4476. return array('' => $sPrefix.'_timespent');
  4477. case 'started':
  4478. return array('' => $sPrefix.'_started');
  4479. case 'laststart':
  4480. return array('' => $sPrefix.'_laststart');
  4481. case 'stopped':
  4482. return array('' => $sPrefix.'_stopped');
  4483. }
  4484. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4485. {
  4486. $sThPrefix = $iThreshold.'_';
  4487. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4488. {
  4489. // The current threshold is concerned
  4490. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4491. switch($sThresholdCode)
  4492. {
  4493. case 'deadline':
  4494. return array('' => $sPrefix.'_'.$iThreshold.'_deadline');
  4495. case 'passed':
  4496. return array('' => $sPrefix.'_'.$iThreshold.'_passed');
  4497. case 'triggered':
  4498. return array('' => $sPrefix.'_'.$iThreshold.'_triggered');
  4499. case 'overrun':
  4500. return array('' => $sPrefix.'_'.$iThreshold.'_overrun');
  4501. }
  4502. }
  4503. }
  4504. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  4505. }
  4506. public function GetSubItemValue($sItemCode, $value, $oHostObject = null)
  4507. {
  4508. $oStopWatch = $value;
  4509. switch($sItemCode)
  4510. {
  4511. case 'timespent':
  4512. return $oStopWatch->GetTimeSpent();
  4513. case 'started':
  4514. return $oStopWatch->GetStartDate();
  4515. case 'laststart':
  4516. return $oStopWatch->GetLastStartDate();
  4517. case 'stopped':
  4518. return $oStopWatch->GetStopDate();
  4519. }
  4520. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4521. {
  4522. $sThPrefix = $iThreshold.'_';
  4523. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4524. {
  4525. // The current threshold is concerned
  4526. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4527. switch($sThresholdCode)
  4528. {
  4529. case 'deadline':
  4530. return $oStopWatch->GetThresholdDate($iThreshold);
  4531. case 'passed':
  4532. return $oStopWatch->IsThresholdPassed($iThreshold);
  4533. case 'triggered':
  4534. return $oStopWatch->IsThresholdTriggered($iThreshold);
  4535. case 'overrun':
  4536. return $oStopWatch->GetOverrun($iThreshold);
  4537. }
  4538. }
  4539. }
  4540. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  4541. }
  4542. protected function GetBooleanLabel($bValue)
  4543. {
  4544. $sDictKey = $bValue ? 'yes' : 'no';
  4545. return Dict::S('BooleanLabel:'.$sDictKey, 'def:'.$sDictKey);
  4546. }
  4547. public function GetSubItemAsHTMLForHistory($sItemCode, $sValue)
  4548. {
  4549. switch($sItemCode)
  4550. {
  4551. case 'timespent':
  4552. $sHtml = (int)$sValue ? Str::pure2html(AttributeDuration::FormatDuration($sValue)) : null;
  4553. break;
  4554. case 'started':
  4555. case 'laststart':
  4556. case 'stopped':
  4557. $sHtml = (int)$sValue ? date(self::GetDateFormat(), (int)$sValue) : null;
  4558. break;
  4559. default:
  4560. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4561. {
  4562. $sThPrefix = $iThreshold.'_';
  4563. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4564. {
  4565. // The current threshold is concerned
  4566. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4567. switch($sThresholdCode)
  4568. {
  4569. case 'deadline':
  4570. $sHtml = (int)$sValue ? date(self::GetDateFormat(true /*full*/), (int)$sValue) : null;
  4571. break;
  4572. case 'passed':
  4573. $sHtml = $this->GetBooleanLabel((int)$sValue);
  4574. break;
  4575. case 'triggered':
  4576. $sHtml = $this->GetBooleanLabel((int)$sValue);
  4577. break;
  4578. case 'overrun':
  4579. $sHtml = (int)$sValue > 0 ? Str::pure2html(AttributeDuration::FormatDuration((int)$sValue)) : '';
  4580. }
  4581. }
  4582. }
  4583. }
  4584. return $sHtml;
  4585. }
  4586. static protected function GetDateFormat($bFull = false)
  4587. {
  4588. if ($bFull)
  4589. {
  4590. return "Y-m-d H:i:s";
  4591. }
  4592. else
  4593. {
  4594. return "Y-m-d H:i";
  4595. }
  4596. }
  4597. public function GetSubItemAsHTML($sItemCode, $value)
  4598. {
  4599. $sHtml = $value;
  4600. switch($sItemCode)
  4601. {
  4602. case 'timespent':
  4603. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  4604. break;
  4605. case 'started':
  4606. case 'laststart':
  4607. case 'stopped':
  4608. if (is_null($value))
  4609. {
  4610. $sHtml = ''; // Undefined
  4611. }
  4612. else
  4613. {
  4614. $sHtml = date(self::GetDateFormat(), $value);
  4615. }
  4616. break;
  4617. default:
  4618. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4619. {
  4620. $sThPrefix = $iThreshold.'_';
  4621. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4622. {
  4623. // The current threshold is concerned
  4624. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4625. switch($sThresholdCode)
  4626. {
  4627. case 'deadline':
  4628. if ($value)
  4629. {
  4630. $sDate = date(self::GetDateFormat(true /*full*/), $value);
  4631. $sHtml = Str::pure2html(AttributeDeadline::FormatDeadline($sDate));
  4632. }
  4633. else
  4634. {
  4635. $sHtml = '';
  4636. }
  4637. break;
  4638. case 'passed':
  4639. case 'triggered':
  4640. $sHtml = $this->GetBooleanLabel($value);
  4641. break;
  4642. case 'overrun':
  4643. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  4644. break;
  4645. }
  4646. }
  4647. }
  4648. }
  4649. return $sHtml;
  4650. }
  4651. public function GetSubItemAsCSV($sItemCode, $value, $sSeparator = ',', $sTextQualifier = '"', $bConvertToPlainText = false)
  4652. {
  4653. $sFrom = array("\r\n", $sTextQualifier);
  4654. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  4655. $sEscaped = str_replace($sFrom, $sTo, (string)$value);
  4656. $sRet = $sTextQualifier.$sEscaped.$sTextQualifier;
  4657. switch($sItemCode)
  4658. {
  4659. case 'timespent':
  4660. case 'started':
  4661. case 'laststart':
  4662. case 'stopped':
  4663. break;
  4664. default:
  4665. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4666. {
  4667. $sThPrefix = $iThreshold.'_';
  4668. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4669. {
  4670. // The current threshold is concerned
  4671. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4672. switch($sThresholdCode)
  4673. {
  4674. case 'deadline':
  4675. if ($value != '')
  4676. {
  4677. $sRet = $sTextQualifier.date(self::GetDateFormat(true /*full*/), $value).$sTextQualifier;
  4678. }
  4679. break;
  4680. case 'passed':
  4681. case 'triggered':
  4682. $sRet = $sTextQualifier.$this->GetBooleanLabel($value).$sTextQualifier;
  4683. break;
  4684. case 'overrun':
  4685. break;
  4686. }
  4687. }
  4688. }
  4689. }
  4690. return $sRet;
  4691. }
  4692. public function GetSubItemAsXML($sItemCode, $value)
  4693. {
  4694. $sRet = Str::pure2xml((string)$value);
  4695. switch($sItemCode)
  4696. {
  4697. case 'timespent':
  4698. case 'started':
  4699. case 'laststart':
  4700. case 'stopped':
  4701. break;
  4702. default:
  4703. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4704. {
  4705. $sThPrefix = $iThreshold.'_';
  4706. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4707. {
  4708. // The current threshold is concerned
  4709. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4710. switch($sThresholdCode)
  4711. {
  4712. case 'deadline':
  4713. break;
  4714. case 'passed':
  4715. case 'triggered':
  4716. $sRet = $this->GetBooleanLabel($value);
  4717. break;
  4718. case 'overrun':
  4719. break;
  4720. }
  4721. }
  4722. }
  4723. }
  4724. return $sRet;
  4725. }
  4726. /**
  4727. * Implemented for the HTML spreadsheet format!
  4728. */
  4729. public function GetSubItemAsEditValue($sItemCode, $value)
  4730. {
  4731. $sRet = $value;
  4732. switch($sItemCode)
  4733. {
  4734. case 'timespent':
  4735. break;
  4736. case 'started':
  4737. case 'laststart':
  4738. case 'stopped':
  4739. if (is_null($value))
  4740. {
  4741. $sRet = ''; // Undefined
  4742. }
  4743. else
  4744. {
  4745. $sRet = date(self::GetDateFormat(), $value);
  4746. }
  4747. break;
  4748. default:
  4749. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4750. {
  4751. $sThPrefix = $iThreshold.'_';
  4752. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4753. {
  4754. // The current threshold is concerned
  4755. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4756. switch($sThresholdCode)
  4757. {
  4758. case 'deadline':
  4759. if ($value)
  4760. {
  4761. $sRet = date(self::GetDateFormat(true /*full*/), $value);
  4762. }
  4763. else
  4764. {
  4765. $sRet = '';
  4766. }
  4767. break;
  4768. case 'passed':
  4769. case 'triggered':
  4770. $sRet = $this->GetBooleanLabel($value);
  4771. break;
  4772. case 'overrun':
  4773. break;
  4774. }
  4775. }
  4776. }
  4777. }
  4778. return $sRet;
  4779. }
  4780. }
  4781. /**
  4782. * View of a subvalue of another attribute
  4783. * If an attribute implements the verbs GetSubItem.... then it can expose
  4784. * internal values, each of them being an attribute and therefore they
  4785. * can be displayed at different times in the object lifecycle, and used for
  4786. * reporting (as a condition in OQL, or as an additional column in an export)
  4787. * Known usages: Stop Watches can expose threshold statuses
  4788. */
  4789. class AttributeSubItem extends AttributeDefinition
  4790. {
  4791. static public function ListExpectedParams()
  4792. {
  4793. return array_merge(parent::ListExpectedParams(), array('target_attcode', 'item_code'));
  4794. }
  4795. public function GetParentAttCode() {return $this->Get("target_attcode");}
  4796. /**
  4797. * Helper : get the attribute definition to which the execution will be forwarded
  4798. */
  4799. public function GetTargetAttDef()
  4800. {
  4801. $sClass = $this->GetHostClass();
  4802. $oParentAttDef = MetaModel::GetAttributeDef($sClass, $this->Get('target_attcode'));
  4803. return $oParentAttDef;
  4804. }
  4805. public function GetEditClass() {return "";}
  4806. public function GetValuesDef() {return null;}
  4807. public function IsDirectField() {return true;}
  4808. public function IsScalar() {return true;}
  4809. public function IsWritable() {return false;}
  4810. public function GetDefaultValue(DBObject $oHostObject = null) {return null;}
  4811. // public function IsNullAllowed() {return false;}
  4812. public function LoadInObject() {return false;} // if this verb returns false, then GetValue must be implemented
  4813. /**
  4814. * Used by DBOBject::Get()
  4815. */
  4816. public function GetValue($oHostObject, $bOriginal = false)
  4817. {
  4818. $oParent = $this->GetTargetAttDef();
  4819. $parentValue = $oHostObject->GetStrict($oParent->GetCode());
  4820. $res = $oParent->GetSubItemValue($this->Get('item_code'), $parentValue, $oHostObject);
  4821. return $res;
  4822. }
  4823. //
  4824. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  4825. public function FromSQLToValue($aCols, $sPrefix = '')
  4826. {
  4827. }
  4828. public function GetSQLColumns($bFullSpec = false)
  4829. {
  4830. return array();
  4831. }
  4832. public function GetFilterDefinitions()
  4833. {
  4834. return array($this->GetCode() => new FilterFromAttribute($this));
  4835. }
  4836. public function GetBasicFilterOperators()
  4837. {
  4838. return array();
  4839. }
  4840. public function GetBasicFilterLooseOperator()
  4841. {
  4842. return "=";
  4843. }
  4844. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4845. {
  4846. $sQValue = CMDBSource::Quote($value);
  4847. switch ($sOpCode)
  4848. {
  4849. case '!=':
  4850. return $this->GetSQLExpr()." != $sQValue";
  4851. break;
  4852. case '=':
  4853. default:
  4854. return $this->GetSQLExpr()." = $sQValue";
  4855. }
  4856. }
  4857. public function GetSQLExpressions($sPrefix = '')
  4858. {
  4859. $oParent = $this->GetTargetAttDef();
  4860. $res = $oParent->GetSubItemSQLExpression($this->Get('item_code'));
  4861. return $res;
  4862. }
  4863. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4864. {
  4865. $oParent = $this->GetTargetAttDef();
  4866. $res = $oParent->GetSubItemAsHTML($this->Get('item_code'), $value);
  4867. return $res;
  4868. }
  4869. public function GetAsHTMLForHistory($value, $oHostObject = null, $bLocalize = true)
  4870. {
  4871. $oParent = $this->GetTargetAttDef();
  4872. $res = $oParent->GetSubItemAsHTMLForHistory($this->Get('item_code'), $value);
  4873. return $res;
  4874. }
  4875. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  4876. {
  4877. $oParent = $this->GetTargetAttDef();
  4878. $res = $oParent->GetSubItemAsCSV($this->Get('item_code'), $value, $sSeparator, $sTextQualifier, $bConvertToPlainText);
  4879. return $res;
  4880. }
  4881. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4882. {
  4883. $oParent = $this->GetTargetAttDef();
  4884. $res = $oParent->GetSubItemAsXML($this->Get('item_code'), $value);
  4885. return $res;
  4886. }
  4887. /**
  4888. * As of now, this function must be implemented to have the value in spreadsheet format
  4889. */
  4890. public function GetEditValue($value, $oHostObj = null)
  4891. {
  4892. $oParent = $this->GetTargetAttDef();
  4893. $res = $oParent->GetSubItemAsEditValue($this->Get('item_code'), $value);
  4894. return $res;
  4895. }
  4896. public function IsPartOfFingerprint() { return false; }
  4897. }
  4898. /**
  4899. * One way encrypted (hashed) password
  4900. */
  4901. class AttributeOneWayPassword extends AttributeDefinition
  4902. {
  4903. static public function ListExpectedParams()
  4904. {
  4905. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  4906. }
  4907. public function GetEditClass() {return "One Way Password";}
  4908. public function IsDirectField() {return true;}
  4909. public function IsScalar() {return true;}
  4910. public function IsWritable() {return true;}
  4911. public function GetDefaultValue(DBObject $oHostObject = null) {return "";}
  4912. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  4913. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  4914. public function MakeRealValue($proposedValue, $oHostObj)
  4915. {
  4916. $oPassword = $proposedValue;
  4917. if (!is_object($oPassword))
  4918. {
  4919. $oPassword = new ormPassword('', '');
  4920. $oPassword->SetPassword($proposedValue);
  4921. }
  4922. return $oPassword;
  4923. }
  4924. public function GetSQLExpressions($sPrefix = '')
  4925. {
  4926. if ($sPrefix == '')
  4927. {
  4928. $sPrefix = $this->GetCode(); // Warning: AttributeOneWayPassword does not have any sql property so code = sql !
  4929. }
  4930. $aColumns = array();
  4931. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  4932. $aColumns[''] = $sPrefix.'_hash';
  4933. $aColumns['_salt'] = $sPrefix.'_salt';
  4934. return $aColumns;
  4935. }
  4936. public function FromSQLToValue($aCols, $sPrefix = '')
  4937. {
  4938. if (!array_key_exists($sPrefix, $aCols))
  4939. {
  4940. $sAvailable = implode(', ', array_keys($aCols));
  4941. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4942. }
  4943. $hashed = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  4944. if (!array_key_exists($sPrefix.'_salt', $aCols))
  4945. {
  4946. $sAvailable = implode(', ', array_keys($aCols));
  4947. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  4948. }
  4949. $sSalt = isset($aCols[$sPrefix.'_salt']) ? $aCols[$sPrefix.'_salt'] : '';
  4950. $value = new ormPassword($hashed, $sSalt);
  4951. return $value;
  4952. }
  4953. public function GetSQLValues($value)
  4954. {
  4955. // #@# Optimization: do not load blobs anytime
  4956. // As per mySQL doc, selecting blob columns will prevent mySQL from
  4957. // using memory in case a temporary table has to be created
  4958. // (temporary tables created on disk)
  4959. // We will have to remove the blobs from the list of attributes when doing the select
  4960. // then the use of Get() should finalize the load
  4961. if ($value instanceOf ormPassword)
  4962. {
  4963. $aValues = array();
  4964. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  4965. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  4966. }
  4967. else
  4968. {
  4969. $aValues = array();
  4970. $aValues[$this->GetCode().'_hash'] = '';
  4971. $aValues[$this->GetCode().'_salt'] = '';
  4972. }
  4973. return $aValues;
  4974. }
  4975. public function GetSQLColumns($bFullSpec = false)
  4976. {
  4977. $aColumns = array();
  4978. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  4979. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  4980. return $aColumns;
  4981. }
  4982. public function GetImportColumns()
  4983. {
  4984. $aColumns = array();
  4985. $aColumns[$this->GetCode()] = 'TINYTEXT';
  4986. return $aColumns;
  4987. }
  4988. public function FromImportToValue($aCols, $sPrefix = '')
  4989. {
  4990. if (!isset($aCols[$sPrefix]))
  4991. {
  4992. $sAvailable = implode(', ', array_keys($aCols));
  4993. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4994. }
  4995. $sClearPwd = $aCols[$sPrefix];
  4996. $oPassword = new ormPassword('', '');
  4997. $oPassword->SetPassword($sClearPwd);
  4998. return $oPassword;
  4999. }
  5000. public function GetFilterDefinitions()
  5001. {
  5002. return array();
  5003. // still not working... see later...
  5004. }
  5005. public function GetBasicFilterOperators()
  5006. {
  5007. return array();
  5008. }
  5009. public function GetBasicFilterLooseOperator()
  5010. {
  5011. return '=';
  5012. }
  5013. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5014. {
  5015. return 'true';
  5016. }
  5017. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5018. {
  5019. if (is_object($value))
  5020. {
  5021. return $value->GetAsHTML();
  5022. }
  5023. }
  5024. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5025. {
  5026. return ''; // Not exportable in CSV
  5027. }
  5028. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5029. {
  5030. return ''; // Not exportable in XML
  5031. }
  5032. }
  5033. // Indexed array having two dimensions
  5034. class AttributeTable extends AttributeDBField
  5035. {
  5036. public function GetEditClass() {return "Table";}
  5037. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  5038. public function GetMaxSize()
  5039. {
  5040. return null;
  5041. }
  5042. public function GetNullValue()
  5043. {
  5044. return array();
  5045. }
  5046. public function IsNull($proposedValue)
  5047. {
  5048. return (count($proposedValue) == 0);
  5049. }
  5050. public function GetEditValue($sValue, $oHostObj = null)
  5051. {
  5052. return '';
  5053. }
  5054. // Facilitate things: allow the user to Set the value from a string
  5055. public function MakeRealValue($proposedValue, $oHostObj)
  5056. {
  5057. if (is_null($proposedValue))
  5058. {
  5059. return array();
  5060. }
  5061. else if (!is_array($proposedValue))
  5062. {
  5063. return array(0 => array(0 => $proposedValue));
  5064. }
  5065. return $proposedValue;
  5066. }
  5067. public function FromSQLToValue($aCols, $sPrefix = '')
  5068. {
  5069. try
  5070. {
  5071. $value = @unserialize($aCols[$sPrefix.'']);
  5072. if ($value === false)
  5073. {
  5074. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  5075. }
  5076. }
  5077. catch(Exception $e)
  5078. {
  5079. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  5080. }
  5081. return $value;
  5082. }
  5083. public function GetSQLValues($value)
  5084. {
  5085. $aValues = array();
  5086. $aValues[$this->Get("sql")] = serialize($value);
  5087. return $aValues;
  5088. }
  5089. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5090. {
  5091. if (!is_array($value))
  5092. {
  5093. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  5094. }
  5095. if (count($value) == 0)
  5096. {
  5097. return "";
  5098. }
  5099. $sRes = "<TABLE class=\"listResults\">";
  5100. $sRes .= "<TBODY>";
  5101. foreach($value as $iRow => $aRawData)
  5102. {
  5103. $sRes .= "<TR>";
  5104. foreach ($aRawData as $iCol => $cell)
  5105. {
  5106. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  5107. $sRes .= "<TD>$sCell</TD>";
  5108. }
  5109. $sRes .= "</TR>";
  5110. }
  5111. $sRes .= "</TBODY>";
  5112. $sRes .= "</TABLE>";
  5113. return $sRes;
  5114. }
  5115. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5116. {
  5117. // Not implemented
  5118. return '';
  5119. }
  5120. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5121. {
  5122. if (count($value) == 0)
  5123. {
  5124. return "";
  5125. }
  5126. $sRes = "";
  5127. foreach($value as $iRow => $aRawData)
  5128. {
  5129. $sRes .= "<row>";
  5130. foreach ($aRawData as $iCol => $cell)
  5131. {
  5132. $sCell = Str::pure2xml((string)$cell);
  5133. $sRes .= "<cell icol=\"$iCol\">$sCell</cell>";
  5134. }
  5135. $sRes .= "</row>";
  5136. }
  5137. return $sRes;
  5138. }
  5139. }
  5140. // The PHP value is a hash array, it is stored as a TEXT column
  5141. class AttributePropertySet extends AttributeTable
  5142. {
  5143. public function GetEditClass() {return "PropertySet";}
  5144. // Facilitate things: allow the user to Set the value from a string
  5145. public function MakeRealValue($proposedValue, $oHostObj)
  5146. {
  5147. if (!is_array($proposedValue))
  5148. {
  5149. return array('?' => (string)$proposedValue);
  5150. }
  5151. return $proposedValue;
  5152. }
  5153. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5154. {
  5155. if (!is_array($value))
  5156. {
  5157. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  5158. }
  5159. if (count($value) == 0)
  5160. {
  5161. return "";
  5162. }
  5163. $sRes = "<TABLE class=\"listResults\">";
  5164. $sRes .= "<TBODY>";
  5165. foreach($value as $sProperty => $sValue)
  5166. {
  5167. if ($sProperty == 'auth_pwd')
  5168. {
  5169. $sValue = '*****';
  5170. }
  5171. $sRes .= "<TR>";
  5172. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  5173. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  5174. $sRes .= "</TR>";
  5175. }
  5176. $sRes .= "</TBODY>";
  5177. $sRes .= "</TABLE>";
  5178. return $sRes;
  5179. }
  5180. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5181. {
  5182. if (count($value) == 0)
  5183. {
  5184. return "";
  5185. }
  5186. $aRes = array();
  5187. foreach($value as $sProperty => $sValue)
  5188. {
  5189. if ($sProperty == 'auth_pwd')
  5190. {
  5191. $sValue = '*****';
  5192. }
  5193. $sFrom = array(',', '=');
  5194. $sTo = array('\,', '\=');
  5195. $aRes[] = $sProperty.'='.str_replace($sFrom, $sTo, (string)$sValue);
  5196. }
  5197. $sRaw = implode(',', $aRes);
  5198. $sFrom = array("\r\n", $sTextQualifier);
  5199. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5200. $sEscaped = str_replace($sFrom, $sTo, $sRaw);
  5201. return $sTextQualifier.$sEscaped.$sTextQualifier;
  5202. }
  5203. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5204. {
  5205. if (count($value) == 0)
  5206. {
  5207. return "";
  5208. }
  5209. $sRes = "";
  5210. foreach($value as $sProperty => $sValue)
  5211. {
  5212. if ($sProperty == 'auth_pwd')
  5213. {
  5214. $sValue = '*****';
  5215. }
  5216. $sRes .= "<property id=\"$sProperty\">";
  5217. $sRes .= Str::pure2xml((string)$sValue);
  5218. $sRes .= "</property>";
  5219. }
  5220. return $sRes;
  5221. }
  5222. }
  5223. /**
  5224. * The attribute dedicated to the friendly name automatic attribute (not written)
  5225. *
  5226. * @package iTopORM
  5227. */
  5228. class AttributeComputedFieldVoid extends AttributeDefinition
  5229. {
  5230. static public function ListExpectedParams()
  5231. {
  5232. return array_merge(parent::ListExpectedParams(), array());
  5233. }
  5234. public function GetEditClass() {return "";}
  5235. public function GetValuesDef() {return null;}
  5236. public function GetPrerequisiteAttributes($sClass = null) {return $this->GetOptional("depends_on", array());}
  5237. public function IsDirectField() {return true;}
  5238. public function IsScalar() {return true;}
  5239. public function IsWritable() {return false;}
  5240. public function GetSQLExpr()
  5241. {
  5242. return null;
  5243. }
  5244. public function GetDefaultValue(DBObject $oHostObject = null) {return $this->MakeRealValue("", $oHostObject);}
  5245. public function IsNullAllowed() {return false;}
  5246. //
  5247. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  5248. public function GetSQLExpressions($sPrefix = '')
  5249. {
  5250. if ($sPrefix == '')
  5251. {
  5252. $sPrefix = $this->GetCode(); // Warning AttributeComputedFieldVoid does not have any sql property
  5253. }
  5254. return array('' => $sPrefix);
  5255. }
  5256. public function FromSQLToValue($aCols, $sPrefix = '')
  5257. {
  5258. return null;
  5259. }
  5260. public function GetSQLValues($value)
  5261. {
  5262. return array();
  5263. }
  5264. public function GetSQLColumns($bFullSpec = false)
  5265. {
  5266. return array();
  5267. }
  5268. public function GetFilterDefinitions()
  5269. {
  5270. return array($this->GetCode() => new FilterFromAttribute($this));
  5271. }
  5272. public function GetBasicFilterOperators()
  5273. {
  5274. return array("="=>"equals", "!="=>"differs from");
  5275. }
  5276. public function GetBasicFilterLooseOperator()
  5277. {
  5278. return "=";
  5279. }
  5280. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5281. {
  5282. $sQValue = CMDBSource::Quote($value);
  5283. switch ($sOpCode)
  5284. {
  5285. case '!=':
  5286. return $this->GetSQLExpr()." != $sQValue";
  5287. break;
  5288. case '=':
  5289. default:
  5290. return $this->GetSQLExpr()." = $sQValue";
  5291. }
  5292. }
  5293. public function IsPartOfFingerprint() { return false; }
  5294. }
  5295. /**
  5296. * The attribute dedicated to the friendly name automatic attribute (not written)
  5297. *
  5298. * @package iTopORM
  5299. */
  5300. class AttributeFriendlyName extends AttributeComputedFieldVoid
  5301. {
  5302. public function __construct($sCode, $sExtKeyAttCode)
  5303. {
  5304. $this->m_sCode = $sCode;
  5305. $aParams = array();
  5306. // $aParams["is_null_allowed"] = false,
  5307. $aParams["default_value"] = '';
  5308. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  5309. parent::__construct($sCode, $aParams);
  5310. $this->m_sValue = $this->Get("default_value");
  5311. }
  5312. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  5313. public function GetExtAttCode() {return 'friendlyname';}
  5314. public function GetLabel($sDefault = null)
  5315. {
  5316. $sLabel = parent::GetLabel('');
  5317. if (strlen($sLabel) == 0)
  5318. {
  5319. $sKeyAttCode = $this->Get("extkey_attcode");
  5320. if ($sKeyAttCode == 'id')
  5321. {
  5322. return Dict::S('Core:FriendlyName-Label');
  5323. }
  5324. else
  5325. {
  5326. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  5327. $sLabel = $oExtKeyAttDef->GetLabel($this->m_sCode);
  5328. }
  5329. }
  5330. return $sLabel;
  5331. }
  5332. public function GetDescription($sDefault = null)
  5333. {
  5334. $sLabel = parent::GetDescription('');
  5335. if (strlen($sLabel) == 0)
  5336. {
  5337. $sKeyAttCode = $this->Get("extkey_attcode");
  5338. if ($sKeyAttCode == 'id')
  5339. {
  5340. return Dict::S('Core:FriendlyName-Description');
  5341. }
  5342. else
  5343. {
  5344. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  5345. $sLabel = $oExtKeyAttDef->GetDescription('');
  5346. }
  5347. }
  5348. return $sLabel;
  5349. }
  5350. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  5351. protected function GetSQLCol($bFullSpec = false) {return "";}
  5352. public function FromSQLToValue($aCols, $sPrefix = '')
  5353. {
  5354. $sValue = $aCols[$sPrefix];
  5355. return $sValue;
  5356. }
  5357. /**
  5358. * Encrypt the value before storing it in the database
  5359. */
  5360. public function GetSQLValues($value)
  5361. {
  5362. return array();
  5363. }
  5364. public function IsWritable()
  5365. {
  5366. return false;
  5367. }
  5368. public function IsDirectField()
  5369. {
  5370. return false;
  5371. }
  5372. public function SetFixedValue($sValue)
  5373. {
  5374. $this->m_sValue = $sValue;
  5375. }
  5376. public function GetDefaultValue(DBObject $oHostObject = null)
  5377. {
  5378. return $this->m_sValue;
  5379. }
  5380. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  5381. {
  5382. return Str::pure2html((string)$sValue);
  5383. }
  5384. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5385. {
  5386. $sFrom = array("\r\n", $sTextQualifier);
  5387. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5388. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  5389. return $sTextQualifier.$sEscaped.$sTextQualifier;
  5390. }
  5391. static function GetFormFieldClass()
  5392. {
  5393. return '\\Combodo\\iTop\\Form\\Field\\StringField';
  5394. }
  5395. public function GetFormField(DBObject $oObject, $oFormField = null)
  5396. {
  5397. if ($oFormField === null)
  5398. {
  5399. $sFormFieldClass = static::GetFormFieldClass();
  5400. $oFormField = new $sFormFieldClass($this->GetCode());
  5401. }
  5402. $oFormField->SetReadOnly(true);
  5403. parent::GetFormField($oObject, $oFormField);
  5404. return $oFormField;
  5405. }
  5406. // Do not display friendly names in the history of change
  5407. public function DescribeChangeAsHTML($sOldValue, $sNewValue, $sLabel = null)
  5408. {
  5409. return '';
  5410. }
  5411. public function GetBasicFilterLooseOperator()
  5412. {
  5413. return "Contains";
  5414. }
  5415. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5416. {
  5417. $sQValue = CMDBSource::Quote($value);
  5418. switch ($sOpCode)
  5419. {
  5420. case '=':
  5421. case '!=':
  5422. return $this->GetSQLExpr()." $sOpCode $sQValue";
  5423. case 'Contains':
  5424. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  5425. case 'NotLike':
  5426. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  5427. case 'Like':
  5428. default:
  5429. return $this->GetSQLExpr()." LIKE $sQValue";
  5430. }
  5431. }
  5432. public function IsPartOfFingerprint() { return false; }
  5433. }
  5434. /**
  5435. * Holds the setting for the redundancy on a specific relation
  5436. * Its value is a string, containing either:
  5437. * - 'disabled'
  5438. * - 'n', where n is a positive integer value giving the minimum count of items upstream
  5439. * - 'n%', where n is a positive integer value, giving the minimum as a percentage of the total count of items upstream
  5440. *
  5441. * @package iTopORM
  5442. */
  5443. class AttributeRedundancySettings extends AttributeDBField
  5444. {
  5445. static public function ListExpectedParams()
  5446. {
  5447. return array('sql', 'relation_code', 'from_class', 'neighbour_id', 'enabled', 'enabled_mode', 'min_up', 'min_up_type', 'min_up_mode');
  5448. }
  5449. public function GetValuesDef() {return null;}
  5450. public function GetPrerequisiteAttributes($sClass = null) {return array();}
  5451. public function GetEditClass() {return "RedundancySetting";}
  5452. protected function GetSQLCol($bFullSpec = false)
  5453. {
  5454. return "VARCHAR(20)".($bFullSpec ? $this->GetSQLColSpec() : '');
  5455. }
  5456. public function GetValidationPattern()
  5457. {
  5458. return "^[0-9]{1,3}|[0-9]{1,2}%|disabled$";
  5459. }
  5460. public function GetMaxSize()
  5461. {
  5462. return 20;
  5463. }
  5464. public function GetDefaultValue(DBObject $oHostObject = null)
  5465. {
  5466. $sRet = 'disabled';
  5467. if ($this->Get('enabled'))
  5468. {
  5469. if ($this->Get('min_up_type') == 'count')
  5470. {
  5471. $sRet = (string) $this->Get('min_up');
  5472. }
  5473. else // percent
  5474. {
  5475. $sRet = $this->Get('min_up').'%';
  5476. }
  5477. }
  5478. return $sRet;
  5479. }
  5480. public function IsNullAllowed()
  5481. {
  5482. return false;
  5483. }
  5484. public function GetNullValue()
  5485. {
  5486. return '';
  5487. }
  5488. public function IsNull($proposedValue)
  5489. {
  5490. return ($proposedValue == '');
  5491. }
  5492. public function MakeRealValue($proposedValue, $oHostObj)
  5493. {
  5494. if (is_null($proposedValue)) return '';
  5495. return (string)$proposedValue;
  5496. }
  5497. public function ScalarToSQL($value)
  5498. {
  5499. if (!is_string($value))
  5500. {
  5501. throw new CoreException('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetHostClass(), 'attribute' => $this->GetCode()));
  5502. }
  5503. return $value;
  5504. }
  5505. public function GetRelationQueryData()
  5506. {
  5507. foreach (MetaModel::EnumRelationQueries($this->GetHostClass(), $this->Get('relation_code'), false) as $sDummy => $aQueryInfo)
  5508. {
  5509. if ($aQueryInfo['sFromClass'] == $this->Get('from_class'))
  5510. {
  5511. if ($aQueryInfo['sNeighbour'] == $this->Get('neighbour_id'))
  5512. {
  5513. return $aQueryInfo;
  5514. }
  5515. }
  5516. }
  5517. }
  5518. /**
  5519. * Find the user option label
  5520. * @param user option : disabled|cout|percent
  5521. */
  5522. public function GetUserOptionFormat($sUserOption, $sDefault = null)
  5523. {
  5524. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, null, true /*user lang*/);
  5525. if (is_null($sLabel))
  5526. {
  5527. // If no default value is specified, let's define the most relevant one for developping purposes
  5528. if (is_null($sDefault))
  5529. {
  5530. $sDefault = str_replace('_', ' ', $this->m_sCode.':'.$sUserOption.'(%1$s)');
  5531. }
  5532. // Browse the hierarchy again, accepting default (english) translations
  5533. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, $sDefault, false);
  5534. }
  5535. return $sLabel;
  5536. }
  5537. /**
  5538. * Override to display the value in the GUI
  5539. */
  5540. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  5541. {
  5542. $sCurrentOption = $this->GetCurrentOption($sValue);
  5543. $sClass = $oHostObject ? get_class($oHostObject) : $this->m_sHostClass;
  5544. return sprintf($this->GetUserOptionFormat($sCurrentOption), $this->GetMinUpValue($sValue), MetaModel::GetName($sClass));
  5545. }
  5546. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5547. {
  5548. $sFrom = array("\r\n", $sTextQualifier);
  5549. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5550. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  5551. return $sTextQualifier.$sEscaped.$sTextQualifier;
  5552. }
  5553. /**
  5554. * Helper to interpret the value, given the current settings and string representation of the attribute
  5555. */
  5556. public function IsEnabled($sValue)
  5557. {
  5558. if ($this->get('enabled_mode') == 'fixed')
  5559. {
  5560. $bRet = $this->get('enabled');
  5561. }
  5562. else
  5563. {
  5564. $bRet = ($sValue != 'disabled');
  5565. }
  5566. return $bRet;
  5567. }
  5568. /**
  5569. * Helper to interpret the value, given the current settings and string representation of the attribute
  5570. */
  5571. public function GetMinUpType($sValue)
  5572. {
  5573. if ($this->get('min_up_mode') == 'fixed')
  5574. {
  5575. $sRet = $this->get('min_up_type');
  5576. }
  5577. else
  5578. {
  5579. $sRet = 'count';
  5580. if (substr(trim($sValue), -1, 1) == '%')
  5581. {
  5582. $sRet = 'percent';
  5583. }
  5584. }
  5585. return $sRet;
  5586. }
  5587. /**
  5588. * Helper to interpret the value, given the current settings and string representation of the attribute
  5589. */
  5590. public function GetMinUpValue($sValue)
  5591. {
  5592. if ($this->get('min_up_mode') == 'fixed')
  5593. {
  5594. $iRet = (int) $this->Get('min_up');
  5595. }
  5596. else
  5597. {
  5598. $sRefValue = $sValue;
  5599. if (substr(trim($sValue), -1, 1) == '%')
  5600. {
  5601. $sRefValue = substr(trim($sValue), 0, -1);
  5602. }
  5603. $iRet = (int) trim($sRefValue);
  5604. }
  5605. return $iRet;
  5606. }
  5607. /**
  5608. * Helper to determine if the redundancy can be viewed/edited by the end-user
  5609. */
  5610. public function IsVisible()
  5611. {
  5612. $bRet = false;
  5613. if ($this->Get('enabled_mode') == 'fixed')
  5614. {
  5615. $bRet = $this->Get('enabled');
  5616. }
  5617. elseif ($this->Get('enabled_mode') == 'user')
  5618. {
  5619. $bRet = true;
  5620. }
  5621. return $bRet;
  5622. }
  5623. public function IsWritable()
  5624. {
  5625. if (($this->Get('enabled_mode') == 'fixed') && ($this->Get('min_up_mode') == 'fixed'))
  5626. {
  5627. return false;
  5628. }
  5629. return true;
  5630. }
  5631. /**
  5632. * Returns an HTML form that can be read by ReadValueFromPostedForm
  5633. */
  5634. public function GetDisplayForm($sCurrentValue, $oPage, $bEditMode = false, $sFormPrefix = '')
  5635. {
  5636. $sRet = '';
  5637. $aUserOptions = $this->GetUserOptions($sCurrentValue);
  5638. if (count($aUserOptions) < 2)
  5639. {
  5640. $bEditOption = false;
  5641. }
  5642. else
  5643. {
  5644. $bEditOption = $bEditMode;
  5645. }
  5646. $sCurrentOption = $this->GetCurrentOption($sCurrentValue);
  5647. foreach($aUserOptions as $sUserOption)
  5648. {
  5649. $bSelected = ($sUserOption == $sCurrentOption);
  5650. $sRet .= '<div>';
  5651. $sRet .= $this->GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditOption, $sUserOption, $bSelected);
  5652. $sRet .= '</div>';
  5653. }
  5654. return $sRet;
  5655. }
  5656. const USER_OPTION_DISABLED = 'disabled';
  5657. const USER_OPTION_ENABLED_COUNT = 'count';
  5658. const USER_OPTION_ENABLED_PERCENT = 'percent';
  5659. /**
  5660. * Depending on the xxx_mode parameters, build the list of options that are allowed to the end-user
  5661. */
  5662. protected function GetUserOptions($sValue)
  5663. {
  5664. $aRet = array();
  5665. if ($this->Get('enabled_mode') == 'user')
  5666. {
  5667. $aRet[] = self::USER_OPTION_DISABLED;
  5668. }
  5669. if ($this->Get('min_up_mode') == 'user')
  5670. {
  5671. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  5672. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  5673. }
  5674. else
  5675. {
  5676. if ($this->GetMinUpType($sValue) == 'count')
  5677. {
  5678. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  5679. }
  5680. else
  5681. {
  5682. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  5683. }
  5684. }
  5685. return $aRet;
  5686. }
  5687. /**
  5688. * Convert the string representation into one of the existing options
  5689. */
  5690. protected function GetCurrentOption($sValue)
  5691. {
  5692. $sRet = self::USER_OPTION_DISABLED;
  5693. if ($this->IsEnabled($sValue))
  5694. {
  5695. if ($this->GetMinUpType($sValue) == 'count')
  5696. {
  5697. $sRet = self::USER_OPTION_ENABLED_COUNT;
  5698. }
  5699. else
  5700. {
  5701. $sRet = self::USER_OPTION_ENABLED_PERCENT;
  5702. }
  5703. }
  5704. return $sRet;
  5705. }
  5706. /**
  5707. * Display an option (form, or current value)
  5708. */
  5709. protected function GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditMode, $sUserOption, $bSelected = true)
  5710. {
  5711. $sRet = '';
  5712. $iCurrentValue = $this->GetMinUpValue($sCurrentValue);
  5713. if ($bEditMode)
  5714. {
  5715. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  5716. switch ($sUserOption)
  5717. {
  5718. case self::USER_OPTION_DISABLED:
  5719. $sValue = ''; // Empty placeholder
  5720. break;
  5721. case self::USER_OPTION_ENABLED_COUNT:
  5722. if ($bEditMode)
  5723. {
  5724. $sName = $sHtmlNamesPrefix.'_min_up_count';
  5725. $sEditValue = $bSelected ? $iCurrentValue : '';
  5726. $sValue = '<input class="redundancy-min-up-count" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  5727. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  5728. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  5729. }
  5730. else
  5731. {
  5732. $sValue = $iCurrentValue;
  5733. }
  5734. break;
  5735. case self::USER_OPTION_ENABLED_PERCENT:
  5736. if ($bEditMode)
  5737. {
  5738. $sName = $sHtmlNamesPrefix.'_min_up_percent';
  5739. $sEditValue = $bSelected ? $iCurrentValue : '';
  5740. $sValue = '<input class="redundancy-min-up-percent" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  5741. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  5742. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  5743. }
  5744. else
  5745. {
  5746. $sValue = $iCurrentValue;
  5747. }
  5748. break;
  5749. }
  5750. $sLabel = sprintf($this->GetUserOptionFormat($sUserOption), $sValue, MetaModel::GetName($this->GetHostClass()));
  5751. $sOptionName = $sHtmlNamesPrefix.'_user_option';
  5752. $sOptionId = $sOptionName.'_'.$sUserOption;
  5753. $sChecked = $bSelected ? 'checked' : '';
  5754. $sRet = '<input type="radio" name="'.$sOptionName.'" id="'.$sOptionId.'" value="'.$sUserOption.'"'.$sChecked.'> <label for="'.$sOptionId.'">'.$sLabel.'</label>';
  5755. }
  5756. else
  5757. {
  5758. // Read-only: display only the currently selected option
  5759. if ($bSelected)
  5760. {
  5761. $sRet = sprintf($this->GetUserOptionFormat($sUserOption), $iCurrentValue, MetaModel::GetName($this->GetHostClass()));
  5762. }
  5763. }
  5764. return $sRet;
  5765. }
  5766. /**
  5767. * Makes the string representation out of the values given by the form defined in GetDisplayForm
  5768. */
  5769. public function ReadValueFromPostedForm($sFormPrefix)
  5770. {
  5771. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  5772. $iMinUpCount = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_count', null, 'raw_data');
  5773. $iMinUpPercent = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_percent', null, 'raw_data');
  5774. $sSelectedOption = utils::ReadPostedParam($sHtmlNamesPrefix.'_user_option', null, 'raw_data');
  5775. switch ($sSelectedOption)
  5776. {
  5777. case self::USER_OPTION_ENABLED_COUNT:
  5778. $sRet = $iMinUpCount;
  5779. break;
  5780. case self::USER_OPTION_ENABLED_PERCENT:
  5781. $sRet = $iMinUpPercent.'%';
  5782. break;
  5783. case self::USER_OPTION_DISABLED:
  5784. default:
  5785. $sRet = 'disabled';
  5786. break;
  5787. }
  5788. return $sRet;
  5789. }
  5790. }
  5791. /**
  5792. * Custom fields managed by an external implementation
  5793. *
  5794. * @package iTopORM
  5795. */
  5796. class AttributeCustomFields extends AttributeDefinition
  5797. {
  5798. static public function ListExpectedParams()
  5799. {
  5800. return array_merge(parent::ListExpectedParams(), array("handler_class"));
  5801. }
  5802. public function GetEditClass() {return "CustomFields";}
  5803. public function IsWritable() {return true;}
  5804. public function LoadFromDB() {return false;} // See ReadValue...
  5805. public function GetDefaultValue(DBObject $oHostObject = null)
  5806. {
  5807. return new ormCustomFieldsValue($oHostObject, $this->GetCode());
  5808. }
  5809. public function GetBasicFilterOperators() {return array();}
  5810. public function GetBasicFilterLooseOperator() {return '';}
  5811. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  5812. /**
  5813. * @param DBObject $oHostObject
  5814. * @param ormCustomFieldsValue|null $oValue
  5815. * @return CustomFieldsHandler
  5816. */
  5817. public function GetHandler(DBObject $oHostObject, ormCustomFieldsValue $oValue = null)
  5818. {
  5819. $sHandlerClass = $this->Get('handler_class');
  5820. $oHandler = new $sHandlerClass($oHostObject, $this->GetCode());
  5821. if (!is_null($oValue))
  5822. {
  5823. $oHandler->SetCurrentValues($oValue->GetValues());
  5824. }
  5825. return $oHandler;
  5826. }
  5827. public function GetPrerequisiteAttributes($sClass = null)
  5828. {
  5829. $sHandlerClass = $this->Get('handler_class');
  5830. return $sHandlerClass::GetPrerequisiteAttributes($sClass);
  5831. }
  5832. public function GetEditValue($sValue, $oHostObj = null)
  5833. {
  5834. return 'GetEditValueNotImplemented for '.get_class($this);
  5835. }
  5836. /**
  5837. * Makes the string representation out of the values given by the form defined in GetDisplayForm
  5838. */
  5839. public function ReadValueFromPostedForm($oHostObject, $sFormPrefix)
  5840. {
  5841. $aRawData = json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$this->GetCode()}", '{}', 'raw_data'), true);
  5842. return new ormCustomFieldsValue($oHostObject, $this->GetCode(), $aRawData);
  5843. }
  5844. public function MakeRealValue($proposedValue, $oHostObject)
  5845. {
  5846. if (is_object($proposedValue) && ($proposedValue instanceof ormCustomFieldsValue))
  5847. {
  5848. return $proposedValue;
  5849. }
  5850. elseif (is_string($proposedValue))
  5851. {
  5852. $aValues = json_decode($proposedValue, true);
  5853. return new ormCustomFieldsValue($oHostObject, $this->GetCode(), $aValues);
  5854. }
  5855. elseif (is_array($proposedValue))
  5856. {
  5857. return new ormCustomFieldsValue($oHostObject, $this->GetCode(), $proposedValue);
  5858. }
  5859. throw new Exception('Unexpected type for the value of a custom fields attribute: '.gettype($proposedValue));
  5860. }
  5861. static public function GetFormFieldClass()
  5862. {
  5863. return '\\Combodo\\iTop\\Form\\Field\\SubFormField';
  5864. }
  5865. /**
  5866. * Override to build the relevant form field
  5867. *
  5868. * 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.
  5869. */
  5870. public function MakeFormField(DBObject $oObject, $oFormField = null)
  5871. {
  5872. if ($oFormField === null)
  5873. {
  5874. $sFormFieldClass = static::GetFormFieldClass();
  5875. $oFormField = new $sFormFieldClass($this->GetCode());
  5876. $oFormField->SetForm($this->GetForm($oObject));
  5877. }
  5878. parent::MakeFormField($oObject, $oFormField);
  5879. return $oFormField;
  5880. }
  5881. /**
  5882. * @param DBObject $oHostObject
  5883. * @return Combodo\iTop\Form\Form
  5884. */
  5885. public function GetForm(DBObject $oHostObject, $sFormPrefix = null)
  5886. {
  5887. $oHandler = $this->GetHandler($oHostObject, $oHostObject->Get($this->GetCode()));
  5888. $sFormId = is_null($sFormPrefix) ? 'cf_'.$this->GetCode() : $sFormPrefix.'_cf_'.$this->GetCode();
  5889. $oHandler->BuildForm($sFormId);
  5890. return $oHandler->GetForm();
  5891. }
  5892. /**
  5893. * Read the data from where it has been stored. This verb must be implemented as soon as LoadFromDB returns false and LoadInObject returns true
  5894. * @param $oHostObject
  5895. * @return ormCustomFieldsValue
  5896. */
  5897. public function ReadValue($oHostObject)
  5898. {
  5899. $oHandler = $this->GetHandler($oHostObject);
  5900. $aValues = $oHandler->ReadValues();
  5901. $oRet = new ormCustomFieldsValue($oHostObject, $this->GetCode(), $aValues);
  5902. return $oRet;
  5903. }
  5904. /**
  5905. * Record the data (currently in the processing of recording the host object)
  5906. * It is assumed that the data has been checked prior to calling Write()
  5907. * @param DBObject $oHostObject
  5908. * @param ormCustomFieldsValue|null $oValue (null is the default value)
  5909. */
  5910. public function WriteValue(DBObject $oHostObject, ormCustomFieldsValue $oValue = null)
  5911. {
  5912. $oHandler = $this->GetHandler($oHostObject, $oHostObject->Get($this->GetCode()));
  5913. if (is_null($oValue))
  5914. {
  5915. $aValues = array();
  5916. }
  5917. else
  5918. {
  5919. $aValues = $oValue->GetValues();
  5920. }
  5921. return $oHandler->WriteValues($aValues);
  5922. }
  5923. /**
  5924. * Check the validity of the data
  5925. * @param DBObject $oHostObject
  5926. * @param $value
  5927. * @return bool|string true or error message
  5928. */
  5929. public function CheckValue(DBObject $oHostObject, $value)
  5930. {
  5931. try
  5932. {
  5933. $oHandler = $this->GetHandler($oHostObject, $value);
  5934. $oHandler->BuildForm('');
  5935. $oForm = $oHandler->GetForm();
  5936. $oForm->Validate();
  5937. if ($oForm->GetValid())
  5938. {
  5939. $ret = true;
  5940. }
  5941. else
  5942. {
  5943. $aMessages = array();
  5944. foreach ($oForm->GetErrorMessages() as $sFieldId => $aFieldMessages)
  5945. {
  5946. $aMessages[] = $sFieldId.': '.implode(', ', $aFieldMessages);
  5947. }
  5948. $ret = 'Invalid value: '.implode(', ', $aMessages);
  5949. }
  5950. }
  5951. catch (Exception $e)
  5952. {
  5953. $ret = $e->getMessage();
  5954. }
  5955. return $ret;
  5956. }
  5957. /**
  5958. * Cleanup data upon object deletion (object id still available here)
  5959. * @param DBObject $oHostObject
  5960. */
  5961. public function DeleteValue(DBObject $oHostObject)
  5962. {
  5963. $oHandler = $this->GetHandler($oHostObject, $oHostObject->Get($this->GetCode()));
  5964. return $oHandler->DeleteValues();
  5965. }
  5966. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5967. {
  5968. return $value->GetAsHTML($bLocalize);
  5969. }
  5970. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5971. {
  5972. return $value->GetAsXML($bLocalize);
  5973. }
  5974. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5975. {
  5976. return $value->GetAsCSV($sSeparator, $sTextQualifier, $bLocalize, $bConvertToPlainText);
  5977. }
  5978. /**
  5979. * List the available verbs for 'GetForTemplate'
  5980. */
  5981. public function EnumTemplateVerbs()
  5982. {
  5983. $sHandlerClass = $this->Get('handler_class');
  5984. return $sHandlerClass::EnumTemplateVerbs();
  5985. }
  5986. /**
  5987. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  5988. * @param $value mixed The current value of the field
  5989. * @param $sVerb string The verb specifying the representation of the value
  5990. * @param $oHostObject DBObject The object
  5991. * @param $bLocalize bool Whether or not to localize the value
  5992. */
  5993. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  5994. {
  5995. return $value->GetForTemplate($sVerb, $bLocalize);
  5996. }
  5997. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  5998. {
  5999. return null;
  6000. }
  6001. /**
  6002. * Helper to get a value that will be JSON encoded
  6003. * The operation is the opposite to FromJSONToValue
  6004. */
  6005. public function GetForJSON($value)
  6006. {
  6007. return null;
  6008. }
  6009. /**
  6010. * Helper to form a value, given JSON decoded data
  6011. * The operation is the opposite to GetForJSON
  6012. */
  6013. public function FromJSONToValue($json)
  6014. {
  6015. return null;
  6016. }
  6017. public function Equals($val1, $val2)
  6018. {
  6019. return $val1->Equals($val2);
  6020. }
  6021. }