attributedef.class.inc.php 196 KB

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