attributedef.class.inc.php 191 KB

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