attributedef.class.inc.php 166 KB

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