attributedef.class.inc.php 162 KB

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