attributedef.class.inc.php 216 KB

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