attributedef.class.inc.php 206 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411
  1. <?php
  2. // Copyright (C) 2010-2017 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Typology for the attributes
  20. *
  21. * @copyright Copyright (C) 2010-2017 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('MyHelpers.class.inc.php');
  25. require_once('ormdocument.class.inc.php');
  26. require_once('ormstopwatch.class.inc.php');
  27. require_once('ormpassword.class.inc.php');
  28. require_once('ormcaselog.class.inc.php');
  29. require_once('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){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->IsWritable() && (!$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. /**
  1899. * An enum can be localized
  1900. */
  1901. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  1902. {
  1903. if ($bLocalizedValue)
  1904. {
  1905. // Lookup for the value matching the input
  1906. //
  1907. $sFoundValue = null;
  1908. $aRawValues = self::GetAllowedValues();
  1909. if (!is_null($aRawValues))
  1910. {
  1911. foreach ($aRawValues as $sKey => $sValue)
  1912. {
  1913. if ($sProposedValue == $sValue)
  1914. {
  1915. $sFoundValue = $sKey;
  1916. break;
  1917. }
  1918. }
  1919. }
  1920. if (is_null($sFoundValue))
  1921. {
  1922. return null;
  1923. }
  1924. return $this->MakeRealValue($sFoundValue, null);
  1925. }
  1926. else
  1927. {
  1928. return parent::MakeValueFromString($sProposedValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue, $sAttributeQualifier);
  1929. }
  1930. }
  1931. // Because this is sometimes used to get a localized/string version of an attribute...
  1932. public function GetEditValue($sValue, $oHostObj = null)
  1933. {
  1934. if (empty($sValue)) return '';
  1935. return MetaModel::GetName($sValue);
  1936. }
  1937. /**
  1938. * Helper to get a value that will be JSON encoded
  1939. * The operation is the opposite to FromJSONToValue
  1940. */
  1941. public function GetForJSON($value)
  1942. {
  1943. // JSON values are NOT localized
  1944. return $value;
  1945. }
  1946. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  1947. {
  1948. if ($bLocalize && $value != '')
  1949. {
  1950. $sRawValue = MetaModel::GetName($value);
  1951. }
  1952. else
  1953. {
  1954. $sRawValue = $value;
  1955. }
  1956. return parent::GetAsCSV($sRawValue, $sSeparator, $sTextQualifier, null, false, $bConvertToPlainText);
  1957. }
  1958. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  1959. {
  1960. if (empty($value)) return '';
  1961. if ($bLocalize)
  1962. {
  1963. $sRawValue = MetaModel::GetName($value);
  1964. }
  1965. else
  1966. {
  1967. $sRawValue = $value;
  1968. }
  1969. return Str::pure2xml($sRawValue);
  1970. }
  1971. public function GetBasicFilterLooseOperator()
  1972. {
  1973. return '=';
  1974. }
  1975. public function GetValueLabel($sValue)
  1976. {
  1977. if (empty($sValue)) return '';
  1978. return MetaModel::GetName($sValue);
  1979. }
  1980. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1981. {
  1982. $aRawValues = MetaModel::EnumChildClasses($this->GetHostClass(), ENUM_CHILD_CLASSES_ALL);
  1983. $aLocalizedValues = array();
  1984. foreach ($aRawValues as $sClass)
  1985. {
  1986. $aLocalizedValues[$sClass] = MetaModel::GetName($sClass);
  1987. }
  1988. return $aLocalizedValues;
  1989. }
  1990. }
  1991. /**
  1992. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  1993. *
  1994. * @package iTopORM
  1995. */
  1996. class AttributePassword extends AttributeString
  1997. {
  1998. static public function ListExpectedParams()
  1999. {
  2000. return parent::ListExpectedParams();
  2001. //return array_merge(parent::ListExpectedParams(), array());
  2002. }
  2003. public function GetEditClass() {return "Password";}
  2004. protected function GetSQLCol($bFullSpec = false) {return "VARCHAR(64)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  2005. public function GetMaxSize()
  2006. {
  2007. return 64;
  2008. }
  2009. public function GetFilterDefinitions()
  2010. {
  2011. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  2012. // not allowed to search on passwords!
  2013. return array();
  2014. }
  2015. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2016. {
  2017. if (strlen($sValue) == 0)
  2018. {
  2019. return '';
  2020. }
  2021. else
  2022. {
  2023. return '******';
  2024. }
  2025. }
  2026. 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'
  2027. }
  2028. /**
  2029. * Map a text column (size < 255) to an attribute that is encrypted in the database
  2030. * The encryption is based on a key set per iTop instance. Thus if you export your
  2031. * database (in SQL) to someone else without providing the key at the same time
  2032. * the encrypted fields will remain encrypted
  2033. *
  2034. * @package iTopORM
  2035. */
  2036. class AttributeEncryptedString extends AttributeString
  2037. {
  2038. static $sKey = null; // Encryption key used for all encrypted fields
  2039. public function __construct($sCode, $aParams)
  2040. {
  2041. parent::__construct($sCode, $aParams);
  2042. if (self::$sKey == null)
  2043. {
  2044. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  2045. }
  2046. }
  2047. /**
  2048. * When the attribute definitions are stored in APC cache:
  2049. * 1) The static class variable $sKey is NOT serialized
  2050. * 2) The object's constructor is NOT called upon wakeup
  2051. * 3) mcrypt may crash the server if passed an empty key !!
  2052. *
  2053. * So let's restore the key (if needed) when waking up
  2054. **/
  2055. public function __wakeup()
  2056. {
  2057. if (self::$sKey == null)
  2058. {
  2059. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  2060. }
  2061. }
  2062. protected function GetSQLCol($bFullSpec = false) {return "TINYBLOB";}
  2063. public function GetMaxSize()
  2064. {
  2065. return 255;
  2066. }
  2067. public function GetFilterDefinitions()
  2068. {
  2069. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  2070. // not allowed to search on encrypted fields !
  2071. return array();
  2072. }
  2073. public function MakeRealValue($proposedValue, $oHostObj)
  2074. {
  2075. if (is_null($proposedValue)) return null;
  2076. return (string)$proposedValue;
  2077. }
  2078. /**
  2079. * Decrypt the value when reading from the database
  2080. */
  2081. public function FromSQLToValue($aCols, $sPrefix = '')
  2082. {
  2083. $oSimpleCrypt = new SimpleCrypt();
  2084. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  2085. return $sValue;
  2086. }
  2087. /**
  2088. * Encrypt the value before storing it in the database
  2089. */
  2090. public function GetSQLValues($value)
  2091. {
  2092. $oSimpleCrypt = new SimpleCrypt();
  2093. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  2094. $aValues = array();
  2095. $aValues[$this->Get("sql")] = $encryptedValue;
  2096. return $aValues;
  2097. }
  2098. }
  2099. // Wiki formatting - experimental
  2100. //
  2101. // [[<objClass>:<objName>]]
  2102. // Example: [[Server:db1.tnut.com]]
  2103. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  2104. /**
  2105. * Map a text column (size > ?) to an attribute
  2106. *
  2107. * @package iTopORM
  2108. */
  2109. class AttributeText extends AttributeString
  2110. {
  2111. public function GetEditClass() {return ($this->GetFormat() == 'text') ? 'Text' : "HTML";}
  2112. protected function GetSQLCol($bFullSpec = false) {return "TEXT";}
  2113. public function GetSQLColumns($bFullSpec = false)
  2114. {
  2115. $aColumns = array();
  2116. $aColumns[$this->Get('sql')] = $this->GetSQLCol($bFullSpec);
  2117. if ($this->GetOptional('format', null) != null )
  2118. {
  2119. // Add the extra column only if the property 'format' is specified for the attribute
  2120. $aColumns[$this->Get('sql').'_format'] = "ENUM('text','html')";
  2121. if ($bFullSpec)
  2122. {
  2123. $aColumns[$this->Get('sql').'_format'].= " DEFAULT 'text'"; // default 'text' is for migrating old records
  2124. }
  2125. }
  2126. return $aColumns;
  2127. }
  2128. public function GetSQLExpressions($sPrefix = '')
  2129. {
  2130. if ($sPrefix == '')
  2131. {
  2132. $sPrefix = $this->Get('sql');
  2133. }
  2134. $aColumns = array();
  2135. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2136. $aColumns[''] = $sPrefix;
  2137. if ($this->GetOptional('format', null) != null )
  2138. {
  2139. // Add the extra column only if the property 'format' is specified for the attribute
  2140. $aColumns['_format'] = $sPrefix.'_format';
  2141. }
  2142. return $aColumns;
  2143. }
  2144. public function GetMaxSize()
  2145. {
  2146. // Is there a way to know the current limitation for mysql?
  2147. // See mysql_field_len()
  2148. return 65535;
  2149. }
  2150. static public function RenderWikiHtml($sText, $bWikiOnly = false)
  2151. {
  2152. if (!$bWikiOnly)
  2153. {
  2154. $sPattern = '/'.str_replace('/', '\/', utils::GetConfig()->Get('url_validation_pattern')).'/i';
  2155. if (preg_match_all($sPattern, $sText, $aAllMatches, PREG_SET_ORDER /* important !*/ |PREG_OFFSET_CAPTURE /* important ! */))
  2156. {
  2157. $aUrls = array();
  2158. $i = count($aAllMatches);
  2159. // Replace the URLs by an actual hyperlink <a href="...">...</a>
  2160. // Let's do it backwards so that the initial positions are not modified by the replacement
  2161. // This works if the matches are captured: in the order they occur in the string AND
  2162. // with their offset (i.e. position) inside the string
  2163. while($i > 0)
  2164. {
  2165. $i--;
  2166. $sUrl = $aAllMatches[$i][0][0]; // String corresponding to the main pattern
  2167. $iPos = $aAllMatches[$i][0][1]; // Position of the main pattern
  2168. $sText = substr_replace($sText, "<a href=\"$sUrl\">$sUrl</a>", $iPos, strlen($sUrl));
  2169. }
  2170. }
  2171. }
  2172. if (preg_match_all(WIKI_OBJECT_REGEXP, $sText, $aAllMatches, PREG_SET_ORDER))
  2173. {
  2174. foreach($aAllMatches as $iPos => $aMatches)
  2175. {
  2176. $sClass = trim($aMatches[1]);
  2177. $sName = trim($aMatches[2]);
  2178. if (MetaModel::IsValidClass($sClass))
  2179. {
  2180. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  2181. if (is_object($oObj))
  2182. {
  2183. // Propose a std link to the object
  2184. $sText = str_replace($aMatches[0], $oObj->GetHyperlink(), $sText);
  2185. }
  2186. else
  2187. {
  2188. // Propose a std link to the object
  2189. $sClassLabel = MetaModel::GetName($sClass);
  2190. $sText = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sText);
  2191. // Later: propose a link to create a new object
  2192. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  2193. //$sText = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="'.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sText);
  2194. }
  2195. }
  2196. }
  2197. }
  2198. return $sText;
  2199. }
  2200. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2201. {
  2202. $aStyles = array();
  2203. if ($this->GetWidth() != '')
  2204. {
  2205. $aStyles[] = 'width:'.$this->GetWidth();
  2206. }
  2207. if ($this->GetHeight() != '')
  2208. {
  2209. $aStyles[] = 'height:'.$this->GetHeight();
  2210. }
  2211. $sStyle = '';
  2212. if (count($aStyles) > 0)
  2213. {
  2214. $aStyles[] = 'overflow:auto';
  2215. $sStyle = 'style="'.implode(';', $aStyles).'"';
  2216. }
  2217. if ($this->GetFormat() == 'text')
  2218. {
  2219. $sValue = parent::GetAsHTML($sValue, $oHostObject, $bLocalize);
  2220. $sValue = self::RenderWikiHtml($sValue);
  2221. return "<div $sStyle>".str_replace("\n", "<br>\n", $sValue).'</div>';
  2222. }
  2223. else
  2224. {
  2225. $sValue = self::RenderWikiHtml($sValue, true /* wiki only */);
  2226. return "<div class=\"HTML\" $sStyle>".InlineImage::FixUrls($sValue).'</div>';
  2227. }
  2228. }
  2229. public function GetEditValue($sValue, $oHostObj = null)
  2230. {
  2231. if ($this->GetFormat() == 'text')
  2232. {
  2233. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  2234. {
  2235. foreach($aAllMatches as $iPos => $aMatches)
  2236. {
  2237. $sClass = $aMatches[1];
  2238. $sName = $aMatches[2];
  2239. if (MetaModel::IsValidClass($sClass))
  2240. {
  2241. $sClassLabel = MetaModel::GetName($sClass);
  2242. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  2243. }
  2244. }
  2245. }
  2246. }
  2247. else
  2248. {
  2249. $sValue = str_replace('&', '&amp;', $sValue);
  2250. }
  2251. return $sValue;
  2252. }
  2253. /**
  2254. * For fields containing a potential markup, return the value without this markup
  2255. * @return string
  2256. */
  2257. public function GetAsPlainText($sValue, $oHostObj = null)
  2258. {
  2259. if ($this->GetFormat() == 'html')
  2260. {
  2261. return (string) utils::HtmlToText($this->GetEditValue($sValue, $oHostObj));
  2262. }
  2263. else
  2264. {
  2265. return parent::GetAsPlainText($sValue, $oHostObj);
  2266. }
  2267. }
  2268. public function MakeRealValue($proposedValue, $oHostObj)
  2269. {
  2270. $sValue = $proposedValue;
  2271. switch ($this->GetFormat())
  2272. {
  2273. case 'html':
  2274. if (($sValue !== null) && ($sValue !== ''))
  2275. {
  2276. $sValue = HTMLSanitizer::Sanitize($sValue);
  2277. }
  2278. break;
  2279. case 'text':
  2280. default:
  2281. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  2282. {
  2283. foreach($aAllMatches as $iPos => $aMatches)
  2284. {
  2285. $sClassLabel = $aMatches[1];
  2286. $sName = $aMatches[2];
  2287. if (!MetaModel::IsValidClass($sClassLabel))
  2288. {
  2289. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  2290. if ($sClass)
  2291. {
  2292. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  2293. }
  2294. }
  2295. }
  2296. }
  2297. }
  2298. return $sValue;
  2299. }
  2300. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2301. {
  2302. return Str::pure2xml($value);
  2303. }
  2304. public function GetWidth()
  2305. {
  2306. return $this->GetOptional('width', '');
  2307. }
  2308. public function GetHeight()
  2309. {
  2310. return $this->GetOptional('height', '');
  2311. }
  2312. static public function GetFormFieldClass()
  2313. {
  2314. return '\\Combodo\\iTop\\Form\\Field\\TextAreaField';
  2315. }
  2316. public function MakeFormField(DBObject $oObject, $oFormField = null)
  2317. {
  2318. if ($oFormField === null)
  2319. {
  2320. $sFormFieldClass = static::GetFormFieldClass();
  2321. $oFormField = new $sFormFieldClass($this->GetCode(), null, $oObject);
  2322. $oFormField->SetFormat($this->GetFormat());
  2323. }
  2324. parent::MakeFormField($oObject, $oFormField);
  2325. return $oFormField;
  2326. }
  2327. /**
  2328. * The actual formatting of the field: either text (=plain text) or html (= text with HTML markup)
  2329. * @return string
  2330. */
  2331. public function GetFormat()
  2332. {
  2333. return $this->GetOptional('format', 'text');
  2334. }
  2335. /**
  2336. * Read the value from the row returned by the SQL query and transorms it to the appropriate
  2337. * internal format (either text or html)
  2338. * @see AttributeDBFieldVoid::FromSQLToValue()
  2339. */
  2340. public function FromSQLToValue($aCols, $sPrefix = '')
  2341. {
  2342. $value = $aCols[$sPrefix.''];
  2343. if ($this->GetOptional('format', null) != null )
  2344. {
  2345. // Read from the extra column only if the property 'format' is specified for the attribute
  2346. $sFormat = $aCols[$sPrefix.'_format'];
  2347. }
  2348. else
  2349. {
  2350. $sFormat = $this->GetFormat();
  2351. }
  2352. switch($sFormat)
  2353. {
  2354. case 'text':
  2355. if ($this->GetFormat() == 'html')
  2356. {
  2357. $value = utils::TextToHtml($value);
  2358. }
  2359. break;
  2360. case 'html':
  2361. if ($this->GetFormat() == 'text')
  2362. {
  2363. $value = utils::HtmlToText($value);
  2364. }
  2365. else
  2366. {
  2367. $value = InlineImage::FixUrls((string)$value);
  2368. }
  2369. break;
  2370. default:
  2371. // unknown format ??
  2372. }
  2373. return $value;
  2374. }
  2375. public function GetSQLValues($value)
  2376. {
  2377. $aValues = array();
  2378. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  2379. if ($this->GetOptional('format', null) != null )
  2380. {
  2381. // Add the extra column only if the property 'format' is specified for the attribute
  2382. $aValues[$this->Get("sql").'_format'] = $this->GetFormat();
  2383. }
  2384. return $aValues;
  2385. }
  2386. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  2387. {
  2388. switch($this->GetFormat())
  2389. {
  2390. case 'html':
  2391. if ($bConvertToPlainText)
  2392. {
  2393. $sValue = utils::HtmlToText((string)$sValue);
  2394. }
  2395. $sFrom = array("\r\n", $sTextQualifier);
  2396. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  2397. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  2398. return $sTextQualifier.$sEscaped.$sTextQualifier;
  2399. break;
  2400. case 'text':
  2401. default:
  2402. return parent::GetAsCSV($sValue, $sSeparator, $sTextQualifier, $oHostObject, $bLocalize, $bConvertToPlainText);
  2403. }
  2404. }
  2405. }
  2406. /**
  2407. * Map a log to an attribute
  2408. *
  2409. * @package iTopORM
  2410. */
  2411. class AttributeLongText extends AttributeText
  2412. {
  2413. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  2414. public function GetMaxSize()
  2415. {
  2416. // Is there a way to know the current limitation for mysql?
  2417. // See mysql_field_len()
  2418. return 65535*1024; // Limited... still 64 Mb!
  2419. }
  2420. }
  2421. /**
  2422. * An attibute that stores a case log (i.e journal)
  2423. *
  2424. * @package iTopORM
  2425. */
  2426. class AttributeCaseLog extends AttributeLongText
  2427. {
  2428. public function GetNullValue()
  2429. {
  2430. return '';
  2431. }
  2432. public function IsNull($proposedValue)
  2433. {
  2434. if (!($proposedValue instanceof ormCaseLog))
  2435. {
  2436. return ($proposedValue == '');
  2437. }
  2438. return ($proposedValue->GetText() == '');
  2439. }
  2440. public function ScalarToSQL($value)
  2441. {
  2442. if (!is_string($value) && !is_null($value))
  2443. {
  2444. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  2445. }
  2446. return $value;
  2447. }
  2448. public function GetEditClass() {return "CaseLog";}
  2449. public function GetEditValue($sValue, $oHostObj = null)
  2450. {
  2451. if (!($sValue instanceOf ormCaseLog))
  2452. {
  2453. return '';
  2454. }
  2455. return $sValue->GetModifiedEntry();
  2456. }
  2457. /**
  2458. * For fields containing a potential markup, return the value without this markup
  2459. * @return string
  2460. */
  2461. public function GetAsPlainText($value, $oHostObj = null)
  2462. {
  2463. $value = $oObj->Get($sAttCode);
  2464. if ($value instanceOf ormCaseLog)
  2465. {
  2466. return $value->GetAsPlainText();
  2467. }
  2468. else
  2469. {
  2470. return (string) $value;
  2471. }
  2472. }
  2473. public function GetDefaultValue(DBObject $oHostObject = null) {return new ormCaseLog();}
  2474. public function Equals($val1, $val2) {return ($val1->GetText() == $val2->GetText());}
  2475. // Facilitate things: allow the user to Set the value from a string
  2476. public function MakeRealValue($proposedValue, $oHostObj)
  2477. {
  2478. if ($proposedValue instanceof ormCaseLog)
  2479. {
  2480. // Passthrough
  2481. $ret = $proposedValue;
  2482. }
  2483. else
  2484. {
  2485. // Append the new value if an instance of the object is supplied
  2486. //
  2487. $oPreviousLog = null;
  2488. if ($oHostObj != null)
  2489. {
  2490. $oPreviousLog = $oHostObj->Get($this->GetCode());
  2491. if (!is_object($oPreviousLog))
  2492. {
  2493. $oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
  2494. }
  2495. }
  2496. if (is_object($oPreviousLog))
  2497. {
  2498. $oCaseLog = clone($oPreviousLog);
  2499. }
  2500. else
  2501. {
  2502. $oCaseLog = new ormCaseLog();
  2503. }
  2504. if ($proposedValue instanceof stdClass)
  2505. {
  2506. $oCaseLog->AddLogEntryFromJSON($proposedValue);
  2507. }
  2508. else
  2509. {
  2510. if (strlen($proposedValue) > 0)
  2511. {
  2512. $oCaseLog->AddLogEntry($proposedValue);
  2513. }
  2514. }
  2515. $ret = $oCaseLog;
  2516. }
  2517. return $ret;
  2518. }
  2519. public function GetSQLExpressions($sPrefix = '')
  2520. {
  2521. if ($sPrefix == '')
  2522. {
  2523. $sPrefix = $this->Get('sql');
  2524. }
  2525. $aColumns = array();
  2526. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2527. $aColumns[''] = $sPrefix;
  2528. $aColumns['_index'] = $sPrefix.'_index';
  2529. return $aColumns;
  2530. }
  2531. public function FromSQLToValue($aCols, $sPrefix = '')
  2532. {
  2533. if (!array_key_exists($sPrefix, $aCols))
  2534. {
  2535. $sAvailable = implode(', ', array_keys($aCols));
  2536. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2537. }
  2538. $sLog = $aCols[$sPrefix];
  2539. if (isset($aCols[$sPrefix.'_index']))
  2540. {
  2541. $sIndex = $aCols[$sPrefix.'_index'];
  2542. }
  2543. else
  2544. {
  2545. // For backward compatibility, allow the current state to be: 1 log, no index
  2546. $sIndex = '';
  2547. }
  2548. if (strlen($sIndex) > 0)
  2549. {
  2550. $aIndex = unserialize($sIndex);
  2551. $value = new ormCaseLog($sLog, $aIndex);
  2552. }
  2553. else
  2554. {
  2555. $value = new ormCaseLog($sLog);
  2556. }
  2557. return $value;
  2558. }
  2559. public function GetSQLValues($value)
  2560. {
  2561. if (!($value instanceOf ormCaseLog))
  2562. {
  2563. $value = new ormCaseLog('');
  2564. }
  2565. $aValues = array();
  2566. $aValues[$this->GetCode()] = $value->GetText();
  2567. $aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
  2568. return $aValues;
  2569. }
  2570. public function GetSQLColumns($bFullSpec = false)
  2571. {
  2572. $aColumns = array();
  2573. $aColumns[$this->GetCode()] = 'LONGTEXT'; // 2^32 (4 Gb)
  2574. $aColumns[$this->GetCode().'_index'] = 'BLOB';
  2575. return $aColumns;
  2576. }
  2577. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  2578. {
  2579. if ($value instanceOf ormCaseLog)
  2580. {
  2581. $sContent = $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
  2582. }
  2583. else
  2584. {
  2585. $sContent = '';
  2586. }
  2587. $aStyles = array();
  2588. if ($this->GetWidth() != '')
  2589. {
  2590. $aStyles[] = 'width:'.$this->GetWidth();
  2591. }
  2592. if ($this->GetHeight() != '')
  2593. {
  2594. $aStyles[] = 'height:'.$this->GetHeight();
  2595. }
  2596. $sStyle = '';
  2597. if (count($aStyles) > 0)
  2598. {
  2599. $sStyle = 'style="'.implode(';', $aStyles).'"';
  2600. }
  2601. return "<div class=\"caselog\" $sStyle>".$sContent.'</div>'; }
  2602. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  2603. {
  2604. if ($value instanceOf ormCaseLog)
  2605. {
  2606. return parent::GetAsCSV($value->GetText($bConvertToPlainText), $sSeparator, $sTextQualifier, $oHostObject, $bLocalize, $bConvertToPlainText);
  2607. }
  2608. else
  2609. {
  2610. return '';
  2611. }
  2612. }
  2613. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2614. {
  2615. if ($value instanceOf ormCaseLog)
  2616. {
  2617. return parent::GetAsXML($value->GetText(), $oHostObject, $bLocalize);
  2618. }
  2619. else
  2620. {
  2621. return '';
  2622. }
  2623. }
  2624. /**
  2625. * List the available verbs for 'GetForTemplate'
  2626. */
  2627. public function EnumTemplateVerbs()
  2628. {
  2629. return array(
  2630. '' => 'Plain text representation of all the log entries',
  2631. 'head' => 'Plain text representation of the latest entry',
  2632. 'head_html' => 'HTML representation of the latest entry',
  2633. 'html' => 'HTML representation of all the log entries',
  2634. );
  2635. }
  2636. /**
  2637. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  2638. * @param $value mixed The current value of the field
  2639. * @param $sVerb string The verb specifying the representation of the value
  2640. * @param $oHostObject DBObject The object
  2641. * @param $bLocalize bool Whether or not to localize the value
  2642. */
  2643. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  2644. {
  2645. switch($sVerb)
  2646. {
  2647. case '':
  2648. return $value->GetText(true);
  2649. case 'head':
  2650. return $value->GetLatestEntry('text');
  2651. case 'head_html':
  2652. return $value->GetLatestEntry('html');
  2653. case 'html':
  2654. return $value->GetAsEmailHtml();
  2655. default:
  2656. throw new Exception("Unknown verb '$sVerb' for attribute ".$this->GetCode().' in class '.get_class($oHostObject));
  2657. }
  2658. }
  2659. /**
  2660. * Helper to get a value that will be JSON encoded
  2661. * The operation is the opposite to FromJSONToValue
  2662. */
  2663. public function GetForJSON($value)
  2664. {
  2665. return $value->GetForJSON();
  2666. }
  2667. /**
  2668. * Helper to form a value, given JSON decoded data
  2669. * The operation is the opposite to GetForJSON
  2670. */
  2671. public function FromJSONToValue($json)
  2672. {
  2673. if (is_string($json))
  2674. {
  2675. // Will be correctly handled in MakeRealValue
  2676. $ret = $json;
  2677. }
  2678. else
  2679. {
  2680. if (isset($json->add_item))
  2681. {
  2682. // Will be correctly handled in MakeRealValue
  2683. $ret = $json->add_item;
  2684. if (!isset($ret->message))
  2685. {
  2686. throw new Exception("Missing mandatory entry: 'message'");
  2687. }
  2688. }
  2689. else
  2690. {
  2691. $ret = ormCaseLog::FromJSON($json);
  2692. }
  2693. }
  2694. return $ret;
  2695. }
  2696. public function Fingerprint($value)
  2697. {
  2698. $sFingerprint = '';
  2699. if ($value instanceOf ormCaseLog)
  2700. {
  2701. $sFingerprint = $value->GetText();
  2702. }
  2703. return $sFingerprint;
  2704. }
  2705. /**
  2706. * The actual formatting of the text: either text (=plain text) or html (= text with HTML markup)
  2707. * @return string
  2708. */
  2709. public function GetFormat()
  2710. {
  2711. return $this->GetOptional('format', 'html'); // default format for case logs is now HTML
  2712. }
  2713. static public function GetFormFieldClass()
  2714. {
  2715. return '\\Combodo\\iTop\\Form\\Field\\CaseLogField';
  2716. }
  2717. public function MakeFormField(DBObject $oObject, $oFormField = null)
  2718. {
  2719. // First we call the parent so the field is build
  2720. $oFormField = parent::MakeFormField($oObject, $oFormField);
  2721. // Then only we set the value
  2722. $oFormField->SetCurrentValue($this->GetEditValue($oObject->Get($this->GetCode())));
  2723. // And we set the entries
  2724. $oFormField->SetEntries($oObject->Get($this->GetCode())->GetAsArray());
  2725. return $oFormField;
  2726. }
  2727. }
  2728. /**
  2729. * Map a text column (size > ?), containing HTML code, to an attribute
  2730. *
  2731. * @package iTopORM
  2732. */
  2733. class AttributeHTML extends AttributeLongText
  2734. {
  2735. public function GetSQLColumns($bFullSpec = false)
  2736. {
  2737. $aColumns = array();
  2738. $aColumns[$this->Get('sql')] = $this->GetSQLCol();
  2739. if ($this->GetOptional('format', null) != null )
  2740. {
  2741. // Add the extra column only if the property 'format' is specified for the attribute
  2742. $aColumns[$this->Get('sql').'_format'] = "ENUM('text','html')";
  2743. if ($bFullSpec)
  2744. {
  2745. $aColumns[$this->Get('sql').'_format'].= " DEFAULT 'html'"; // default 'html' is for migrating old records
  2746. }
  2747. }
  2748. return $aColumns;
  2749. }
  2750. /**
  2751. * The actual formatting of the text: either text (=plain text) or html (= text with HTML markup)
  2752. * @return string
  2753. */
  2754. public function GetFormat()
  2755. {
  2756. return $this->GetOptional('format', 'html'); // Defaults to HTML
  2757. }
  2758. }
  2759. /**
  2760. * Specialization of a string: email
  2761. *
  2762. * @package iTopORM
  2763. */
  2764. class AttributeEmailAddress extends AttributeString
  2765. {
  2766. public function GetValidationPattern()
  2767. {
  2768. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('email_validation_pattern').'$');
  2769. }
  2770. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2771. {
  2772. if (empty($sValue)) return '';
  2773. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  2774. }
  2775. }
  2776. /**
  2777. * Specialization of a string: IP address
  2778. *
  2779. * @package iTopORM
  2780. */
  2781. class AttributeIPAddress extends AttributeString
  2782. {
  2783. public function GetValidationPattern()
  2784. {
  2785. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  2786. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  2787. }
  2788. public function GetOrderBySQLExpressions($sClassAlias)
  2789. {
  2790. // Note: This is the responsibility of this function to place backticks around column aliases
  2791. return array('INET_ATON(`'.$sClassAlias.$this->GetCode().'`)');
  2792. }
  2793. }
  2794. /**
  2795. * Specialization of a string: OQL expression
  2796. *
  2797. * @package iTopORM
  2798. */
  2799. class AttributeOQL extends AttributeText
  2800. {
  2801. public function GetEditClass() {return "OQLExpression";}
  2802. }
  2803. /**
  2804. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2805. *
  2806. * @package iTopORM
  2807. */
  2808. class AttributeTemplateString extends AttributeString
  2809. {
  2810. }
  2811. /**
  2812. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2813. *
  2814. * @package iTopORM
  2815. */
  2816. class AttributeTemplateText extends AttributeText
  2817. {
  2818. }
  2819. /**
  2820. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  2821. *
  2822. * @package iTopORM
  2823. */
  2824. class AttributeTemplateHTML extends AttributeText
  2825. {
  2826. public function GetSQLColumns($bFullSpec = false)
  2827. {
  2828. $aColumns = array();
  2829. $aColumns[$this->Get('sql')] = $this->GetSQLCol();
  2830. if ($this->GetOptional('format', null) != null )
  2831. {
  2832. // Add the extra column only if the property 'format' is specified for the attribute
  2833. $aColumns[$this->Get('sql').'_format'] = "ENUM('text','html')";
  2834. if ($bFullSpec)
  2835. {
  2836. $aColumns[$this->Get('sql').'_format'].= " DEFAULT 'html'"; // default 'html' is for migrating old records
  2837. }
  2838. }
  2839. return $aColumns;
  2840. }
  2841. /**
  2842. * The actual formatting of the text: either text (=plain text) or html (= text with HTML markup)
  2843. * @return string
  2844. */
  2845. public function GetFormat()
  2846. {
  2847. return $this->GetOptional('format', 'html'); // Defaults to HTML
  2848. }
  2849. }
  2850. /**
  2851. * Map a enum column to an attribute
  2852. *
  2853. * @package iTopORM
  2854. */
  2855. class AttributeEnum extends AttributeString
  2856. {
  2857. static public function ListExpectedParams()
  2858. {
  2859. return parent::ListExpectedParams();
  2860. //return array_merge(parent::ListExpectedParams(), array());
  2861. }
  2862. public function GetEditClass() {return "String";}
  2863. protected function GetSQLCol($bFullSpec = false)
  2864. {
  2865. $oValDef = $this->GetValuesDef();
  2866. if ($oValDef)
  2867. {
  2868. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  2869. }
  2870. else
  2871. {
  2872. $aValues = array();
  2873. }
  2874. if (count($aValues) > 0)
  2875. {
  2876. // The syntax used here do matters
  2877. // In particular, I had to remove unnecessary spaces to
  2878. // make sure that this string will match the field type returned by the DB
  2879. // (used to perform a comparison between the current DB format and the data model)
  2880. return "ENUM(".implode(",", $aValues).")".($bFullSpec ? $this->GetSQLColSpec() : '');
  2881. }
  2882. else
  2883. {
  2884. return "VARCHAR(255)".($bFullSpec ? " DEFAULT ''" : ""); // ENUM() is not an allowed syntax!
  2885. }
  2886. }
  2887. protected function GetSQLColSpec()
  2888. {
  2889. $default = $this->ScalarToSQL($this->GetDefaultValue());
  2890. if (is_null($default))
  2891. {
  2892. $sRet = '';
  2893. }
  2894. else
  2895. {
  2896. // ENUMs values are strings so the default value must be a string as well,
  2897. // otherwise MySQL interprets the number as the zero-based index of the value in the list (i.e. the nth value in the list)
  2898. $sRet = " DEFAULT ".CMDBSource::Quote($default);
  2899. }
  2900. return $sRet;
  2901. }
  2902. public function ScalarToSQL($value)
  2903. {
  2904. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  2905. // but that wasn't working for enums, because '' is NOT one of the allowed values
  2906. // that's why a null value must be forced to a real null
  2907. $value = parent::ScalarToSQL($value);
  2908. if ($this->IsNull($value))
  2909. {
  2910. return null;
  2911. }
  2912. else
  2913. {
  2914. return $value;
  2915. }
  2916. }
  2917. public function RequiresIndex()
  2918. {
  2919. return false;
  2920. }
  2921. public function GetBasicFilterOperators()
  2922. {
  2923. return parent::GetBasicFilterOperators();
  2924. }
  2925. public function GetBasicFilterLooseOperator()
  2926. {
  2927. return '=';
  2928. }
  2929. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2930. {
  2931. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2932. }
  2933. public function GetValueLabel($sValue)
  2934. {
  2935. if (is_null($sValue))
  2936. {
  2937. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2938. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  2939. }
  2940. else
  2941. {
  2942. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, null, true /*user lang*/);
  2943. if (is_null($sLabel))
  2944. {
  2945. $sDefault = str_replace('_', ' ', $sValue);
  2946. // Browse the hierarchy again, accepting default (english) translations
  2947. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/Value:'.$sValue, $sDefault, false);
  2948. }
  2949. }
  2950. return $sLabel;
  2951. }
  2952. public function GetValueDescription($sValue)
  2953. {
  2954. if (is_null($sValue))
  2955. {
  2956. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  2957. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', Dict::S('Enum:Undefined'));
  2958. }
  2959. else
  2960. {
  2961. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', '', true /* user language only */);
  2962. if (strlen($sDescription) == 0)
  2963. {
  2964. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  2965. if ($sParentClass)
  2966. {
  2967. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  2968. {
  2969. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  2970. $sDescription = $oAttDef->GetValueDescription($sValue);
  2971. }
  2972. }
  2973. }
  2974. }
  2975. return $sDescription;
  2976. }
  2977. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  2978. {
  2979. if ($bLocalize)
  2980. {
  2981. $sLabel = $this->GetValueLabel($sValue);
  2982. $sDescription = $this->GetValueDescription($sValue);
  2983. // later, we could imagine a detailed description in the title
  2984. $sRes = "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  2985. }
  2986. else
  2987. {
  2988. $sRes = parent::GetAsHtml($sValue, $oHostObject, $bLocalize);
  2989. }
  2990. return $sRes;
  2991. }
  2992. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  2993. {
  2994. if (is_null($value))
  2995. {
  2996. $sFinalValue = '';
  2997. }
  2998. elseif ($bLocalize)
  2999. {
  3000. $sFinalValue = $this->GetValueLabel($value);
  3001. }
  3002. else
  3003. {
  3004. $sFinalValue = $value;
  3005. }
  3006. $sRes = parent::GetAsXML($sFinalValue, $oHostObject, $bLocalize);
  3007. return $sRes;
  3008. }
  3009. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  3010. {
  3011. if (is_null($sValue))
  3012. {
  3013. $sFinalValue = '';
  3014. }
  3015. elseif ($bLocalize)
  3016. {
  3017. $sFinalValue = $this->GetValueLabel($sValue);
  3018. }
  3019. else
  3020. {
  3021. $sFinalValue = $sValue;
  3022. }
  3023. $sRes = parent::GetAsCSV($sFinalValue, $sSeparator, $sTextQualifier, $oHostObject, $bLocalize);
  3024. return $sRes;
  3025. }
  3026. static public function GetFormFieldClass()
  3027. {
  3028. return '\\Combodo\\iTop\\Form\\Field\\SelectField';
  3029. }
  3030. public function MakeFormField(DBObject $oObject, $oFormField = null)
  3031. {
  3032. if ($oFormField === null)
  3033. {
  3034. // TODO : We should check $this->Get('display_style') and create a Radio / Select / ... regarding its value
  3035. $sFormFieldClass = static::GetFormFieldClass();
  3036. $oFormField = new $sFormFieldClass($this->GetCode());
  3037. }
  3038. $oFormField->SetChoices($this->GetAllowedValues($oObject->ToArgsForQuery()));
  3039. parent::MakeFormField($oObject, $oFormField);
  3040. return $oFormField;
  3041. }
  3042. public function GetEditValue($sValue, $oHostObj = null)
  3043. {
  3044. if (is_null($sValue))
  3045. {
  3046. return '';
  3047. }
  3048. else
  3049. {
  3050. return $this->GetValueLabel($sValue);
  3051. }
  3052. }
  3053. /**
  3054. * Helper to get a value that will be JSON encoded
  3055. * The operation is the opposite to FromJSONToValue
  3056. */
  3057. public function GetForJSON($value)
  3058. {
  3059. return $value;
  3060. }
  3061. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3062. {
  3063. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  3064. if (is_null($aRawValues)) return null;
  3065. $aLocalizedValues = array();
  3066. foreach ($aRawValues as $sKey => $sValue)
  3067. {
  3068. $aLocalizedValues[$sKey] = Str::pure2html($this->GetValueLabel($sKey));
  3069. }
  3070. return $aLocalizedValues;
  3071. }
  3072. /**
  3073. * An enum can be localized
  3074. */
  3075. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  3076. {
  3077. if ($bLocalizedValue)
  3078. {
  3079. // Lookup for the value matching the input
  3080. //
  3081. $sFoundValue = null;
  3082. $aRawValues = parent::GetAllowedValues();
  3083. if (!is_null($aRawValues))
  3084. {
  3085. foreach ($aRawValues as $sKey => $sValue)
  3086. {
  3087. $sRefValue = $this->GetValueLabel($sKey);
  3088. if ($sProposedValue == $sRefValue)
  3089. {
  3090. $sFoundValue = $sKey;
  3091. break;
  3092. }
  3093. }
  3094. }
  3095. if (is_null($sFoundValue))
  3096. {
  3097. return null;
  3098. }
  3099. return $this->MakeRealValue($sFoundValue, null);
  3100. }
  3101. else
  3102. {
  3103. return parent::MakeValueFromString($sProposedValue, $bLocalizedValue, $sSepItem, $sSepAttribute, $sSepValue, $sAttributeQualifier);
  3104. }
  3105. }
  3106. /**
  3107. * Processes the input value to align it with the values supported
  3108. * by this type of attribute. In this case: turns empty strings into nulls
  3109. * @param mixed $proposedValue The value to be set for the attribute
  3110. * @return mixed The actual value that will be set
  3111. */
  3112. public function MakeRealValue($proposedValue, $oHostObj)
  3113. {
  3114. if ($proposedValue == '') return null;
  3115. return parent::MakeRealValue($proposedValue, $oHostObj);
  3116. }
  3117. public function GetOrderByHint()
  3118. {
  3119. $aValues = $this->GetAllowedValues();
  3120. return Dict::Format('UI:OrderByHint_Values', implode(', ', $aValues));
  3121. }
  3122. }
  3123. /**
  3124. * A meta enum is an aggregation of enum from subclasses into an enum of a base class
  3125. * It has been designed is to cope with the fact that statuses must be defined in leaf classes, while it makes sense to
  3126. * have a superstatus available on the root classe(s)
  3127. *
  3128. * @package iTopORM
  3129. */
  3130. class AttributeMetaEnum extends AttributeEnum
  3131. {
  3132. static public function ListExpectedParams()
  3133. {
  3134. return array('allowed_values', 'sql', 'default_value', 'mapping');
  3135. }
  3136. public function IsNullAllowed()
  3137. {
  3138. return false; // Well... this actually depends on the mapping
  3139. }
  3140. public function IsWritable()
  3141. {
  3142. return false;
  3143. }
  3144. public function RequiresIndex()
  3145. {
  3146. return true;
  3147. }
  3148. public function GetPrerequisiteAttributes($sClass = null)
  3149. {
  3150. if (is_null($sClass))
  3151. {
  3152. $sClass = $this->GetHostClass();
  3153. }
  3154. $aMappingData = $this->GetMapRule($sClass);
  3155. if ($aMappingData == null)
  3156. {
  3157. $aRet = array();
  3158. }
  3159. else
  3160. {
  3161. $aRet = array($aMappingData['attcode']);
  3162. }
  3163. return $aRet;
  3164. }
  3165. /**
  3166. * Overload the standard so as to leave the data unsorted
  3167. *
  3168. * @param array $aArgs
  3169. * @param string $sContains
  3170. * @return array|null
  3171. */
  3172. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3173. {
  3174. $oValSetDef = $this->GetValuesDef();
  3175. if (!$oValSetDef) return null;
  3176. $aRawValues = $oValSetDef->GetValueList();
  3177. if (is_null($aRawValues)) return null;
  3178. $aLocalizedValues = array();
  3179. foreach ($aRawValues as $sKey => $sValue)
  3180. {
  3181. $aLocalizedValues[$sKey] = Str::pure2html($this->GetValueLabel($sKey));
  3182. }
  3183. return $aLocalizedValues;
  3184. }
  3185. /**
  3186. * Returns the meta value for the given object.
  3187. * See also MetaModel::RebuildMetaEnums() that must be maintained when MapValue changes
  3188. *
  3189. * @param $oObject
  3190. * @return mixed
  3191. * @throws Exception
  3192. */
  3193. public function MapValue($oObject)
  3194. {
  3195. $aMappingData = $this->GetMapRule(get_class($oObject));
  3196. if ($aMappingData == null)
  3197. {
  3198. $sRet = $this->GetDefaultValue();
  3199. }
  3200. else
  3201. {
  3202. $sAttCode = $aMappingData['attcode'];
  3203. $value = $oObject->Get($sAttCode);
  3204. if (array_key_exists($value, $aMappingData['values']))
  3205. {
  3206. $sRet = $aMappingData['values'][$value];
  3207. }
  3208. elseif ($this->GetDefaultValue() != '')
  3209. {
  3210. $sRet = $this->GetDefaultValue();
  3211. }
  3212. else
  3213. {
  3214. 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());
  3215. }
  3216. }
  3217. return $sRet;
  3218. }
  3219. public function GetMapRule($sClass)
  3220. {
  3221. $aMappings = $this->Get('mapping');
  3222. if (array_key_exists($sClass, $aMappings))
  3223. {
  3224. $aMappingData = $aMappings[$sClass];
  3225. }
  3226. else
  3227. {
  3228. $sParent = MetaModel::GetParentClass($sClass);
  3229. if (is_null($sParent))
  3230. {
  3231. $aMappingData = null;
  3232. }
  3233. else
  3234. {
  3235. $aMappingData = $this->GetMapRule($sParent);
  3236. }
  3237. }
  3238. return $aMappingData;
  3239. }
  3240. }
  3241. /**
  3242. * Map a date+time column to an attribute
  3243. *
  3244. * @package iTopORM
  3245. */
  3246. class AttributeDateTime extends AttributeDBField
  3247. {
  3248. static $oFormat = null;
  3249. static public function GetFormat()
  3250. {
  3251. if (self::$oFormat == null)
  3252. {
  3253. static::LoadFormatFromConfig();
  3254. }
  3255. return self::$oFormat;
  3256. }
  3257. /**
  3258. * Load the 3 settings: date format, time format and data_time format from the configuration
  3259. */
  3260. protected static function LoadFormatFromConfig()
  3261. {
  3262. $aFormats = MetaModel::GetConfig()->Get('date_and_time_format');
  3263. $sLang = Dict::GetUserLanguage();
  3264. $sDateFormat = isset($aFormats[$sLang]['date']) ? $aFormats[$sLang]['date'] : (isset($aFormats['default']['date']) ? $aFormats['default']['date'] : 'Y-m-d');
  3265. $sTimeFormat = isset($aFormats[$sLang]['time']) ? $aFormats[$sLang]['time'] : (isset($aFormats['default']['time']) ? $aFormats['default']['time'] : 'H:i:s');
  3266. $sDateAndTimeFormat = isset($aFormats[$sLang]['date_time']) ? $aFormats[$sLang]['date_time'] : (isset($aFormats['default']['date_time']) ? $aFormats['default']['date_time'] : '$date $time');
  3267. $sFullFormat = str_replace(array('$date', '$time'), array($sDateFormat, $sTimeFormat), $sDateAndTimeFormat);
  3268. self::SetFormat(new DateTimeFormat($sFullFormat));
  3269. AttributeDate::SetFormat(new DateTimeFormat($sDateFormat));
  3270. }
  3271. /**
  3272. * Returns the format string used for the date & time stored in memory
  3273. * @return string
  3274. */
  3275. static public function GetInternalFormat()
  3276. {
  3277. return 'Y-m-d H:i:s';
  3278. }
  3279. /**
  3280. * Returns the format string used for the date & time written to MySQL
  3281. * @return string
  3282. */
  3283. static public function GetSQLFormat()
  3284. {
  3285. return 'Y-m-d H:i:s';
  3286. }
  3287. static public function SetFormat(DateTimeFormat $oDateTimeFormat)
  3288. {
  3289. self::$oFormat = $oDateTimeFormat;
  3290. }
  3291. static public function GetSQLTimeFormat()
  3292. {
  3293. return 'H:i:s';
  3294. }
  3295. /**
  3296. * Parses a search string coming from user input
  3297. * @param string $sSearchString
  3298. * @return string
  3299. */
  3300. public function ParseSearchString($sSearchString)
  3301. {
  3302. try
  3303. {
  3304. $oDateTime = $this->GetFormat()->Parse($sSearchString);
  3305. $sSearchString = $oDateTime->format($this->GetInternalFormat());
  3306. }
  3307. catch(Exception $e)
  3308. {
  3309. $sFormatString = '!'.(string)AttributeDate::GetFormat(); // BEWARE: ! is needed to set non-parsed fields to zero !!!
  3310. $oDateTime = DateTime::createFromFormat($sFormatString, $sSearchString);
  3311. if ($oDateTime !== false)
  3312. {
  3313. $sSearchString = $oDateTime->format($this->GetInternalFormat());
  3314. }
  3315. }
  3316. return $sSearchString;
  3317. }
  3318. static public function GetFormFieldClass()
  3319. {
  3320. return '\\Combodo\\iTop\\Form\\Field\\DateTimeField';
  3321. }
  3322. /**
  3323. * Override to specify Field class
  3324. *
  3325. * 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.
  3326. */
  3327. public function MakeFormField(DBObject $oObject, $oFormField = null)
  3328. {
  3329. if ($oFormField === null)
  3330. {
  3331. $sFormFieldClass = static::GetFormFieldClass();
  3332. $oFormField = new $sFormFieldClass($this->GetCode());
  3333. }
  3334. $oFormField->SetPHPDateTimeFormat((string) $this->GetFormat());
  3335. $oFormField->SetJSDateTimeFormat($this->GetFormat()->ToMomentJS());
  3336. $oFormField = parent::MakeFormField($oObject, $oFormField);
  3337. // After call to the parent as it sets the current value
  3338. $oFormField->SetCurrentValue($this->GetFormat()->Format($oObject->Get($this->GetCode())));
  3339. return $oFormField;
  3340. }
  3341. static public function ListExpectedParams()
  3342. {
  3343. return parent::ListExpectedParams();
  3344. //return array_merge(parent::ListExpectedParams(), array());
  3345. }
  3346. public function GetEditClass() {return "DateTime";}
  3347. public function GetEditValue($sValue, $oHostObj = null)
  3348. {
  3349. return (string)static::GetFormat()->format($sValue);
  3350. }
  3351. public function GetValueLabel($sValue, $oHostObj = null)
  3352. {
  3353. return (string)static::GetFormat()->format($sValue);
  3354. }
  3355. protected function GetSQLCol($bFullSpec = false) {return "DATETIME";}
  3356. public function GetImportColumns()
  3357. {
  3358. // Allow an empty string to be a valid value (synonym for "reset")
  3359. $aColumns = array();
  3360. $aColumns[$this->GetCode()] = 'VARCHAR(19)';
  3361. return $aColumns;
  3362. }
  3363. public static function GetAsUnixSeconds($value)
  3364. {
  3365. $oDeadlineDateTime = new DateTime($value);
  3366. $iUnixSeconds = $oDeadlineDateTime->format('U');
  3367. return $iUnixSeconds;
  3368. }
  3369. public function GetDefaultValue(DBObject $oHostObject = null)
  3370. {
  3371. // null value will be replaced by the current date, if not already set, in DoComputeValues
  3372. return $this->GetNullValue();
  3373. }
  3374. public function GetValidationPattern()
  3375. {
  3376. return static::GetFormat()->ToRegExpr();
  3377. }
  3378. public function GetBasicFilterOperators()
  3379. {
  3380. return array(
  3381. "="=>"equals",
  3382. "!="=>"differs from",
  3383. "<"=>"before",
  3384. "<="=>"before",
  3385. ">"=>"after (strictly)",
  3386. ">="=>"after",
  3387. "SameDay"=>"same day (strip time)",
  3388. "SameMonth"=>"same year/month",
  3389. "SameYear"=>"same year",
  3390. "Today"=>"today",
  3391. ">|"=>"after today + N days",
  3392. "<|"=>"before today + N days",
  3393. "=|"=>"equals today + N days",
  3394. );
  3395. }
  3396. public function GetBasicFilterLooseOperator()
  3397. {
  3398. // Unless we implement a "same xxx, depending on given precision" !
  3399. return "=";
  3400. }
  3401. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3402. {
  3403. $sQValue = CMDBSource::Quote($value);
  3404. switch ($sOpCode)
  3405. {
  3406. case '=':
  3407. case '!=':
  3408. case '<':
  3409. case '<=':
  3410. case '>':
  3411. case '>=':
  3412. return $this->GetSQLExpr()." $sOpCode $sQValue";
  3413. case 'SameDay':
  3414. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  3415. case 'SameMonth':
  3416. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  3417. case 'SameYear':
  3418. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  3419. case 'Today':
  3420. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  3421. case '>|':
  3422. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  3423. case '<|':
  3424. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  3425. case '=|':
  3426. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  3427. default:
  3428. return $this->GetSQLExpr()." = $sQValue";
  3429. }
  3430. }
  3431. public function MakeRealValue($proposedValue, $oHostObj)
  3432. {
  3433. if (is_null($proposedValue))
  3434. {
  3435. return null;
  3436. }
  3437. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  3438. {
  3439. return null;
  3440. }
  3441. if (!is_numeric($proposedValue))
  3442. {
  3443. // Check the format
  3444. try
  3445. {
  3446. $oFormat = new DateTimeFormat($this->GetInternalFormat());
  3447. $oTrash = $oFormat->Parse($proposedValue);
  3448. }
  3449. catch (Exception $e)
  3450. {
  3451. throw new Exception('Wrong format for date attribute '.$this->GetCode().', expecting "'.$this->GetInternalFormat().'" and got "'.$proposedValue.'"');
  3452. }
  3453. return $proposedValue;
  3454. }
  3455. return date(static::GetInternalFormat(), $proposedValue);
  3456. }
  3457. public function ScalarToSQL($value)
  3458. {
  3459. if (is_null($value))
  3460. {
  3461. return null;
  3462. }
  3463. elseif (empty($value))
  3464. {
  3465. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  3466. // todo: this is NOT valid in strict mode (default setting for MySQL 5.7)
  3467. // todo: if to be kept, this should be overloaded for AttributeDate (0000-00-00)
  3468. return '0000-00-00 00:00:00';
  3469. }
  3470. return $value;
  3471. }
  3472. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3473. {
  3474. return Str::pure2html(static::GetFormat()->format($value));
  3475. }
  3476. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  3477. {
  3478. return Str::pure2xml($value);
  3479. }
  3480. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  3481. {
  3482. if (empty($sValue) || ($sValue === '0000-00-00 00:00:00') || ($sValue === '0000-00-00'))
  3483. {
  3484. return '';
  3485. }
  3486. else if ((string)static::GetFormat() !== static::GetInternalFormat())
  3487. {
  3488. // Format conversion
  3489. $oDate = new DateTime($sValue);
  3490. if ($oDate !== false)
  3491. {
  3492. $sValue = static::GetFormat()->format($oDate);
  3493. }
  3494. }
  3495. $sFrom = array("\r\n", $sTextQualifier);
  3496. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  3497. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  3498. return $sTextQualifier.$sEscaped.$sTextQualifier;
  3499. }
  3500. /**
  3501. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  3502. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  3503. * does nothing special, and just calls the default (loose) operator
  3504. * @param string $sSearchText The search string to analyze for smart patterns
  3505. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  3506. * @param Hash $aParams Values of the query parameters
  3507. * @return Expression The search condition to be added (AND) to the current search
  3508. */
  3509. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams, $bParseSearchString = false)
  3510. {
  3511. // Possible smart patterns
  3512. $aPatterns = array(
  3513. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  3514. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  3515. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  3516. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  3517. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  3518. );
  3519. $sPatternFound = '';
  3520. $aMatches = array();
  3521. foreach($aPatterns as $sPatName => $sPattern)
  3522. {
  3523. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  3524. {
  3525. $sPatternFound = $sPatName;
  3526. break;
  3527. }
  3528. }
  3529. switch($sPatternFound)
  3530. {
  3531. case 'between':
  3532. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  3533. $oRightExpr = new VariableExpression($sParamName1);
  3534. if ($bParseSearchString)
  3535. {
  3536. $aParams[$sParamName1] = $this->ParseSearchString($aMatches[1]);
  3537. }
  3538. else
  3539. {
  3540. $aParams[$sParamName1] = $aMatches[1];
  3541. }
  3542. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  3543. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  3544. $oRightExpr = new VariableExpression($sParamName2);
  3545. $sOperator = $this->GetBasicFilterLooseOperator();
  3546. if ($bParseSearchString)
  3547. {
  3548. $aParams[$sParamName2] = $this->ParseSearchString($aMatches[2]);
  3549. }
  3550. else
  3551. {
  3552. $aParams[$sParamName2] = $aMatches[2];
  3553. }
  3554. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  3555. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  3556. break;
  3557. case 'greater than':
  3558. case 'greater than or equal':
  3559. case 'less than':
  3560. case 'less than or equal':
  3561. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  3562. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  3563. $oRightExpr = new VariableExpression($sParamName);
  3564. if ($bParseSearchString)
  3565. {
  3566. $aParams[$sParamName] = $this->ParseSearchString($aMatches[1]);
  3567. }
  3568. else
  3569. {
  3570. $aParams[$sParamName] = $aMatches[1];
  3571. }
  3572. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  3573. break;
  3574. default:
  3575. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams, $bParseSearchString);
  3576. }
  3577. return $oNewCondition;
  3578. }
  3579. public function GetHelpOnSmartSearch()
  3580. {
  3581. $sDict = parent::GetHelpOnSmartSearch();
  3582. $oFormat = static::GetFormat();
  3583. $sExample = $oFormat->Format(new DateTime('2015-07-19 18:40:00'));
  3584. return vsprintf($sDict, array($oFormat->ToPlaceholder(), $sExample));
  3585. }
  3586. }
  3587. /**
  3588. * Store a duration as a number of seconds
  3589. *
  3590. * @package iTopORM
  3591. */
  3592. class AttributeDuration extends AttributeInteger
  3593. {
  3594. public function GetEditClass() {return "Duration";}
  3595. protected function GetSQLCol($bFullSpec = false) {return "INT(11) UNSIGNED";}
  3596. public function GetNullValue() {return '0';}
  3597. public function MakeRealValue($proposedValue, $oHostObj)
  3598. {
  3599. if (is_null($proposedValue)) return null;
  3600. if (!is_numeric($proposedValue)) return null;
  3601. if ( ((int)$proposedValue) < 0) return null;
  3602. return (int)$proposedValue;
  3603. }
  3604. public function ScalarToSQL($value)
  3605. {
  3606. if (is_null($value))
  3607. {
  3608. return null;
  3609. }
  3610. return $value;
  3611. }
  3612. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3613. {
  3614. return Str::pure2html(self::FormatDuration($value));
  3615. }
  3616. public static function FormatDuration($duration)
  3617. {
  3618. $aDuration = self::SplitDuration($duration);
  3619. $sResult = '';
  3620. if ($duration < 60)
  3621. {
  3622. // Less than 1 min
  3623. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  3624. }
  3625. else if ($duration < 3600)
  3626. {
  3627. // less than 1 hour, display it in minutes/seconds
  3628. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  3629. }
  3630. else if ($duration < 86400)
  3631. {
  3632. // Less than 1 day, display it in hours/minutes/seconds
  3633. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  3634. }
  3635. else
  3636. {
  3637. // more than 1 day, display it in days/hours/minutes/seconds
  3638. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  3639. }
  3640. return $sResult;
  3641. }
  3642. static function SplitDuration($duration)
  3643. {
  3644. $duration = (int) $duration;
  3645. $days = floor($duration / 86400);
  3646. $hours = floor(($duration - (86400*$days)) / 3600);
  3647. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  3648. $seconds = ($duration % 60); // modulo
  3649. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  3650. }
  3651. static public function GetFormFieldClass()
  3652. {
  3653. return '\\Combodo\\iTop\\Form\\Field\\DurationField';
  3654. }
  3655. public function MakeFormField(DBObject $oObject, $oFormField = null)
  3656. {
  3657. if ($oFormField === null)
  3658. {
  3659. $sFormFieldClass = static::GetFormFieldClass();
  3660. $oFormField = new $sFormFieldClass($this->GetCode());
  3661. }
  3662. parent::MakeFormField($oObject, $oFormField);
  3663. // Note : As of today, this attribute is -by nature- only supported in readonly mode, not edition
  3664. $sAttCode = $this->GetCode();
  3665. $oFormField->SetCurrentValue($oObject->Get($sAttCode));
  3666. $oFormField->SetReadOnly(true);
  3667. return $oFormField;
  3668. }
  3669. }
  3670. /**
  3671. * Map a date+time column to an attribute
  3672. *
  3673. * @package iTopORM
  3674. */
  3675. class AttributeDate extends AttributeDateTime
  3676. {
  3677. static $oDateFormat = null;
  3678. static public function GetFormat()
  3679. {
  3680. if (self::$oDateFormat == null)
  3681. {
  3682. AttributeDateTime::LoadFormatFromConfig();
  3683. }
  3684. return self::$oDateFormat;
  3685. }
  3686. static public function SetFormat(DateTimeFormat $oDateFormat)
  3687. {
  3688. self::$oDateFormat = $oDateFormat;
  3689. }
  3690. /**
  3691. * Returns the format string used for the date & time stored in memory
  3692. * @return string
  3693. */
  3694. static public function GetInternalFormat()
  3695. {
  3696. return 'Y-m-d';
  3697. }
  3698. /**
  3699. * Returns the format string used for the date & time written to MySQL
  3700. * @return string
  3701. */
  3702. static public function GetSQLFormat()
  3703. {
  3704. return 'Y-m-d';
  3705. }
  3706. static public function ListExpectedParams()
  3707. {
  3708. return parent::ListExpectedParams();
  3709. //return array_merge(parent::ListExpectedParams(), array());
  3710. }
  3711. public function GetEditClass() {return "Date";}
  3712. protected function GetSQLCol($bFullSpec = false) {return "DATE";}
  3713. public function GetImportColumns()
  3714. {
  3715. // Allow an empty string to be a valid value (synonym for "reset")
  3716. $aColumns = array();
  3717. $aColumns[$this->GetCode()] = 'VARCHAR(10)';
  3718. return $aColumns;
  3719. }
  3720. /**
  3721. * Override to specify Field class
  3722. *
  3723. * 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.
  3724. */
  3725. public function MakeFormField(DBObject $oObject, $oFormField = null)
  3726. {
  3727. $oFormField = parent::MakeFormField($oObject, $oFormField);
  3728. $oFormField->SetDateOnly(true);
  3729. return $oFormField;
  3730. }
  3731. }
  3732. /**
  3733. * A dead line stored as a date & time
  3734. * The only difference with the DateTime attribute is the display:
  3735. * relative to the current time
  3736. */
  3737. class AttributeDeadline extends AttributeDateTime
  3738. {
  3739. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  3740. {
  3741. $sResult = self::FormatDeadline($value);
  3742. return $sResult;
  3743. }
  3744. public static function FormatDeadline($value)
  3745. {
  3746. $sResult = '';
  3747. if ($value !== null)
  3748. {
  3749. $iValue = AttributeDateTime::GetAsUnixSeconds($value);
  3750. $sDate = AttributeDateTime::GetFormat()->Format($value);
  3751. $difference = $iValue - time();
  3752. if ($difference >= 0)
  3753. {
  3754. $sDifference = self::FormatDuration($difference);
  3755. }
  3756. else
  3757. {
  3758. $sDifference = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  3759. }
  3760. $sFormat = MetaModel::GetConfig()->Get('deadline_format', '$difference$');
  3761. $sResult = str_replace(array('$date$', '$difference$'), array($sDate, $sDifference), $sFormat);
  3762. }
  3763. return $sResult;
  3764. }
  3765. static function FormatDuration($duration)
  3766. {
  3767. $days = floor($duration / 86400);
  3768. $hours = floor(($duration - (86400*$days)) / 3600);
  3769. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  3770. $sResult = '';
  3771. if ($duration < 60)
  3772. {
  3773. // Less than 1 min
  3774. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  3775. }
  3776. else if ($duration < 3600)
  3777. {
  3778. // less than 1 hour, display it in minutes
  3779. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  3780. }
  3781. else if ($duration < 86400)
  3782. {
  3783. // Less that 1 day, display it in hours/minutes
  3784. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  3785. }
  3786. else
  3787. {
  3788. // Less that 1 day, display it in hours/minutes
  3789. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  3790. }
  3791. return $sResult;
  3792. }
  3793. }
  3794. /**
  3795. * Map a foreign key to an attribute
  3796. * AttributeExternalKey and AttributeExternalField may be an external key
  3797. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  3798. * where an AttributeExternalField corresponds to a column into another table (class)
  3799. *
  3800. * @package iTopORM
  3801. */
  3802. class AttributeExternalKey extends AttributeDBFieldVoid
  3803. {
  3804. static public function ListExpectedParams()
  3805. {
  3806. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  3807. }
  3808. public function GetEditClass() {return "ExtKey";}
  3809. protected function GetSQLCol($bFullSpec = false) {return "INT(11)".($bFullSpec ? " DEFAULT 0" : "");}
  3810. public function RequiresIndex()
  3811. {
  3812. return true;
  3813. }
  3814. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  3815. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  3816. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  3817. public function GetKeyAttCode() {return $this->GetCode();}
  3818. public function GetDisplayStyle() { return $this->GetOptional('display_style', 'select'); }
  3819. public function GetDefaultValue(DBObject $oHostObject = null) {return 0;}
  3820. public function IsNullAllowed()
  3821. {
  3822. if (MetaModel::GetConfig()->Get('disable_mandatory_ext_keys'))
  3823. {
  3824. return true;
  3825. }
  3826. return $this->Get("is_null_allowed");
  3827. }
  3828. public function GetBasicFilterOperators()
  3829. {
  3830. return parent::GetBasicFilterOperators();
  3831. }
  3832. public function GetBasicFilterLooseOperator()
  3833. {
  3834. return parent::GetBasicFilterLooseOperator();
  3835. }
  3836. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3837. {
  3838. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  3839. }
  3840. // overloaded here so that an ext key always have the answer to
  3841. // "what are your possible values?"
  3842. public function GetValuesDef()
  3843. {
  3844. $oValSetDef = $this->Get("allowed_values");
  3845. if (!$oValSetDef)
  3846. {
  3847. // Let's propose every existing value
  3848. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  3849. }
  3850. return $oValSetDef;
  3851. }
  3852. public function GetAllowedValues($aArgs = array(), $sContains = '')
  3853. {
  3854. //throw new Exception("GetAllowedValues on ext key has been deprecated");
  3855. try
  3856. {
  3857. return parent::GetAllowedValues($aArgs, $sContains);
  3858. }
  3859. catch (MissingQueryArgument $e)
  3860. {
  3861. // Some required arguments could not be found, enlarge to any existing value
  3862. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  3863. return $oValSetDef->GetValues($aArgs, $sContains);
  3864. }
  3865. }
  3866. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  3867. {
  3868. $oValSetDef = $this->GetValuesDef();
  3869. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  3870. return $oSet;
  3871. }
  3872. public function GetDeletionPropagationOption()
  3873. {
  3874. return $this->Get("on_target_delete");
  3875. }
  3876. public function GetNullValue()
  3877. {
  3878. return 0;
  3879. }
  3880. public function IsNull($proposedValue)
  3881. {
  3882. return ($proposedValue == 0);
  3883. }
  3884. public function MakeRealValue($proposedValue, $oHostObj)
  3885. {
  3886. if (is_null($proposedValue)) return 0;
  3887. if ($proposedValue === '') return 0;
  3888. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  3889. return (int)$proposedValue;
  3890. }
  3891. public function GetMaximumComboLength()
  3892. {
  3893. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  3894. }
  3895. public function GetMinAutoCompleteChars()
  3896. {
  3897. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  3898. }
  3899. public function AllowTargetCreation()
  3900. {
  3901. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  3902. }
  3903. /**
  3904. * Find the corresponding "link" attribute on the target class
  3905. *
  3906. * @return string The attribute code on the target class, or null if none has been found
  3907. */
  3908. public function GetMirrorLinkAttribute()
  3909. {
  3910. $oRet = null;
  3911. $sRemoteClass = $this->GetTargetClass();
  3912. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  3913. {
  3914. if (!$oRemoteAttDef->IsLinkSet()) continue;
  3915. if (!is_subclass_of($this->GetHostClass(), $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $this->GetHostClass()) continue;
  3916. if ($oRemoteAttDef->GetExtKeyToMe() != $this->GetCode()) continue;
  3917. $oRet = $oRemoteAttDef;
  3918. break;
  3919. }
  3920. return $oRet;
  3921. }
  3922. static public function GetFormFieldClass()
  3923. {
  3924. return '\\Combodo\\iTop\\Form\\Field\\SelectObjectField';
  3925. }
  3926. public function MakeFormField(DBObject $oObject, $oFormField = null)
  3927. {
  3928. if ($oFormField === null)
  3929. {
  3930. // TODO : We should check $this->Get('display_style') and create a Radio / Select / ... regarding its value
  3931. $sFormFieldClass = static::GetFormFieldClass();
  3932. $oFormField = new $sFormFieldClass($this->GetCode());
  3933. }
  3934. // Setting params
  3935. $oFormField->SetMaximumComboLength($this->GetMaximumComboLength());
  3936. $oFormField->SetMinAutoCompleteChars($this->GetMinAutoCompleteChars());
  3937. $oFormField->SetHierarchical(MetaModel::IsHierarchicalClass($this->GetTargetClass()));
  3938. // Setting choices regarding the field dependencies
  3939. $aFieldDependencies = $this->GetPrerequisiteAttributes();
  3940. if (!empty($aFieldDependencies))
  3941. {
  3942. $oTmpAttDef = $this;
  3943. $oTmpField = $oFormField;
  3944. $oFormField->SetOnFinalizeCallback(function() use ($oTmpField, $oTmpAttDef, $oObject)
  3945. {
  3946. // We set search object only if it has not already been set (overrided)
  3947. if ($oTmpField->GetSearch() === null)
  3948. {
  3949. $oSearch = DBSearch::FromOQL($oTmpAttDef->GetValuesDef()->GetFilterExpression());
  3950. $oSearch->SetInternalParams(array('this' => $oObject));
  3951. $oTmpField->SetSearch($oSearch);
  3952. }
  3953. });
  3954. }
  3955. else
  3956. {
  3957. $oSearch = DBSearch::FromOQL($this->GetValuesDef()->GetFilterExpression());
  3958. $oSearch->SetInternalParams(array('this' => $oObject));
  3959. $oFormField->SetSearch($oSearch);
  3960. }
  3961. // If ExtKey is mandatory, we add a validator to ensure that the value 0 is not selected
  3962. if ($oObject->GetAttributeFlags($this->GetCode()) & OPT_ATT_MANDATORY)
  3963. {
  3964. $oFormField->AddValidator(new \Combodo\iTop\Form\Validator\NotEmptyExtKeyValidator());
  3965. }
  3966. parent::MakeFormField($oObject, $oFormField);
  3967. return $oFormField;
  3968. }
  3969. }
  3970. /**
  3971. * Special kind of External Key to manage a hierarchy of objects
  3972. */
  3973. class AttributeHierarchicalKey extends AttributeExternalKey
  3974. {
  3975. protected $m_sTargetClass;
  3976. static public function ListExpectedParams()
  3977. {
  3978. $aParams = parent::ListExpectedParams();
  3979. $idx = array_search('targetclass', $aParams);
  3980. unset($aParams[$idx]);
  3981. $idx = array_search('jointype', $aParams);
  3982. unset($aParams[$idx]);
  3983. return $aParams; // TODO: mettre les bons parametres ici !!
  3984. }
  3985. public function GetEditClass() {return "ExtKey";}
  3986. public function RequiresIndex()
  3987. {
  3988. return true;
  3989. }
  3990. /*
  3991. * The target class is the class for which the attribute has been defined first
  3992. */
  3993. public function SetHostClass($sHostClass)
  3994. {
  3995. if (!isset($this->m_sTargetClass))
  3996. {
  3997. $this->m_sTargetClass = $sHostClass;
  3998. }
  3999. parent::SetHostClass($sHostClass);
  4000. }
  4001. public function IsHierarchicalKey() {return true;}
  4002. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->m_sTargetClass;}
  4003. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  4004. public function GetKeyAttCode() {return $this->GetCode();}
  4005. public function GetBasicFilterOperators()
  4006. {
  4007. return parent::GetBasicFilterOperators();
  4008. }
  4009. public function GetBasicFilterLooseOperator()
  4010. {
  4011. return parent::GetBasicFilterLooseOperator();
  4012. }
  4013. public function GetSQLColumns($bFullSpec = false)
  4014. {
  4015. $aColumns = array();
  4016. $aColumns[$this->GetCode()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  4017. $aColumns[$this->GetSQLLeft()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  4018. $aColumns[$this->GetSQLRight()] = 'INT(11)'.($bFullSpec ? ' DEFAULT 0' : '');
  4019. return $aColumns;
  4020. }
  4021. public function GetSQLRight()
  4022. {
  4023. return $this->GetCode().'_right';
  4024. }
  4025. public function GetSQLLeft()
  4026. {
  4027. return $this->GetCode().'_left';
  4028. }
  4029. public function GetSQLValues($value)
  4030. {
  4031. if (!is_array($value))
  4032. {
  4033. $aValues[$this->GetCode()] = $value;
  4034. }
  4035. else
  4036. {
  4037. $aValues = array();
  4038. $aValues[$this->GetCode()] = $value[$this->GetCode()];
  4039. $aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
  4040. $aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
  4041. }
  4042. return $aValues;
  4043. }
  4044. public function GetAllowedValues($aArgs = array(), $sContains = '')
  4045. {
  4046. if (array_key_exists('this', $aArgs))
  4047. {
  4048. // Hierarchical keys have one more constraint: the "parent value" cannot be
  4049. // "under" themselves
  4050. $iRootId = $aArgs['this']->GetKey();
  4051. if ($iRootId > 0) // ignore objects that do no exist in the database...
  4052. {
  4053. $oValSetDef = $this->GetValuesDef();
  4054. $sClass = $this->m_sTargetClass;
  4055. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  4056. $oValSetDef->AddCondition($oFilter);
  4057. }
  4058. }
  4059. else
  4060. {
  4061. return parent::GetAllowedValues($aArgs, $sContains);
  4062. }
  4063. }
  4064. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  4065. {
  4066. $oValSetDef = $this->GetValuesDef();
  4067. if (array_key_exists('this', $aArgs))
  4068. {
  4069. // Hierarchical keys have one more constraint: the "parent value" cannot be
  4070. // "under" themselves
  4071. $iRootId = $aArgs['this']->GetKey();
  4072. if ($iRootId > 0) // ignore objects that do no exist in the database...
  4073. {
  4074. $aValuesSetDef = $this->GetValuesDef();
  4075. $sClass = $this->m_sTargetClass;
  4076. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  4077. $oValSetDef->AddCondition($oFilter);
  4078. }
  4079. }
  4080. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  4081. return $oSet;
  4082. }
  4083. /**
  4084. * Find the corresponding "link" attribute on the target class
  4085. *
  4086. * @return string The attribute code on the target class, or null if none has been found
  4087. */
  4088. public function GetMirrorLinkAttribute()
  4089. {
  4090. return null;
  4091. }
  4092. }
  4093. /**
  4094. * An attribute which corresponds to an external key (direct or indirect)
  4095. *
  4096. * @package iTopORM
  4097. */
  4098. class AttributeExternalField extends AttributeDefinition
  4099. {
  4100. static public function ListExpectedParams()
  4101. {
  4102. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  4103. }
  4104. public function GetEditClass() {return "ExtField";}
  4105. public function GetFinalAttDef()
  4106. {
  4107. $oExtAttDef = $this->GetExtAttDef();
  4108. return $oExtAttDef->GetFinalAttDef();
  4109. }
  4110. protected function GetSQLCol($bFullSpec = false)
  4111. {
  4112. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  4113. $oExtAttDef = $this->GetExtAttDef();
  4114. return $oExtAttDef->GetSQLCol($bFullSpec);
  4115. }
  4116. public function GetSQLExpressions($sPrefix = '')
  4117. {
  4118. if ($sPrefix == '')
  4119. {
  4120. return array('' => $this->GetCode()); // Warning: Use GetCode() since AttributeExternalField does not have any 'sql' property
  4121. }
  4122. else
  4123. {
  4124. return $sPrefix;
  4125. }
  4126. }
  4127. public function GetLabel($sDefault = null)
  4128. {
  4129. $sLabel = parent::GetLabel('');
  4130. if (strlen($sLabel) == 0)
  4131. {
  4132. $oRemoteAtt = $this->GetExtAttDef();
  4133. $sLabel = $oRemoteAtt->GetLabel($this->m_sCode);
  4134. }
  4135. return $sLabel;
  4136. }
  4137. public function GetDescription($sDefault = null)
  4138. {
  4139. $sLabel = parent::GetDescription('');
  4140. if (strlen($sLabel) == 0)
  4141. {
  4142. $oRemoteAtt = $this->GetExtAttDef();
  4143. $sLabel = $oRemoteAtt->GetDescription('');
  4144. }
  4145. return $sLabel;
  4146. }
  4147. public function GetHelpOnEdition($sDefault = null)
  4148. {
  4149. $sLabel = parent::GetHelpOnEdition('');
  4150. if (strlen($sLabel) == 0)
  4151. {
  4152. $oRemoteAtt = $this->GetExtAttDef();
  4153. $sLabel = $oRemoteAtt->GetHelpOnEdition('');
  4154. }
  4155. return $sLabel;
  4156. }
  4157. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  4158. {
  4159. switch($iType)
  4160. {
  4161. case EXTKEY_ABSOLUTE:
  4162. // see further
  4163. $oRemoteAtt = $this->GetExtAttDef();
  4164. return $oRemoteAtt->IsExternalKey($iType);
  4165. case EXTKEY_RELATIVE:
  4166. return false;
  4167. default:
  4168. throw new CoreException("Unexpected value for argument iType: '$iType'");
  4169. }
  4170. }
  4171. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  4172. {
  4173. return $this->GetKeyAttDef($iType)->GetTargetClass();
  4174. }
  4175. public function IsExternalField() {return true;}
  4176. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  4177. public function GetExtAttCode() {return $this->Get("target_attcode");}
  4178. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  4179. {
  4180. switch($iType)
  4181. {
  4182. case EXTKEY_ABSOLUTE:
  4183. // see further
  4184. $oRemoteAtt = $this->GetExtAttDef();
  4185. if ($oRemoteAtt->IsExternalField())
  4186. {
  4187. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  4188. }
  4189. else if ($oRemoteAtt->IsExternalKey())
  4190. {
  4191. return $oRemoteAtt;
  4192. }
  4193. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  4194. case EXTKEY_RELATIVE:
  4195. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  4196. default:
  4197. throw new CoreException("Unexpected value for argument iType: '$iType'");
  4198. }
  4199. }
  4200. public function GetPrerequisiteAttributes($sClass = null)
  4201. {
  4202. return array($this->Get("extkey_attcode"));
  4203. }
  4204. public function GetExtAttDef()
  4205. {
  4206. $oKeyAttDef = $this->GetKeyAttDef();
  4207. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $this->Get("target_attcode"));
  4208. 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"));
  4209. return $oExtAttDef;
  4210. }
  4211. public function GetSQLExpr()
  4212. {
  4213. $oExtAttDef = $this->GetExtAttDef();
  4214. return $oExtAttDef->GetSQLExpr();
  4215. }
  4216. public function GetDefaultValue(DBObject $oHostObject = null)
  4217. {
  4218. $oExtAttDef = $this->GetExtAttDef();
  4219. return $oExtAttDef->GetDefaultValue();
  4220. }
  4221. public function IsNullAllowed()
  4222. {
  4223. $oExtAttDef = $this->GetExtAttDef();
  4224. return $oExtAttDef->IsNullAllowed();
  4225. }
  4226. public function IsScalar()
  4227. {
  4228. $oExtAttDef = $this->GetExtAttDef();
  4229. return $oExtAttDef->IsScalar();
  4230. }
  4231. public function GetFilterDefinitions()
  4232. {
  4233. return array($this->GetCode() => new FilterFromAttribute($this));
  4234. }
  4235. public function GetBasicFilterOperators()
  4236. {
  4237. $oExtAttDef = $this->GetExtAttDef();
  4238. return $oExtAttDef->GetBasicFilterOperators();
  4239. }
  4240. public function GetBasicFilterLooseOperator()
  4241. {
  4242. $oExtAttDef = $this->GetExtAttDef();
  4243. return $oExtAttDef->GetBasicFilterLooseOperator();
  4244. }
  4245. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4246. {
  4247. $oExtAttDef = $this->GetExtAttDef();
  4248. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  4249. }
  4250. public function GetNullValue()
  4251. {
  4252. $oExtAttDef = $this->GetExtAttDef();
  4253. return $oExtAttDef->GetNullValue();
  4254. }
  4255. public function IsNull($proposedValue)
  4256. {
  4257. $oExtAttDef = $this->GetExtAttDef();
  4258. return $oExtAttDef->IsNull($proposedValue);
  4259. }
  4260. public function MakeRealValue($proposedValue, $oHostObj)
  4261. {
  4262. $oExtAttDef = $this->GetExtAttDef();
  4263. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  4264. }
  4265. public function ScalarToSQL($value)
  4266. {
  4267. // This one could be used in case of filtering only
  4268. $oExtAttDef = $this->GetExtAttDef();
  4269. return $oExtAttDef->ScalarToSQL($value);
  4270. }
  4271. // Do not overload GetSQLExpression here because this is handled in the joins
  4272. //public function GetSQLExpressions($sPrefix = '') {return array();}
  4273. // Here, we get the data...
  4274. public function FromSQLToValue($aCols, $sPrefix = '')
  4275. {
  4276. $oExtAttDef = $this->GetExtAttDef();
  4277. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  4278. }
  4279. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4280. {
  4281. $oExtAttDef = $this->GetExtAttDef();
  4282. return $oExtAttDef->GetAsHTML($value, null, $bLocalize);
  4283. }
  4284. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4285. {
  4286. $oExtAttDef = $this->GetExtAttDef();
  4287. return $oExtAttDef->GetAsXML($value, null, $bLocalize);
  4288. }
  4289. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  4290. {
  4291. $oExtAttDef = $this->GetExtAttDef();
  4292. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier, null, $bLocalize, $bConvertToPlainText);
  4293. }
  4294. static public function GetFormFieldClass()
  4295. {
  4296. return '\\Combodo\\iTop\\Form\\Field\\LabelField';
  4297. }
  4298. public function MakeFormField(DBObject $oObject, $oFormField = null)
  4299. {
  4300. if ($oFormField === null)
  4301. {
  4302. $sFormFieldClass = static::GetFormFieldClass();
  4303. $oFormField = new $sFormFieldClass($this->GetCode());
  4304. }
  4305. parent::MakeFormField($oObject, $oFormField);
  4306. // Note : As of today, this attribute is -by nature- only supported in readonly mode, not edition
  4307. $sAttCode = $this->GetCode();
  4308. $sAttCodeFriendlyname = $sAttCode . '_friendlyname';
  4309. if ($this->IsExternalKey(EXTKEY_ABSOLUTE) && MetaModel::IsValidAttCode(get_class($oObject), $sAttCodeFriendlyname))
  4310. {
  4311. $sAttCode = $sAttCodeFriendlyname;
  4312. }
  4313. $oFormField->SetCurrentValue(html_entity_decode($oObject->GetAsHTML($sAttCode), ENT_QUOTES, 'UTF-8'));
  4314. return $oFormField;
  4315. }
  4316. public function IsPartOfFingerprint()
  4317. {
  4318. return false;
  4319. }
  4320. }
  4321. /**
  4322. * Map a varchar column to an URL (formats the ouput in HMTL)
  4323. *
  4324. * @package iTopORM
  4325. */
  4326. class AttributeURL extends AttributeString
  4327. {
  4328. static public function ListExpectedParams()
  4329. {
  4330. //return parent::ListExpectedParams();
  4331. return array_merge(parent::ListExpectedParams(), array("target"));
  4332. }
  4333. protected function GetSQLCol($bFullSpec = false) {return "VARCHAR(2048)".($bFullSpec ? $this->GetSQLColSpec() : '');}
  4334. public function GetMaxSize()
  4335. {
  4336. return 2048;
  4337. }
  4338. public function GetEditClass() {return "String";}
  4339. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  4340. {
  4341. $sTarget = $this->Get("target");
  4342. if (empty($sTarget)) $sTarget = "_blank";
  4343. $sLabel = Str::pure2html($sValue);
  4344. if (strlen($sLabel) > 128)
  4345. {
  4346. // Truncate the length to 128 characters, by removing the middle
  4347. $sLabel = substr($sLabel, 0, 100).'.....'.substr($sLabel, -20);
  4348. }
  4349. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  4350. }
  4351. public function GetValidationPattern()
  4352. {
  4353. return $this->GetOptional('validation_pattern', '^'.utils::GetConfig()->Get('url_validation_pattern').'$');
  4354. }
  4355. }
  4356. /**
  4357. * A blob is an ormDocument, it is stored as several columns in the database
  4358. *
  4359. * @package iTopORM
  4360. */
  4361. class AttributeBlob extends AttributeDefinition
  4362. {
  4363. static public function ListExpectedParams()
  4364. {
  4365. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  4366. }
  4367. public function GetEditClass() {return "Document";}
  4368. public function IsDirectField() {return true;}
  4369. public function IsScalar() {return true;}
  4370. public function IsWritable() {return true;}
  4371. public function GetDefaultValue(DBObject $oHostObject = null) {return "";}
  4372. public function IsNullAllowed(DBObject $oHostObject = null) {return $this->GetOptional("is_null_allowed", false);}
  4373. public function GetEditValue($sValue, $oHostObj = null)
  4374. {
  4375. return '';
  4376. }
  4377. // Facilitate things: allow administrators to upload a document
  4378. // from a CSV by specifying its path/URL
  4379. public function MakeRealValue($proposedValue, $oHostObj)
  4380. {
  4381. if (!is_object($proposedValue))
  4382. {
  4383. if (file_exists($proposedValue) && UserRights::IsAdministrator())
  4384. {
  4385. $sContent = file_get_contents($proposedValue);
  4386. $sExtension = strtolower(pathinfo($proposedValue, PATHINFO_EXTENSION));
  4387. $sMimeType = "application/x-octet-stream";
  4388. $aKnownExtensions = array(
  4389. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  4390. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  4391. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  4392. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  4393. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  4394. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  4395. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  4396. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  4397. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  4398. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12.xlsx',
  4399. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  4400. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  4401. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  4402. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  4403. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  4404. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  4405. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  4406. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  4407. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  4408. 'jpg' => 'image/jpeg',
  4409. 'jpeg' => 'image/jpeg',
  4410. 'gif' => 'image/gif',
  4411. 'png' => 'image/png',
  4412. 'pdf' => 'application/pdf',
  4413. 'doc' => 'application/msword',
  4414. 'dot' => 'application/msword',
  4415. 'xls' => 'application/vnd.ms-excel',
  4416. 'ppt' => 'application/vnd.ms-powerpoint',
  4417. 'vsd' => 'application/x-visio',
  4418. 'vdx' => 'application/visio.drawing',
  4419. 'odt' => 'application/vnd.oasis.opendocument.text',
  4420. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  4421. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  4422. 'zip' => 'application/zip',
  4423. 'txt' => 'text/plain',
  4424. 'htm' => 'text/html',
  4425. 'html' => 'text/html',
  4426. 'exe' => 'application/octet-stream'
  4427. );
  4428. if (!array_key_exists($sExtension, $aKnownExtensions) && extension_loaded('fileinfo'))
  4429. {
  4430. $finfo = new finfo(FILEINFO_MIME);
  4431. $sMimeType = $finfo->file($proposedValue);
  4432. }
  4433. return new ormDocument($sContent, $sMimeType);
  4434. }
  4435. else
  4436. {
  4437. return new ormDocument($proposedValue, 'text/plain');
  4438. }
  4439. }
  4440. return $proposedValue;
  4441. }
  4442. public function GetSQLExpressions($sPrefix = '')
  4443. {
  4444. if ($sPrefix == '')
  4445. {
  4446. $sPrefix = $this->GetCode();
  4447. }
  4448. $aColumns = array();
  4449. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  4450. $aColumns[''] = $sPrefix.'_mimetype';
  4451. $aColumns['_data'] = $sPrefix.'_data';
  4452. $aColumns['_filename'] = $sPrefix.'_filename';
  4453. return $aColumns;
  4454. }
  4455. public function FromSQLToValue($aCols, $sPrefix = '')
  4456. {
  4457. if (!array_key_exists($sPrefix, $aCols))
  4458. {
  4459. $sAvailable = implode(', ', array_keys($aCols));
  4460. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  4461. }
  4462. $sMimeType = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  4463. if (!array_key_exists($sPrefix.'_data', $aCols))
  4464. {
  4465. $sAvailable = implode(', ', array_keys($aCols));
  4466. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  4467. }
  4468. $data = isset($aCols[$sPrefix.'_data']) ? $aCols[$sPrefix.'_data'] : null;
  4469. if (!array_key_exists($sPrefix.'_filename', $aCols))
  4470. {
  4471. $sAvailable = implode(', ', array_keys($aCols));
  4472. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  4473. }
  4474. $sFileName = isset($aCols[$sPrefix.'_filename']) ? $aCols[$sPrefix.'_filename'] : '';
  4475. $value = new ormDocument($data, $sMimeType, $sFileName);
  4476. return $value;
  4477. }
  4478. public function GetSQLValues($value)
  4479. {
  4480. // #@# Optimization: do not load blobs anytime
  4481. // As per mySQL doc, selecting blob columns will prevent mySQL from
  4482. // using memory in case a temporary table has to be created
  4483. // (temporary tables created on disk)
  4484. // We will have to remove the blobs from the list of attributes when doing the select
  4485. // then the use of Get() should finalize the load
  4486. if ($value instanceOf ormDocument && !$value->IsEmpty())
  4487. {
  4488. $aValues = array();
  4489. $aValues[$this->GetCode().'_data'] = $value->GetData();
  4490. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  4491. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  4492. }
  4493. else
  4494. {
  4495. $aValues = array();
  4496. $aValues[$this->GetCode().'_data'] = '';
  4497. $aValues[$this->GetCode().'_mimetype'] = '';
  4498. $aValues[$this->GetCode().'_filename'] = '';
  4499. }
  4500. return $aValues;
  4501. }
  4502. public function GetSQLColumns($bFullSpec = false)
  4503. {
  4504. $aColumns = array();
  4505. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  4506. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  4507. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  4508. return $aColumns;
  4509. }
  4510. public function GetFilterDefinitions()
  4511. {
  4512. return array();
  4513. // still not working... see later...
  4514. return array(
  4515. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  4516. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  4517. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  4518. );
  4519. }
  4520. public function GetBasicFilterOperators()
  4521. {
  4522. return array();
  4523. }
  4524. public function GetBasicFilterLooseOperator()
  4525. {
  4526. return '=';
  4527. }
  4528. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4529. {
  4530. return 'true';
  4531. }
  4532. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4533. {
  4534. if (is_object($value))
  4535. {
  4536. return $value->GetAsHTML();
  4537. }
  4538. }
  4539. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  4540. {
  4541. return ''; // Not exportable in CSV !
  4542. }
  4543. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4544. {
  4545. $sRet = '';
  4546. if (is_object($value))
  4547. {
  4548. if (!$value->IsEmpty())
  4549. {
  4550. $sRet = '<mimetype>'.$value->GetMimeType().'</mimetype>';
  4551. $sRet .= '<filename>'.$value->GetFileName().'</filename>';
  4552. $sRet .= '<data>'.base64_encode($value->GetData()).'</data>';
  4553. }
  4554. }
  4555. return $sRet;
  4556. }
  4557. /**
  4558. * Helper to get a value that will be JSON encoded
  4559. * The operation is the opposite to FromJSONToValue
  4560. */
  4561. public function GetForJSON($value)
  4562. {
  4563. if ($value instanceOf ormDocument)
  4564. {
  4565. $aValues = array();
  4566. $aValues['data'] = base64_encode($value->GetData());
  4567. $aValues['mimetype'] = $value->GetMimeType();
  4568. $aValues['filename'] = $value->GetFileName();
  4569. }
  4570. else
  4571. {
  4572. $aValues = null;
  4573. }
  4574. return $aValues;
  4575. }
  4576. /**
  4577. * Helper to form a value, given JSON decoded data
  4578. * The operation is the opposite to GetForJSON
  4579. */
  4580. public function FromJSONToValue($json)
  4581. {
  4582. if (isset($json->data))
  4583. {
  4584. $data = base64_decode($json->data);
  4585. $value = new ormDocument($data, $json->mimetype, $json->filename);
  4586. }
  4587. else
  4588. {
  4589. $value = null;
  4590. }
  4591. return $value;
  4592. }
  4593. public function Fingerprint($value)
  4594. {
  4595. $sFingerprint = '';
  4596. if ($value instanceOf ormDocument)
  4597. {
  4598. $sFingerprint = md5($value->GetData());
  4599. }
  4600. return $sFingerprint;
  4601. }
  4602. static public function GetFormFieldClass()
  4603. {
  4604. return '\\Combodo\\iTop\\Form\\Field\\BlobField';
  4605. }
  4606. public function MakeFormField(DBObject $oObject, $oFormField = null)
  4607. {
  4608. if ($oFormField === null)
  4609. {
  4610. $sFormFieldClass = static::GetFormFieldClass();
  4611. $oFormField = new $sFormFieldClass($this->GetCode());
  4612. }
  4613. // Note: As of today we want this field to always be read-only
  4614. $oFormField->SetReadOnly(true);
  4615. // Generating urls
  4616. $value = $oObject->Get($this->GetCode());
  4617. $oFormField->SetDownloadUrl($value->GetDownloadURL(get_class($oObject), $oObject->GetKey(), $this->GetCode()));
  4618. $oFormField->SetDisplayUrl($value->GetDisplayURL(get_class($oObject), $oObject->GetKey(), $this->GetCode()));
  4619. parent::MakeFormField($oObject, $oFormField);
  4620. return $oFormField;
  4621. }
  4622. }
  4623. /**
  4624. * An image is a specific type of document, it is stored as several columns in the database
  4625. *
  4626. * @package iTopORM
  4627. */
  4628. class AttributeImage extends AttributeBlob
  4629. {
  4630. public function GetEditClass() {return "Image";}
  4631. // Facilitate things: allow administrators to upload a document
  4632. // from a CSV by specifying its path/URL
  4633. public function MakeRealValue($proposedValue, $oHostObj)
  4634. {
  4635. if (!is_object($proposedValue))
  4636. {
  4637. if (file_exists($proposedValue) && UserRights::IsAdministrator())
  4638. {
  4639. $sContent = file_get_contents($proposedValue);
  4640. $sExtension = strtolower(pathinfo($proposedValue, PATHINFO_EXTENSION));
  4641. $sMimeType = "application/x-octet-stream";
  4642. $aKnownExtensions = array(
  4643. 'jpg' => 'image/jpeg',
  4644. 'jpeg' => 'image/jpeg',
  4645. 'gif' => 'image/gif',
  4646. 'png' => 'image/png'
  4647. );
  4648. if (!array_key_exists($sExtension, $aKnownExtensions) && extension_loaded('fileinfo'))
  4649. {
  4650. $finfo = new finfo(FILEINFO_MIME);
  4651. $sMimeType = $finfo->file($proposedValue);
  4652. }
  4653. return new ormDocument($sContent, $sMimeType);
  4654. }
  4655. }
  4656. return $proposedValue;
  4657. }
  4658. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4659. {
  4660. $iMaxWidthPx = $this->Get('display_max_width');
  4661. $iMaxHeightPx = $this->Get('display_max_height');
  4662. $sUrl = $this->Get('default_image');
  4663. $sRet = '<img src="'.$sUrl.'" style="max-width: '.$iMaxWidthPx.'px; max-height: '.$iMaxHeightPx.'px">';
  4664. if (is_object($value) && !$value->IsEmpty())
  4665. {
  4666. $sUrl = $value->GetDownloadURL(get_class($oHostObject), $oHostObject->GetKey(), $this->GetCode());
  4667. $sRet = '<img src="'.$sUrl.'" style="max-width: '.$iMaxWidthPx.'px; max-height: '.$iMaxHeightPx.'px">';
  4668. }
  4669. return '<div class="view-image" style="width: '.$iMaxWidthPx.'px; height: '.$iMaxHeightPx.'px;"><span class="helper-middle"></span>'.$sRet.'</div>';
  4670. }
  4671. }
  4672. /**
  4673. * A stop watch is an ormStopWatch object, it is stored as several columns in the database
  4674. *
  4675. * @package iTopORM
  4676. */
  4677. class AttributeStopWatch extends AttributeDefinition
  4678. {
  4679. static public function ListExpectedParams()
  4680. {
  4681. // The list of thresholds must be an array of iPercent => array of 'option' => value
  4682. return array_merge(parent::ListExpectedParams(), array("states", "goal_computing", "working_time_computing", "thresholds"));
  4683. }
  4684. public function GetEditClass() {return "StopWatch";}
  4685. public function IsDirectField() {return true;}
  4686. public function IsScalar() {return true;}
  4687. public function IsWritable() {return false;}
  4688. public function GetDefaultValue(DBObject $oHostObject = null) {return $this->NewStopWatch();}
  4689. public function GetEditValue($value, $oHostObj = null)
  4690. {
  4691. return $value->GetTimeSpent();
  4692. }
  4693. public function GetStates()
  4694. {
  4695. return $this->Get('states');
  4696. }
  4697. public function AlwaysLoadInTables()
  4698. {
  4699. // Each and every stop watch is accessed for computing the highlight code (DBObject::GetHighlightCode())
  4700. return true;
  4701. }
  4702. /**
  4703. * Construct a brand new (but configured) stop watch
  4704. */
  4705. public function NewStopWatch()
  4706. {
  4707. $oSW = new ormStopWatch();
  4708. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4709. {
  4710. $oSW->DefineThreshold($iThreshold);
  4711. }
  4712. return $oSW;
  4713. }
  4714. // Facilitate things: allow the user to Set the value from a string
  4715. public function MakeRealValue($proposedValue, $oHostObj)
  4716. {
  4717. if (!$proposedValue instanceof ormStopWatch)
  4718. {
  4719. return $this->NewStopWatch();
  4720. }
  4721. return $proposedValue;
  4722. }
  4723. public function GetSQLExpressions($sPrefix = '')
  4724. {
  4725. if ($sPrefix == '')
  4726. {
  4727. $sPrefix = $this->GetCode(); // Warning: a stopwatch does not have any 'sql' property, so its SQL column is equal to its attribute code !!
  4728. }
  4729. $aColumns = array();
  4730. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  4731. $aColumns[''] = $sPrefix.'_timespent';
  4732. $aColumns['_started'] = $sPrefix.'_started';
  4733. $aColumns['_laststart'] = $sPrefix.'_laststart';
  4734. $aColumns['_stopped'] = $sPrefix.'_stopped';
  4735. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4736. {
  4737. $sThPrefix = '_'.$iThreshold;
  4738. $aColumns[$sThPrefix.'_deadline'] = $sPrefix.$sThPrefix.'_deadline';
  4739. $aColumns[$sThPrefix.'_passed'] = $sPrefix.$sThPrefix.'_passed';
  4740. $aColumns[$sThPrefix.'_triggered'] = $sPrefix.$sThPrefix.'_triggered';
  4741. $aColumns[$sThPrefix.'_overrun'] = $sPrefix.$sThPrefix.'_overrun';
  4742. }
  4743. return $aColumns;
  4744. }
  4745. public static function DateToSeconds($sDate)
  4746. {
  4747. if (is_null($sDate))
  4748. {
  4749. return null;
  4750. }
  4751. $oDateTime = new DateTime($sDate);
  4752. $iSeconds = $oDateTime->format('U');
  4753. return $iSeconds;
  4754. }
  4755. public static function SecondsToDate($iSeconds)
  4756. {
  4757. if (is_null($iSeconds))
  4758. {
  4759. return null;
  4760. }
  4761. return date("Y-m-d H:i:s", $iSeconds);
  4762. }
  4763. public function FromSQLToValue($aCols, $sPrefix = '')
  4764. {
  4765. $aExpectedCols = array($sPrefix, $sPrefix.'_started', $sPrefix.'_laststart', $sPrefix.'_stopped');
  4766. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4767. {
  4768. $sThPrefix = '_'.$iThreshold;
  4769. $aExpectedCols[] = $sPrefix.$sThPrefix.'_deadline';
  4770. $aExpectedCols[] = $sPrefix.$sThPrefix.'_passed';
  4771. $aExpectedCols[] = $sPrefix.$sThPrefix.'_triggered';
  4772. $aExpectedCols[] = $sPrefix.$sThPrefix.'_overrun';
  4773. }
  4774. foreach ($aExpectedCols as $sExpectedCol)
  4775. {
  4776. if (!array_key_exists($sExpectedCol, $aCols))
  4777. {
  4778. $sAvailable = implode(', ', array_keys($aCols));
  4779. throw new MissingColumnException("Missing column '$sExpectedCol' from {$sAvailable}");
  4780. }
  4781. }
  4782. $value = new ormStopWatch(
  4783. $aCols[$sPrefix],
  4784. self::DateToSeconds($aCols[$sPrefix.'_started']),
  4785. self::DateToSeconds($aCols[$sPrefix.'_laststart']),
  4786. self::DateToSeconds($aCols[$sPrefix.'_stopped'])
  4787. );
  4788. $aThresholds = array();
  4789. foreach ($this->ListThresholds() as $iThreshold => $aDefinition)
  4790. {
  4791. $sThPrefix = '_'.$iThreshold;
  4792. $value->DefineThreshold(
  4793. $iThreshold,
  4794. self::DateToSeconds($aCols[$sPrefix.$sThPrefix.'_deadline']),
  4795. (bool)($aCols[$sPrefix.$sThPrefix.'_passed'] == 1),
  4796. (bool)($aCols[$sPrefix.$sThPrefix.'_triggered'] == 1),
  4797. $aCols[$sPrefix.$sThPrefix.'_overrun'],
  4798. array_key_exists('highlight', $aDefinition) ? $aDefinition['highlight'] : null
  4799. );
  4800. }
  4801. return $value;
  4802. }
  4803. public function GetSQLValues($value)
  4804. {
  4805. if ($value instanceOf ormStopWatch)
  4806. {
  4807. $aValues = array();
  4808. $aValues[$this->GetCode().'_timespent'] = $value->GetTimeSpent();
  4809. $aValues[$this->GetCode().'_started'] = self::SecondsToDate($value->GetStartDate());
  4810. $aValues[$this->GetCode().'_laststart'] = self::SecondsToDate($value->GetLastStartDate());
  4811. $aValues[$this->GetCode().'_stopped'] = self::SecondsToDate($value->GetStopDate());
  4812. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4813. {
  4814. $sPrefix = $this->GetCode().'_'.$iThreshold;
  4815. $aValues[$sPrefix.'_deadline'] = self::SecondsToDate($value->GetThresholdDate($iThreshold));
  4816. $aValues[$sPrefix.'_passed'] = $value->IsThresholdPassed($iThreshold) ? '1' : '0';
  4817. $aValues[$sPrefix.'_triggered'] = $value->IsThresholdTriggered($iThreshold) ? '1' : '0';
  4818. $aValues[$sPrefix.'_overrun'] = $value->GetOverrun($iThreshold);
  4819. }
  4820. }
  4821. else
  4822. {
  4823. $aValues = array();
  4824. $aValues[$this->GetCode().'_timespent'] = '';
  4825. $aValues[$this->GetCode().'_started'] = '';
  4826. $aValues[$this->GetCode().'_laststart'] = '';
  4827. $aValues[$this->GetCode().'_stopped'] = '';
  4828. }
  4829. return $aValues;
  4830. }
  4831. public function GetSQLColumns($bFullSpec = false)
  4832. {
  4833. $aColumns = array();
  4834. $aColumns[$this->GetCode().'_timespent'] = 'INT(11) UNSIGNED';
  4835. $aColumns[$this->GetCode().'_started'] = 'DATETIME';
  4836. $aColumns[$this->GetCode().'_laststart'] = 'DATETIME';
  4837. $aColumns[$this->GetCode().'_stopped'] = 'DATETIME';
  4838. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4839. {
  4840. $sPrefix = $this->GetCode().'_'.$iThreshold;
  4841. $aColumns[$sPrefix.'_deadline'] = 'DATETIME';
  4842. $aColumns[$sPrefix.'_passed'] = 'TINYINT(1) UNSIGNED';
  4843. $aColumns[$sPrefix.'_triggered'] = 'TINYINT(1)';
  4844. $aColumns[$sPrefix.'_overrun'] = 'INT(11) UNSIGNED';
  4845. }
  4846. return $aColumns;
  4847. }
  4848. public function GetFilterDefinitions()
  4849. {
  4850. $aRes = array(
  4851. $this->GetCode() => new FilterFromAttribute($this),
  4852. $this->GetCode().'_started' => new FilterFromAttribute($this, '_started'),
  4853. $this->GetCode().'_laststart' => new FilterFromAttribute($this, '_laststart'),
  4854. $this->GetCode().'_stopped' => new FilterFromAttribute($this, '_stopped')
  4855. );
  4856. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4857. {
  4858. $sPrefix = $this->GetCode().'_'.$iThreshold;
  4859. $aRes[$sPrefix.'_deadline'] = new FilterFromAttribute($this, '_deadline');
  4860. $aRes[$sPrefix.'_passed'] = new FilterFromAttribute($this, '_passed');
  4861. $aRes[$sPrefix.'_triggered'] = new FilterFromAttribute($this, '_triggered');
  4862. $aRes[$sPrefix.'_overrun'] = new FilterFromAttribute($this, '_overrun');
  4863. }
  4864. return $aRes;
  4865. }
  4866. public function GetBasicFilterOperators()
  4867. {
  4868. return array();
  4869. }
  4870. public function GetBasicFilterLooseOperator()
  4871. {
  4872. return '=';
  4873. }
  4874. public function GetBasicFilterSQLExpr($sOpCode, $value)
  4875. {
  4876. return 'true';
  4877. }
  4878. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  4879. {
  4880. if (is_object($value))
  4881. {
  4882. return $value->GetAsHTML($this, $oHostObject);
  4883. }
  4884. }
  4885. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  4886. {
  4887. return $value->GetTimeSpent();
  4888. }
  4889. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  4890. {
  4891. return $value->GetTimeSpent();
  4892. }
  4893. public function ListThresholds()
  4894. {
  4895. return $this->Get('thresholds');
  4896. }
  4897. public function Fingerprint($value)
  4898. {
  4899. $sFingerprint = '';
  4900. if (is_object($value))
  4901. {
  4902. $sFingerprint = $value->GetAsHTML($this);
  4903. }
  4904. return $sFingerprint;
  4905. }
  4906. /**
  4907. * To expose internal values: Declare an attribute AttributeSubItem
  4908. * and implement the GetSubItemXXXX verbs
  4909. */
  4910. public function GetSubItemSQLExpression($sItemCode)
  4911. {
  4912. $sPrefix = $this->GetCode();
  4913. switch($sItemCode)
  4914. {
  4915. case 'timespent':
  4916. return array('' => $sPrefix.'_timespent');
  4917. case 'started':
  4918. return array('' => $sPrefix.'_started');
  4919. case 'laststart':
  4920. return array('' => $sPrefix.'_laststart');
  4921. case 'stopped':
  4922. return array('' => $sPrefix.'_stopped');
  4923. }
  4924. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4925. {
  4926. $sThPrefix = $iThreshold.'_';
  4927. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4928. {
  4929. // The current threshold is concerned
  4930. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4931. switch($sThresholdCode)
  4932. {
  4933. case 'deadline':
  4934. return array('' => $sPrefix.'_'.$iThreshold.'_deadline');
  4935. case 'passed':
  4936. return array('' => $sPrefix.'_'.$iThreshold.'_passed');
  4937. case 'triggered':
  4938. return array('' => $sPrefix.'_'.$iThreshold.'_triggered');
  4939. case 'overrun':
  4940. return array('' => $sPrefix.'_'.$iThreshold.'_overrun');
  4941. }
  4942. }
  4943. }
  4944. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  4945. }
  4946. public function GetSubItemValue($sItemCode, $value, $oHostObject = null)
  4947. {
  4948. $oStopWatch = $value;
  4949. switch($sItemCode)
  4950. {
  4951. case 'timespent':
  4952. return $oStopWatch->GetTimeSpent();
  4953. case 'started':
  4954. return $oStopWatch->GetStartDate();
  4955. case 'laststart':
  4956. return $oStopWatch->GetLastStartDate();
  4957. case 'stopped':
  4958. return $oStopWatch->GetStopDate();
  4959. }
  4960. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  4961. {
  4962. $sThPrefix = $iThreshold.'_';
  4963. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  4964. {
  4965. // The current threshold is concerned
  4966. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  4967. switch($sThresholdCode)
  4968. {
  4969. case 'deadline':
  4970. return $oStopWatch->GetThresholdDate($iThreshold);
  4971. case 'passed':
  4972. return $oStopWatch->IsThresholdPassed($iThreshold);
  4973. case 'triggered':
  4974. return $oStopWatch->IsThresholdTriggered($iThreshold);
  4975. case 'overrun':
  4976. return $oStopWatch->GetOverrun($iThreshold);
  4977. }
  4978. }
  4979. }
  4980. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  4981. }
  4982. protected function GetBooleanLabel($bValue)
  4983. {
  4984. $sDictKey = $bValue ? 'yes' : 'no';
  4985. return Dict::S('BooleanLabel:'.$sDictKey, 'def:'.$sDictKey);
  4986. }
  4987. public function GetSubItemAsHTMLForHistory($sItemCode, $sValue)
  4988. {
  4989. switch($sItemCode)
  4990. {
  4991. case 'timespent':
  4992. $sHtml = (int)$sValue ? Str::pure2html(AttributeDuration::FormatDuration($sValue)) : null;
  4993. break;
  4994. case 'started':
  4995. case 'laststart':
  4996. case 'stopped':
  4997. $sHtml = (int)$sValue ? date((string)AttributeDateTime::GetFormat(), (int)$sValue) : null;
  4998. break;
  4999. default:
  5000. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  5001. {
  5002. $sThPrefix = $iThreshold.'_';
  5003. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  5004. {
  5005. // The current threshold is concerned
  5006. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  5007. switch($sThresholdCode)
  5008. {
  5009. case 'deadline':
  5010. $sHtml = (int)$sValue ? date((string)AttributeDateTime::GetFormat(), (int)$sValue) : null;
  5011. break;
  5012. case 'passed':
  5013. $sHtml = $this->GetBooleanLabel((int)$sValue);
  5014. break;
  5015. case 'triggered':
  5016. $sHtml = $this->GetBooleanLabel((int)$sValue);
  5017. break;
  5018. case 'overrun':
  5019. $sHtml = (int)$sValue > 0 ? Str::pure2html(AttributeDuration::FormatDuration((int)$sValue)) : '';
  5020. }
  5021. }
  5022. }
  5023. }
  5024. return $sHtml;
  5025. }
  5026. public function GetSubItemAsPlainText($sItemCode, $value)
  5027. {
  5028. $sRet = $value;
  5029. switch ($sItemCode)
  5030. {
  5031. case 'timespent':
  5032. $sRet = AttributeDuration::FormatDuration($value);
  5033. break;
  5034. case 'started':
  5035. case 'laststart':
  5036. case 'stopped':
  5037. if (is_null($value))
  5038. {
  5039. $sRet = ''; // Undefined
  5040. }
  5041. else
  5042. {
  5043. $oDateTime = new DateTime();
  5044. $oDateTime->setTimestamp($value);
  5045. $oDateTimeFormat = AttributeDateTime::GetFormat();
  5046. $sRet = $oDateTimeFormat->Format($oDateTime);
  5047. }
  5048. break;
  5049. default:
  5050. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  5051. {
  5052. $sThPrefix = $iThreshold . '_';
  5053. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  5054. {
  5055. // The current threshold is concerned
  5056. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  5057. switch ($sThresholdCode)
  5058. {
  5059. case 'deadline':
  5060. if ($value)
  5061. {
  5062. $sDate = date(AttributeDateTime::GetInternalFormat(), $value);
  5063. $sRet = AttributeDeadline::FormatDeadline($sDate);
  5064. }
  5065. else
  5066. {
  5067. $sRet = '';
  5068. }
  5069. break;
  5070. case 'passed':
  5071. case 'triggered':
  5072. $sRet = $this->GetBooleanLabel($value);
  5073. break;
  5074. case 'overrun':
  5075. $sRet = AttributeDuration::FormatDuration($value);
  5076. break;
  5077. }
  5078. }
  5079. }
  5080. }
  5081. return $sRet;
  5082. }
  5083. public function GetSubItemAsHTML($sItemCode, $value)
  5084. {
  5085. $sHtml = $value;
  5086. switch ($sItemCode)
  5087. {
  5088. case 'timespent':
  5089. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  5090. break;
  5091. case 'started':
  5092. case 'laststart':
  5093. case 'stopped':
  5094. if (is_null($value))
  5095. {
  5096. $sHtml = ''; // Undefined
  5097. }
  5098. else
  5099. {
  5100. $oDateTime = new DateTime();
  5101. $oDateTime->setTimestamp($value);
  5102. $oDateTimeFormat = AttributeDateTime::GetFormat();
  5103. $sHtml = Str::pure2html($oDateTimeFormat->Format($oDateTime));
  5104. }
  5105. break;
  5106. default:
  5107. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  5108. {
  5109. $sThPrefix = $iThreshold . '_';
  5110. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  5111. {
  5112. // The current threshold is concerned
  5113. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  5114. switch ($sThresholdCode)
  5115. {
  5116. case 'deadline':
  5117. if ($value)
  5118. {
  5119. $sDate = date(AttributeDateTime::GetInternalFormat(), $value);
  5120. $sHtml = Str::pure2html(AttributeDeadline::FormatDeadline($sDate));
  5121. }
  5122. else
  5123. {
  5124. $sHtml = '';
  5125. }
  5126. break;
  5127. case 'passed':
  5128. case 'triggered':
  5129. $sHtml = $this->GetBooleanLabel($value);
  5130. break;
  5131. case 'overrun':
  5132. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  5133. break;
  5134. }
  5135. }
  5136. }
  5137. }
  5138. return $sHtml;
  5139. }
  5140. public function GetSubItemAsCSV($sItemCode, $value, $sSeparator = ',', $sTextQualifier = '"', $bConvertToPlainText = false)
  5141. {
  5142. $sFrom = array("\r\n", $sTextQualifier);
  5143. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5144. $sEscaped = str_replace($sFrom, $sTo, (string)$value);
  5145. $sRet = $sTextQualifier.$sEscaped.$sTextQualifier;
  5146. switch($sItemCode)
  5147. {
  5148. case 'timespent':
  5149. $sRet = $sTextQualifier . AttributeDuration::FormatDuration($value) . $sTextQualifier;
  5150. break;
  5151. case 'started':
  5152. case 'laststart':
  5153. case 'stopped':
  5154. if ($value !== null)
  5155. {
  5156. $oDateTime = new DateTime();
  5157. $oDateTime->setTimestamp($value);
  5158. $oDateTimeFormat = AttributeDateTime::GetFormat();
  5159. $sRet = $sTextQualifier . $oDateTimeFormat->Format($oDateTime) . $sTextQualifier;
  5160. }
  5161. break;
  5162. default:
  5163. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  5164. {
  5165. $sThPrefix = $iThreshold.'_';
  5166. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  5167. {
  5168. // The current threshold is concerned
  5169. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  5170. switch($sThresholdCode)
  5171. {
  5172. case 'deadline':
  5173. if ($value != '')
  5174. {
  5175. $oDateTime = new DateTime();
  5176. $oDateTime->setTimestamp($value);
  5177. $oDateTimeFormat = AttributeDateTime::GetFormat();
  5178. $sRet = $sTextQualifier . $oDateTimeFormat->Format($oDateTime) . $sTextQualifier;
  5179. }
  5180. break;
  5181. case 'passed':
  5182. case 'triggered':
  5183. $sRet = $sTextQualifier . $this->GetBooleanLabel($value) . $sTextQualifier;
  5184. break;
  5185. case 'overrun':
  5186. $sRet = $sTextQualifier . AttributeDuration::FormatDuration($value) . $sTextQualifier;
  5187. break;
  5188. }
  5189. }
  5190. }
  5191. }
  5192. return $sRet;
  5193. }
  5194. public function GetSubItemAsXML($sItemCode, $value)
  5195. {
  5196. $sRet = Str::pure2xml((string)$value);
  5197. switch($sItemCode)
  5198. {
  5199. case 'timespent':
  5200. case 'started':
  5201. case 'laststart':
  5202. case 'stopped':
  5203. break;
  5204. default:
  5205. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  5206. {
  5207. $sThPrefix = $iThreshold.'_';
  5208. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  5209. {
  5210. // The current threshold is concerned
  5211. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  5212. switch($sThresholdCode)
  5213. {
  5214. case 'deadline':
  5215. break;
  5216. case 'passed':
  5217. case 'triggered':
  5218. $sRet = $this->GetBooleanLabel($value);
  5219. break;
  5220. case 'overrun':
  5221. break;
  5222. }
  5223. }
  5224. }
  5225. }
  5226. return $sRet;
  5227. }
  5228. /**
  5229. * Implemented for the HTML spreadsheet format!
  5230. */
  5231. public function GetSubItemAsEditValue($sItemCode, $value)
  5232. {
  5233. $sRet = $value;
  5234. switch($sItemCode)
  5235. {
  5236. case 'timespent':
  5237. break;
  5238. case 'started':
  5239. case 'laststart':
  5240. case 'stopped':
  5241. if (is_null($value))
  5242. {
  5243. $sRet = ''; // Undefined
  5244. }
  5245. else
  5246. {
  5247. $sRet = date((string)AttributeDateTime::GetFormat(), $value);
  5248. }
  5249. break;
  5250. default:
  5251. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  5252. {
  5253. $sThPrefix = $iThreshold.'_';
  5254. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  5255. {
  5256. // The current threshold is concerned
  5257. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  5258. switch($sThresholdCode)
  5259. {
  5260. case 'deadline':
  5261. if ($value)
  5262. {
  5263. $sRet = date((string)AttributeDateTime::GetFormat(), $value);
  5264. }
  5265. else
  5266. {
  5267. $sRet = '';
  5268. }
  5269. break;
  5270. case 'passed':
  5271. case 'triggered':
  5272. $sRet = $this->GetBooleanLabel($value);
  5273. break;
  5274. case 'overrun':
  5275. break;
  5276. }
  5277. }
  5278. }
  5279. }
  5280. return $sRet;
  5281. }
  5282. }
  5283. /**
  5284. * View of a subvalue of another attribute
  5285. * If an attribute implements the verbs GetSubItem.... then it can expose
  5286. * internal values, each of them being an attribute and therefore they
  5287. * can be displayed at different times in the object lifecycle, and used for
  5288. * reporting (as a condition in OQL, or as an additional column in an export)
  5289. * Known usages: Stop Watches can expose threshold statuses
  5290. */
  5291. class AttributeSubItem extends AttributeDefinition
  5292. {
  5293. static public function ListExpectedParams()
  5294. {
  5295. return array_merge(parent::ListExpectedParams(), array('target_attcode', 'item_code'));
  5296. }
  5297. public function GetParentAttCode() {return $this->Get("target_attcode");}
  5298. /**
  5299. * Helper : get the attribute definition to which the execution will be forwarded
  5300. */
  5301. public function GetTargetAttDef()
  5302. {
  5303. $sClass = $this->GetHostClass();
  5304. $oParentAttDef = MetaModel::GetAttributeDef($sClass, $this->Get('target_attcode'));
  5305. return $oParentAttDef;
  5306. }
  5307. public function GetEditClass() {return "";}
  5308. public function GetValuesDef() {return null;}
  5309. public function IsDirectField() {return true;}
  5310. public function IsScalar() {return true;}
  5311. public function IsWritable() {return false;}
  5312. public function GetDefaultValue(DBObject $oHostObject = null) {return null;}
  5313. // public function IsNullAllowed() {return false;}
  5314. public function LoadInObject() {return false;} // if this verb returns false, then GetValue must be implemented
  5315. /**
  5316. * Used by DBOBject::Get()
  5317. */
  5318. public function GetValue($oHostObject)
  5319. {
  5320. $oParent = $this->GetTargetAttDef();
  5321. $parentValue = $oHostObject->GetStrict($oParent->GetCode());
  5322. $res = $oParent->GetSubItemValue($this->Get('item_code'), $parentValue, $oHostObject);
  5323. return $res;
  5324. }
  5325. //
  5326. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  5327. public function FromSQLToValue($aCols, $sPrefix = '')
  5328. {
  5329. }
  5330. public function GetSQLColumns($bFullSpec = false)
  5331. {
  5332. return array();
  5333. }
  5334. public function GetFilterDefinitions()
  5335. {
  5336. return array($this->GetCode() => new FilterFromAttribute($this));
  5337. }
  5338. public function GetBasicFilterOperators()
  5339. {
  5340. return array();
  5341. }
  5342. public function GetBasicFilterLooseOperator()
  5343. {
  5344. return "=";
  5345. }
  5346. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5347. {
  5348. $sQValue = CMDBSource::Quote($value);
  5349. switch ($sOpCode)
  5350. {
  5351. case '!=':
  5352. return $this->GetSQLExpr()." != $sQValue";
  5353. break;
  5354. case '=':
  5355. default:
  5356. return $this->GetSQLExpr()." = $sQValue";
  5357. }
  5358. }
  5359. public function GetSQLExpressions($sPrefix = '')
  5360. {
  5361. $oParent = $this->GetTargetAttDef();
  5362. $res = $oParent->GetSubItemSQLExpression($this->Get('item_code'));
  5363. return $res;
  5364. }
  5365. public function GetAsPlainText($value, $oHostObject = null, $bLocalize = true)
  5366. {
  5367. $oParent = $this->GetTargetAttDef();
  5368. $res = $oParent->GetSubItemAsPlainText($this->Get('item_code'), $value);
  5369. return $res;
  5370. }
  5371. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5372. {
  5373. $oParent = $this->GetTargetAttDef();
  5374. $res = $oParent->GetSubItemAsHTML($this->Get('item_code'), $value);
  5375. return $res;
  5376. }
  5377. public function GetAsHTMLForHistory($value, $oHostObject = null, $bLocalize = true)
  5378. {
  5379. $oParent = $this->GetTargetAttDef();
  5380. $res = $oParent->GetSubItemAsHTMLForHistory($this->Get('item_code'), $value);
  5381. return $res;
  5382. }
  5383. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5384. {
  5385. $oParent = $this->GetTargetAttDef();
  5386. $res = $oParent->GetSubItemAsCSV($this->Get('item_code'), $value, $sSeparator, $sTextQualifier, $bConvertToPlainText);
  5387. return $res;
  5388. }
  5389. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5390. {
  5391. $oParent = $this->GetTargetAttDef();
  5392. $res = $oParent->GetSubItemAsXML($this->Get('item_code'), $value);
  5393. return $res;
  5394. }
  5395. /**
  5396. * As of now, this function must be implemented to have the value in spreadsheet format
  5397. */
  5398. public function GetEditValue($value, $oHostObj = null)
  5399. {
  5400. $oParent = $this->GetTargetAttDef();
  5401. $res = $oParent->GetSubItemAsEditValue($this->Get('item_code'), $value);
  5402. return $res;
  5403. }
  5404. public function IsPartOfFingerprint()
  5405. {
  5406. return false;
  5407. }
  5408. static public function GetFormFieldClass()
  5409. {
  5410. return '\\Combodo\\iTop\\Form\\Field\\LabelField';
  5411. }
  5412. public function MakeFormField(DBObject $oObject, $oFormField = null)
  5413. {
  5414. if ($oFormField === null)
  5415. {
  5416. $sFormFieldClass = static::GetFormFieldClass();
  5417. $oFormField = new $sFormFieldClass($this->GetCode());
  5418. }
  5419. parent::MakeFormField($oObject, $oFormField);
  5420. // Note : As of today, this attribute is -by nature- only supported in readonly mode, not edition
  5421. $sAttCode = $this->GetCode();
  5422. $oFormField->SetCurrentValue(html_entity_decode($oObject->GetAsHTML($sAttCode), ENT_QUOTES, 'UTF-8'));
  5423. $oFormField->SetReadOnly(true);
  5424. return $oFormField;
  5425. }
  5426. }
  5427. /**
  5428. * One way encrypted (hashed) password
  5429. */
  5430. class AttributeOneWayPassword extends AttributeDefinition
  5431. {
  5432. static public function ListExpectedParams()
  5433. {
  5434. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  5435. }
  5436. public function GetEditClass() {return "One Way Password";}
  5437. public function IsDirectField() {return true;}
  5438. public function IsScalar() {return true;}
  5439. public function IsWritable() {return true;}
  5440. public function GetDefaultValue(DBObject $oHostObject = null) {return "";}
  5441. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  5442. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  5443. public function MakeRealValue($proposedValue, $oHostObj)
  5444. {
  5445. $oPassword = $proposedValue;
  5446. if (!is_object($oPassword))
  5447. {
  5448. $oPassword = new ormPassword('', '');
  5449. $oPassword->SetPassword($proposedValue);
  5450. }
  5451. return $oPassword;
  5452. }
  5453. public function GetSQLExpressions($sPrefix = '')
  5454. {
  5455. if ($sPrefix == '')
  5456. {
  5457. $sPrefix = $this->GetCode(); // Warning: AttributeOneWayPassword does not have any sql property so code = sql !
  5458. }
  5459. $aColumns = array();
  5460. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  5461. $aColumns[''] = $sPrefix.'_hash';
  5462. $aColumns['_salt'] = $sPrefix.'_salt';
  5463. return $aColumns;
  5464. }
  5465. public function FromSQLToValue($aCols, $sPrefix = '')
  5466. {
  5467. if (!array_key_exists($sPrefix, $aCols))
  5468. {
  5469. $sAvailable = implode(', ', array_keys($aCols));
  5470. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  5471. }
  5472. $hashed = isset($aCols[$sPrefix]) ? $aCols[$sPrefix] : '';
  5473. if (!array_key_exists($sPrefix.'_salt', $aCols))
  5474. {
  5475. $sAvailable = implode(', ', array_keys($aCols));
  5476. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  5477. }
  5478. $sSalt = isset($aCols[$sPrefix.'_salt']) ? $aCols[$sPrefix.'_salt'] : '';
  5479. $value = new ormPassword($hashed, $sSalt);
  5480. return $value;
  5481. }
  5482. public function GetSQLValues($value)
  5483. {
  5484. // #@# Optimization: do not load blobs anytime
  5485. // As per mySQL doc, selecting blob columns will prevent mySQL from
  5486. // using memory in case a temporary table has to be created
  5487. // (temporary tables created on disk)
  5488. // We will have to remove the blobs from the list of attributes when doing the select
  5489. // then the use of Get() should finalize the load
  5490. if ($value instanceOf ormPassword)
  5491. {
  5492. $aValues = array();
  5493. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  5494. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  5495. }
  5496. else
  5497. {
  5498. $aValues = array();
  5499. $aValues[$this->GetCode().'_hash'] = '';
  5500. $aValues[$this->GetCode().'_salt'] = '';
  5501. }
  5502. return $aValues;
  5503. }
  5504. public function GetSQLColumns($bFullSpec = false)
  5505. {
  5506. $aColumns = array();
  5507. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  5508. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  5509. return $aColumns;
  5510. }
  5511. public function GetImportColumns()
  5512. {
  5513. $aColumns = array();
  5514. $aColumns[$this->GetCode()] = 'TINYTEXT';
  5515. return $aColumns;
  5516. }
  5517. public function FromImportToValue($aCols, $sPrefix = '')
  5518. {
  5519. if (!isset($aCols[$sPrefix]))
  5520. {
  5521. $sAvailable = implode(', ', array_keys($aCols));
  5522. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  5523. }
  5524. $sClearPwd = $aCols[$sPrefix];
  5525. $oPassword = new ormPassword('', '');
  5526. $oPassword->SetPassword($sClearPwd);
  5527. return $oPassword;
  5528. }
  5529. public function GetFilterDefinitions()
  5530. {
  5531. return array();
  5532. // still not working... see later...
  5533. }
  5534. public function GetBasicFilterOperators()
  5535. {
  5536. return array();
  5537. }
  5538. public function GetBasicFilterLooseOperator()
  5539. {
  5540. return '=';
  5541. }
  5542. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5543. {
  5544. return 'true';
  5545. }
  5546. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5547. {
  5548. if (is_object($value))
  5549. {
  5550. return $value->GetAsHTML();
  5551. }
  5552. }
  5553. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5554. {
  5555. return ''; // Not exportable in CSV
  5556. }
  5557. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5558. {
  5559. return ''; // Not exportable in XML
  5560. }
  5561. public function GetValueLabel($sValue, $oHostObj = null)
  5562. {
  5563. // Don't display anything in "group by" reports
  5564. return '*****';
  5565. }
  5566. }
  5567. // Indexed array having two dimensions
  5568. class AttributeTable extends AttributeDBField
  5569. {
  5570. public function GetEditClass() {return "Table";}
  5571. protected function GetSQLCol($bFullSpec = false) {return "LONGTEXT";}
  5572. public function GetMaxSize()
  5573. {
  5574. return null;
  5575. }
  5576. public function GetNullValue()
  5577. {
  5578. return array();
  5579. }
  5580. public function IsNull($proposedValue)
  5581. {
  5582. return (count($proposedValue) == 0);
  5583. }
  5584. public function GetEditValue($sValue, $oHostObj = null)
  5585. {
  5586. return '';
  5587. }
  5588. // Facilitate things: allow the user to Set the value from a string
  5589. public function MakeRealValue($proposedValue, $oHostObj)
  5590. {
  5591. if (is_null($proposedValue))
  5592. {
  5593. return array();
  5594. }
  5595. else if (!is_array($proposedValue))
  5596. {
  5597. return array(0 => array(0 => $proposedValue));
  5598. }
  5599. return $proposedValue;
  5600. }
  5601. public function FromSQLToValue($aCols, $sPrefix = '')
  5602. {
  5603. try
  5604. {
  5605. $value = @unserialize($aCols[$sPrefix.'']);
  5606. if ($value === false)
  5607. {
  5608. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  5609. }
  5610. }
  5611. catch(Exception $e)
  5612. {
  5613. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  5614. }
  5615. return $value;
  5616. }
  5617. public function GetSQLValues($value)
  5618. {
  5619. $aValues = array();
  5620. $aValues[$this->Get("sql")] = serialize($value);
  5621. return $aValues;
  5622. }
  5623. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5624. {
  5625. if (!is_array($value))
  5626. {
  5627. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  5628. }
  5629. if (count($value) == 0)
  5630. {
  5631. return "";
  5632. }
  5633. $sRes = "<TABLE class=\"listResults\">";
  5634. $sRes .= "<TBODY>";
  5635. foreach($value as $iRow => $aRawData)
  5636. {
  5637. $sRes .= "<TR>";
  5638. foreach ($aRawData as $iCol => $cell)
  5639. {
  5640. // Note: avoid the warning in case the cell is made of an array
  5641. $sCell = @Str::pure2html((string)$cell);
  5642. $sCell = str_replace("\n", "<br>\n", $sCell);
  5643. $sRes .= "<TD>$sCell</TD>";
  5644. }
  5645. $sRes .= "</TR>";
  5646. }
  5647. $sRes .= "</TBODY>";
  5648. $sRes .= "</TABLE>";
  5649. return $sRes;
  5650. }
  5651. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5652. {
  5653. // Not implemented
  5654. return '';
  5655. }
  5656. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5657. {
  5658. if (count($value) == 0)
  5659. {
  5660. return "";
  5661. }
  5662. $sRes = "";
  5663. foreach($value as $iRow => $aRawData)
  5664. {
  5665. $sRes .= "<row>";
  5666. foreach ($aRawData as $iCol => $cell)
  5667. {
  5668. $sCell = Str::pure2xml((string)$cell);
  5669. $sRes .= "<cell icol=\"$iCol\">$sCell</cell>";
  5670. }
  5671. $sRes .= "</row>";
  5672. }
  5673. return $sRes;
  5674. }
  5675. }
  5676. // The PHP value is a hash array, it is stored as a TEXT column
  5677. class AttributePropertySet extends AttributeTable
  5678. {
  5679. public function GetEditClass() {return "PropertySet";}
  5680. // Facilitate things: allow the user to Set the value from a string
  5681. public function MakeRealValue($proposedValue, $oHostObj)
  5682. {
  5683. if (!is_array($proposedValue))
  5684. {
  5685. return array('?' => (string)$proposedValue);
  5686. }
  5687. return $proposedValue;
  5688. }
  5689. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  5690. {
  5691. if (!is_array($value))
  5692. {
  5693. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  5694. }
  5695. if (count($value) == 0)
  5696. {
  5697. return "";
  5698. }
  5699. $sRes = "<TABLE class=\"listResults\">";
  5700. $sRes .= "<TBODY>";
  5701. foreach($value as $sProperty => $sValue)
  5702. {
  5703. if ($sProperty == 'auth_pwd')
  5704. {
  5705. $sValue = '*****';
  5706. }
  5707. $sRes .= "<TR>";
  5708. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  5709. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  5710. $sRes .= "</TR>";
  5711. }
  5712. $sRes .= "</TBODY>";
  5713. $sRes .= "</TABLE>";
  5714. return $sRes;
  5715. }
  5716. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5717. {
  5718. if (count($value) == 0)
  5719. {
  5720. return "";
  5721. }
  5722. $aRes = array();
  5723. foreach($value as $sProperty => $sValue)
  5724. {
  5725. if ($sProperty == 'auth_pwd')
  5726. {
  5727. $sValue = '*****';
  5728. }
  5729. $sFrom = array(',', '=');
  5730. $sTo = array('\,', '\=');
  5731. $aRes[] = $sProperty.'='.str_replace($sFrom, $sTo, (string)$sValue);
  5732. }
  5733. $sRaw = implode(',', $aRes);
  5734. $sFrom = array("\r\n", $sTextQualifier);
  5735. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5736. $sEscaped = str_replace($sFrom, $sTo, $sRaw);
  5737. return $sTextQualifier.$sEscaped.$sTextQualifier;
  5738. }
  5739. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  5740. {
  5741. if (count($value) == 0)
  5742. {
  5743. return "";
  5744. }
  5745. $sRes = "";
  5746. foreach($value as $sProperty => $sValue)
  5747. {
  5748. if ($sProperty == 'auth_pwd')
  5749. {
  5750. $sValue = '*****';
  5751. }
  5752. $sRes .= "<property id=\"$sProperty\">";
  5753. $sRes .= Str::pure2xml((string)$sValue);
  5754. $sRes .= "</property>";
  5755. }
  5756. return $sRes;
  5757. }
  5758. }
  5759. /**
  5760. * The attribute dedicated to the friendly name automatic attribute (not written)
  5761. *
  5762. * @package iTopORM
  5763. */
  5764. class AttributeComputedFieldVoid extends AttributeDefinition
  5765. {
  5766. static public function ListExpectedParams()
  5767. {
  5768. return array_merge(parent::ListExpectedParams(), array());
  5769. }
  5770. public function GetEditClass() {return "";}
  5771. public function GetValuesDef() {return null;}
  5772. public function GetPrerequisiteAttributes($sClass = null) {return $this->GetOptional("depends_on", array());}
  5773. public function IsDirectField() {return true;}
  5774. public function IsScalar() {return true;}
  5775. public function IsWritable() {return false;}
  5776. public function GetSQLExpr()
  5777. {
  5778. return null;
  5779. }
  5780. public function GetDefaultValue(DBObject $oHostObject = null) {return $this->MakeRealValue("", $oHostObject);}
  5781. public function IsNullAllowed() {return false;}
  5782. //
  5783. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  5784. public function GetSQLExpressions($sPrefix = '')
  5785. {
  5786. if ($sPrefix == '')
  5787. {
  5788. $sPrefix = $this->GetCode(); // Warning AttributeComputedFieldVoid does not have any sql property
  5789. }
  5790. return array('' => $sPrefix);
  5791. }
  5792. public function FromSQLToValue($aCols, $sPrefix = '')
  5793. {
  5794. return null;
  5795. }
  5796. public function GetSQLValues($value)
  5797. {
  5798. return array();
  5799. }
  5800. public function GetSQLColumns($bFullSpec = false)
  5801. {
  5802. return array();
  5803. }
  5804. public function GetFilterDefinitions()
  5805. {
  5806. return array($this->GetCode() => new FilterFromAttribute($this));
  5807. }
  5808. public function GetBasicFilterOperators()
  5809. {
  5810. return array("="=>"equals", "!="=>"differs from");
  5811. }
  5812. public function GetBasicFilterLooseOperator()
  5813. {
  5814. return "=";
  5815. }
  5816. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5817. {
  5818. $sQValue = CMDBSource::Quote($value);
  5819. switch ($sOpCode)
  5820. {
  5821. case '!=':
  5822. return $this->GetSQLExpr()." != $sQValue";
  5823. break;
  5824. case '=':
  5825. default:
  5826. return $this->GetSQLExpr()." = $sQValue";
  5827. }
  5828. }
  5829. public function IsPartOfFingerprint() { return false; }
  5830. }
  5831. /**
  5832. * The attribute dedicated to the friendly name automatic attribute (not written)
  5833. *
  5834. * @package iTopORM
  5835. */
  5836. class AttributeFriendlyName extends AttributeComputedFieldVoid
  5837. {
  5838. public function __construct($sCode, $sExtKeyAttCode)
  5839. {
  5840. $this->m_sCode = $sCode;
  5841. $aParams = array();
  5842. // $aParams["is_null_allowed"] = false,
  5843. $aParams["default_value"] = '';
  5844. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  5845. parent::__construct($sCode, $aParams);
  5846. $this->m_sValue = $this->Get("default_value");
  5847. }
  5848. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  5849. public function GetExtAttCode() {return 'friendlyname';}
  5850. public function GetLabel($sDefault = null)
  5851. {
  5852. $sLabel = parent::GetLabel('');
  5853. if (strlen($sLabel) == 0)
  5854. {
  5855. $sKeyAttCode = $this->Get("extkey_attcode");
  5856. if ($sKeyAttCode == 'id')
  5857. {
  5858. return Dict::S('Core:FriendlyName-Label');
  5859. }
  5860. else
  5861. {
  5862. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  5863. $sLabel = $oExtKeyAttDef->GetLabel($this->m_sCode);
  5864. }
  5865. }
  5866. return $sLabel;
  5867. }
  5868. public function GetDescription($sDefault = null)
  5869. {
  5870. $sLabel = parent::GetDescription('');
  5871. if (strlen($sLabel) == 0)
  5872. {
  5873. $sKeyAttCode = $this->Get("extkey_attcode");
  5874. if ($sKeyAttCode == 'id')
  5875. {
  5876. return Dict::S('Core:FriendlyName-Description');
  5877. }
  5878. else
  5879. {
  5880. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  5881. $sLabel = $oExtKeyAttDef->GetDescription('');
  5882. }
  5883. }
  5884. return $sLabel;
  5885. }
  5886. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  5887. protected function GetSQLCol($bFullSpec = false) {return "";}
  5888. public function FromSQLToValue($aCols, $sPrefix = '')
  5889. {
  5890. $sValue = $aCols[$sPrefix];
  5891. return $sValue;
  5892. }
  5893. /**
  5894. * Encrypt the value before storing it in the database
  5895. */
  5896. public function GetSQLValues($value)
  5897. {
  5898. return array();
  5899. }
  5900. public function IsWritable()
  5901. {
  5902. return false;
  5903. }
  5904. public function IsDirectField()
  5905. {
  5906. return false;
  5907. }
  5908. public function SetFixedValue($sValue)
  5909. {
  5910. $this->m_sValue = $sValue;
  5911. }
  5912. public function GetDefaultValue(DBObject $oHostObject = null)
  5913. {
  5914. return $this->m_sValue;
  5915. }
  5916. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  5917. {
  5918. return Str::pure2html((string)$sValue);
  5919. }
  5920. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  5921. {
  5922. $sFrom = array("\r\n", $sTextQualifier);
  5923. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  5924. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  5925. return $sTextQualifier.$sEscaped.$sTextQualifier;
  5926. }
  5927. static function GetFormFieldClass()
  5928. {
  5929. return '\\Combodo\\iTop\\Form\\Field\\StringField';
  5930. }
  5931. public function MakeFormField(DBObject $oObject, $oFormField = null)
  5932. {
  5933. if ($oFormField === null)
  5934. {
  5935. $sFormFieldClass = static::GetFormFieldClass();
  5936. $oFormField = new $sFormFieldClass($this->GetCode());
  5937. }
  5938. $oFormField->SetReadOnly(true);
  5939. parent::MakeFormField($oObject, $oFormField);
  5940. return $oFormField;
  5941. }
  5942. // Do not display friendly names in the history of change
  5943. public function DescribeChangeAsHTML($sOldValue, $sNewValue, $sLabel = null)
  5944. {
  5945. return '';
  5946. }
  5947. public function GetBasicFilterLooseOperator()
  5948. {
  5949. return "Contains";
  5950. }
  5951. public function GetBasicFilterSQLExpr($sOpCode, $value)
  5952. {
  5953. $sQValue = CMDBSource::Quote($value);
  5954. switch ($sOpCode)
  5955. {
  5956. case '=':
  5957. case '!=':
  5958. return $this->GetSQLExpr()." $sOpCode $sQValue";
  5959. case 'Contains':
  5960. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  5961. case 'NotLike':
  5962. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  5963. case 'Like':
  5964. default:
  5965. return $this->GetSQLExpr()." LIKE $sQValue";
  5966. }
  5967. }
  5968. public function IsPartOfFingerprint() { return false; }
  5969. }
  5970. /**
  5971. * Holds the setting for the redundancy on a specific relation
  5972. * Its value is a string, containing either:
  5973. * - 'disabled'
  5974. * - 'n', where n is a positive integer value giving the minimum count of items upstream
  5975. * - 'n%', where n is a positive integer value, giving the minimum as a percentage of the total count of items upstream
  5976. *
  5977. * @package iTopORM
  5978. */
  5979. class AttributeRedundancySettings extends AttributeDBField
  5980. {
  5981. static public function ListExpectedParams()
  5982. {
  5983. return array('sql', 'relation_code', 'from_class', 'neighbour_id', 'enabled', 'enabled_mode', 'min_up', 'min_up_type', 'min_up_mode');
  5984. }
  5985. public function GetValuesDef() {return null;}
  5986. public function GetPrerequisiteAttributes($sClass = null) {return array();}
  5987. public function GetEditClass() {return "RedundancySetting";}
  5988. protected function GetSQLCol($bFullSpec = false)
  5989. {
  5990. return "VARCHAR(20)".($bFullSpec ? $this->GetSQLColSpec() : '');
  5991. }
  5992. public function GetValidationPattern()
  5993. {
  5994. return "^[0-9]{1,3}|[0-9]{1,2}%|disabled$";
  5995. }
  5996. public function GetMaxSize()
  5997. {
  5998. return 20;
  5999. }
  6000. public function GetDefaultValue(DBObject $oHostObject = null)
  6001. {
  6002. $sRet = 'disabled';
  6003. if ($this->Get('enabled'))
  6004. {
  6005. if ($this->Get('min_up_type') == 'count')
  6006. {
  6007. $sRet = (string) $this->Get('min_up');
  6008. }
  6009. else // percent
  6010. {
  6011. $sRet = $this->Get('min_up').'%';
  6012. }
  6013. }
  6014. return $sRet;
  6015. }
  6016. public function IsNullAllowed()
  6017. {
  6018. return false;
  6019. }
  6020. public function GetNullValue()
  6021. {
  6022. return '';
  6023. }
  6024. public function IsNull($proposedValue)
  6025. {
  6026. return ($proposedValue == '');
  6027. }
  6028. public function MakeRealValue($proposedValue, $oHostObj)
  6029. {
  6030. if (is_null($proposedValue)) return '';
  6031. return (string)$proposedValue;
  6032. }
  6033. public function ScalarToSQL($value)
  6034. {
  6035. if (!is_string($value))
  6036. {
  6037. throw new CoreException('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetHostClass(), 'attribute' => $this->GetCode()));
  6038. }
  6039. return $value;
  6040. }
  6041. public function GetRelationQueryData()
  6042. {
  6043. foreach (MetaModel::EnumRelationQueries($this->GetHostClass(), $this->Get('relation_code'), false) as $sDummy => $aQueryInfo)
  6044. {
  6045. if ($aQueryInfo['sFromClass'] == $this->Get('from_class'))
  6046. {
  6047. if ($aQueryInfo['sNeighbour'] == $this->Get('neighbour_id'))
  6048. {
  6049. return $aQueryInfo;
  6050. }
  6051. }
  6052. }
  6053. }
  6054. /**
  6055. * Find the user option label
  6056. * @param user option : disabled|cout|percent
  6057. */
  6058. public function GetUserOptionFormat($sUserOption, $sDefault = null)
  6059. {
  6060. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, null, true /*user lang*/);
  6061. if (is_null($sLabel))
  6062. {
  6063. // If no default value is specified, let's define the most relevant one for developping purposes
  6064. if (is_null($sDefault))
  6065. {
  6066. $sDefault = str_replace('_', ' ', $this->m_sCode.':'.$sUserOption.'(%1$s)');
  6067. }
  6068. // Browse the hierarchy again, accepting default (english) translations
  6069. $sLabel = $this->SearchLabel('/Attribute:'.$this->m_sCode.'/'.$sUserOption, $sDefault, false);
  6070. }
  6071. return $sLabel;
  6072. }
  6073. /**
  6074. * Override to display the value in the GUI
  6075. */
  6076. public function GetAsHTML($sValue, $oHostObject = null, $bLocalize = true)
  6077. {
  6078. $sCurrentOption = $this->GetCurrentOption($sValue);
  6079. $sClass = $oHostObject ? get_class($oHostObject) : $this->m_sHostClass;
  6080. return sprintf($this->GetUserOptionFormat($sCurrentOption), $this->GetMinUpValue($sValue), MetaModel::GetName($sClass));
  6081. }
  6082. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  6083. {
  6084. $sFrom = array("\r\n", $sTextQualifier);
  6085. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  6086. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  6087. return $sTextQualifier.$sEscaped.$sTextQualifier;
  6088. }
  6089. /**
  6090. * Helper to interpret the value, given the current settings and string representation of the attribute
  6091. */
  6092. public function IsEnabled($sValue)
  6093. {
  6094. if ($this->get('enabled_mode') == 'fixed')
  6095. {
  6096. $bRet = $this->get('enabled');
  6097. }
  6098. else
  6099. {
  6100. $bRet = ($sValue != 'disabled');
  6101. }
  6102. return $bRet;
  6103. }
  6104. /**
  6105. * Helper to interpret the value, given the current settings and string representation of the attribute
  6106. */
  6107. public function GetMinUpType($sValue)
  6108. {
  6109. if ($this->get('min_up_mode') == 'fixed')
  6110. {
  6111. $sRet = $this->get('min_up_type');
  6112. }
  6113. else
  6114. {
  6115. $sRet = 'count';
  6116. if (substr(trim($sValue), -1, 1) == '%')
  6117. {
  6118. $sRet = 'percent';
  6119. }
  6120. }
  6121. return $sRet;
  6122. }
  6123. /**
  6124. * Helper to interpret the value, given the current settings and string representation of the attribute
  6125. */
  6126. public function GetMinUpValue($sValue)
  6127. {
  6128. if ($this->get('min_up_mode') == 'fixed')
  6129. {
  6130. $iRet = (int) $this->Get('min_up');
  6131. }
  6132. else
  6133. {
  6134. $sRefValue = $sValue;
  6135. if (substr(trim($sValue), -1, 1) == '%')
  6136. {
  6137. $sRefValue = substr(trim($sValue), 0, -1);
  6138. }
  6139. $iRet = (int) trim($sRefValue);
  6140. }
  6141. return $iRet;
  6142. }
  6143. /**
  6144. * Helper to determine if the redundancy can be viewed/edited by the end-user
  6145. */
  6146. public function IsVisible()
  6147. {
  6148. $bRet = false;
  6149. if ($this->Get('enabled_mode') == 'fixed')
  6150. {
  6151. $bRet = $this->Get('enabled');
  6152. }
  6153. elseif ($this->Get('enabled_mode') == 'user')
  6154. {
  6155. $bRet = true;
  6156. }
  6157. return $bRet;
  6158. }
  6159. public function IsWritable()
  6160. {
  6161. if (($this->Get('enabled_mode') == 'fixed') && ($this->Get('min_up_mode') == 'fixed'))
  6162. {
  6163. return false;
  6164. }
  6165. return true;
  6166. }
  6167. /**
  6168. * Returns an HTML form that can be read by ReadValueFromPostedForm
  6169. */
  6170. public function GetDisplayForm($sCurrentValue, $oPage, $bEditMode = false, $sFormPrefix = '')
  6171. {
  6172. $sRet = '';
  6173. $aUserOptions = $this->GetUserOptions($sCurrentValue);
  6174. if (count($aUserOptions) < 2)
  6175. {
  6176. $bEditOption = false;
  6177. }
  6178. else
  6179. {
  6180. $bEditOption = $bEditMode;
  6181. }
  6182. $sCurrentOption = $this->GetCurrentOption($sCurrentValue);
  6183. foreach($aUserOptions as $sUserOption)
  6184. {
  6185. $bSelected = ($sUserOption == $sCurrentOption);
  6186. $sRet .= '<div>';
  6187. $sRet .= $this->GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditOption, $sUserOption, $bSelected);
  6188. $sRet .= '</div>';
  6189. }
  6190. return $sRet;
  6191. }
  6192. const USER_OPTION_DISABLED = 'disabled';
  6193. const USER_OPTION_ENABLED_COUNT = 'count';
  6194. const USER_OPTION_ENABLED_PERCENT = 'percent';
  6195. /**
  6196. * Depending on the xxx_mode parameters, build the list of options that are allowed to the end-user
  6197. */
  6198. protected function GetUserOptions($sValue)
  6199. {
  6200. $aRet = array();
  6201. if ($this->Get('enabled_mode') == 'user')
  6202. {
  6203. $aRet[] = self::USER_OPTION_DISABLED;
  6204. }
  6205. if ($this->Get('min_up_mode') == 'user')
  6206. {
  6207. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  6208. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  6209. }
  6210. else
  6211. {
  6212. if ($this->GetMinUpType($sValue) == 'count')
  6213. {
  6214. $aRet[] = self::USER_OPTION_ENABLED_COUNT;
  6215. }
  6216. else
  6217. {
  6218. $aRet[] = self::USER_OPTION_ENABLED_PERCENT;
  6219. }
  6220. }
  6221. return $aRet;
  6222. }
  6223. /**
  6224. * Convert the string representation into one of the existing options
  6225. */
  6226. protected function GetCurrentOption($sValue)
  6227. {
  6228. $sRet = self::USER_OPTION_DISABLED;
  6229. if ($this->IsEnabled($sValue))
  6230. {
  6231. if ($this->GetMinUpType($sValue) == 'count')
  6232. {
  6233. $sRet = self::USER_OPTION_ENABLED_COUNT;
  6234. }
  6235. else
  6236. {
  6237. $sRet = self::USER_OPTION_ENABLED_PERCENT;
  6238. }
  6239. }
  6240. return $sRet;
  6241. }
  6242. /**
  6243. * Display an option (form, or current value)
  6244. */
  6245. protected function GetDisplayOption($sCurrentValue, $oPage, $sFormPrefix, $bEditMode, $sUserOption, $bSelected = true)
  6246. {
  6247. $sRet = '';
  6248. $iCurrentValue = $this->GetMinUpValue($sCurrentValue);
  6249. if ($bEditMode)
  6250. {
  6251. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  6252. switch ($sUserOption)
  6253. {
  6254. case self::USER_OPTION_DISABLED:
  6255. $sValue = ''; // Empty placeholder
  6256. break;
  6257. case self::USER_OPTION_ENABLED_COUNT:
  6258. if ($bEditMode)
  6259. {
  6260. $sName = $sHtmlNamesPrefix.'_min_up_count';
  6261. $sEditValue = $bSelected ? $iCurrentValue : '';
  6262. $sValue = '<input class="redundancy-min-up-count" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  6263. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  6264. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  6265. }
  6266. else
  6267. {
  6268. $sValue = $iCurrentValue;
  6269. }
  6270. break;
  6271. case self::USER_OPTION_ENABLED_PERCENT:
  6272. if ($bEditMode)
  6273. {
  6274. $sName = $sHtmlNamesPrefix.'_min_up_percent';
  6275. $sEditValue = $bSelected ? $iCurrentValue : '';
  6276. $sValue = '<input class="redundancy-min-up-percent" type="string" size="3" name="'.$sName.'" value="'.$sEditValue.'">';
  6277. // To fix an issue on Firefox: focus set to the option (because the input is within the label for the option)
  6278. $oPage->add_ready_script("\$('[name=\"$sName\"]').click(function(){var me=this; setTimeout(function(){\$(me).focus();}, 100);});");
  6279. }
  6280. else
  6281. {
  6282. $sValue = $iCurrentValue;
  6283. }
  6284. break;
  6285. }
  6286. $sLabel = sprintf($this->GetUserOptionFormat($sUserOption), $sValue, MetaModel::GetName($this->GetHostClass()));
  6287. $sOptionName = $sHtmlNamesPrefix.'_user_option';
  6288. $sOptionId = $sOptionName.'_'.$sUserOption;
  6289. $sChecked = $bSelected ? 'checked' : '';
  6290. $sRet = '<input type="radio" name="'.$sOptionName.'" id="'.$sOptionId.'" value="'.$sUserOption.'"'.$sChecked.'> <label for="'.$sOptionId.'">'.$sLabel.'</label>';
  6291. }
  6292. else
  6293. {
  6294. // Read-only: display only the currently selected option
  6295. if ($bSelected)
  6296. {
  6297. $sRet = sprintf($this->GetUserOptionFormat($sUserOption), $iCurrentValue, MetaModel::GetName($this->GetHostClass()));
  6298. }
  6299. }
  6300. return $sRet;
  6301. }
  6302. /**
  6303. * Makes the string representation out of the values given by the form defined in GetDisplayForm
  6304. */
  6305. public function ReadValueFromPostedForm($sFormPrefix)
  6306. {
  6307. $sHtmlNamesPrefix = 'rddcy_'.$this->Get('relation_code').'_'.$this->Get('from_class').'_'.$this->Get('neighbour_id');
  6308. $iMinUpCount = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_count', null, 'raw_data');
  6309. $iMinUpPercent = (int) utils::ReadPostedParam($sHtmlNamesPrefix.'_min_up_percent', null, 'raw_data');
  6310. $sSelectedOption = utils::ReadPostedParam($sHtmlNamesPrefix.'_user_option', null, 'raw_data');
  6311. switch ($sSelectedOption)
  6312. {
  6313. case self::USER_OPTION_ENABLED_COUNT:
  6314. $sRet = $iMinUpCount;
  6315. break;
  6316. case self::USER_OPTION_ENABLED_PERCENT:
  6317. $sRet = $iMinUpPercent.'%';
  6318. break;
  6319. case self::USER_OPTION_DISABLED:
  6320. default:
  6321. $sRet = 'disabled';
  6322. break;
  6323. }
  6324. return $sRet;
  6325. }
  6326. }
  6327. /**
  6328. * Custom fields managed by an external implementation
  6329. *
  6330. * @package iTopORM
  6331. */
  6332. class AttributeCustomFields extends AttributeDefinition
  6333. {
  6334. static public function ListExpectedParams()
  6335. {
  6336. return array_merge(parent::ListExpectedParams(), array("handler_class"));
  6337. }
  6338. public function GetEditClass() {return "CustomFields";}
  6339. public function IsWritable() {return true;}
  6340. public function LoadFromDB() {return false;} // See ReadValue...
  6341. public function GetDefaultValue(DBObject $oHostObject = null)
  6342. {
  6343. return new ormCustomFieldsValue($oHostObject, $this->GetCode());
  6344. }
  6345. public function GetBasicFilterOperators() {return array();}
  6346. public function GetBasicFilterLooseOperator() {return '';}
  6347. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  6348. /**
  6349. * @param DBObject $oHostObject
  6350. * @param array|null $aValues
  6351. * @return CustomFieldsHandler
  6352. */
  6353. public function GetHandler($aValues = null)
  6354. {
  6355. $sHandlerClass = $this->Get('handler_class');
  6356. $oHandler = new $sHandlerClass($this->GetCode());
  6357. if (!is_null($aValues))
  6358. {
  6359. $oHandler->SetCurrentValues($aValues);
  6360. }
  6361. return $oHandler;
  6362. }
  6363. public function GetPrerequisiteAttributes($sClass = null)
  6364. {
  6365. $sHandlerClass = $this->Get('handler_class');
  6366. return $sHandlerClass::GetPrerequisiteAttributes($sClass);
  6367. }
  6368. public function GetEditValue($sValue, $oHostObj = null)
  6369. {
  6370. return 'GetEditValueNotImplemented for '.get_class($this);
  6371. }
  6372. /**
  6373. * Makes the string representation out of the values given by the form defined in GetDisplayForm
  6374. */
  6375. public function ReadValueFromPostedForm($oHostObject, $sFormPrefix)
  6376. {
  6377. $aRawData = json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$this->GetCode()}", '{}', 'raw_data'), true);
  6378. return new ormCustomFieldsValue($oHostObject, $this->GetCode(), $aRawData);
  6379. }
  6380. public function MakeRealValue($proposedValue, $oHostObject)
  6381. {
  6382. if (is_object($proposedValue) && ($proposedValue instanceof ormCustomFieldsValue))
  6383. {
  6384. return $proposedValue;
  6385. }
  6386. elseif (is_string($proposedValue))
  6387. {
  6388. $aValues = json_decode($proposedValue, true);
  6389. return new ormCustomFieldsValue($oHostObject, $this->GetCode(), $aValues);
  6390. }
  6391. elseif (is_array($proposedValue))
  6392. {
  6393. return new ormCustomFieldsValue($oHostObject, $this->GetCode(), $proposedValue);
  6394. }
  6395. elseif (is_null($proposedValue))
  6396. {
  6397. return new ormCustomFieldsValue($oHostObject, $this->GetCode());
  6398. }
  6399. throw new Exception('Unexpected type for the value of a custom fields attribute: '.gettype($proposedValue));
  6400. }
  6401. static public function GetFormFieldClass()
  6402. {
  6403. return '\\Combodo\\iTop\\Form\\Field\\SubFormField';
  6404. }
  6405. /**
  6406. * Override to build the relevant form field
  6407. *
  6408. * 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.
  6409. */
  6410. public function MakeFormField(DBObject $oObject, $oFormField = null)
  6411. {
  6412. if ($oFormField === null)
  6413. {
  6414. $sFormFieldClass = static::GetFormFieldClass();
  6415. $oFormField = new $sFormFieldClass($this->GetCode());
  6416. $oFormField->SetForm($this->GetForm($oObject));
  6417. }
  6418. parent::MakeFormField($oObject, $oFormField);
  6419. return $oFormField;
  6420. }
  6421. /**
  6422. * @param DBObject $oHostObject
  6423. * @return Combodo\iTop\Form\Form
  6424. */
  6425. public function GetForm(DBObject $oHostObject, $sFormPrefix = null)
  6426. {
  6427. try
  6428. {
  6429. $oValue = $oHostObject->Get($this->GetCode());
  6430. $oHandler = $this->GetHandler($oValue->GetValues());
  6431. $sFormId = is_null($sFormPrefix) ? 'cf_'.$this->GetCode() : $sFormPrefix.'_cf_'.$this->GetCode();
  6432. $oHandler->BuildForm($oHostObject, $sFormId);
  6433. $oForm = $oHandler->GetForm();
  6434. }
  6435. catch (Exception $e)
  6436. {
  6437. $oForm = new \Combodo\iTop\Form\Form('');
  6438. $oField = new \Combodo\iTop\Form\Field\LabelField('');
  6439. $oField->SetLabel('Custom field error: '.$e->getMessage());
  6440. $oForm->AddField($oField);
  6441. $oForm->Finalize();
  6442. }
  6443. return $oForm;
  6444. }
  6445. /**
  6446. * Read the data from where it has been stored. This verb must be implemented as soon as LoadFromDB returns false and LoadInObject returns true
  6447. * @param $oHostObject
  6448. * @return ormCustomFieldsValue
  6449. */
  6450. public function ReadValue($oHostObject)
  6451. {
  6452. try
  6453. {
  6454. $oHandler = $this->GetHandler();
  6455. $aValues = $oHandler->ReadValues($oHostObject);
  6456. $oRet = new ormCustomFieldsValue($oHostObject, $this->GetCode(), $aValues);
  6457. }
  6458. catch (Exception $e)
  6459. {
  6460. $oRet = new ormCustomFieldsValue($oHostObject, $this->GetCode());
  6461. }
  6462. return $oRet;
  6463. }
  6464. /**
  6465. * Record the data (currently in the processing of recording the host object)
  6466. * It is assumed that the data has been checked prior to calling Write()
  6467. * @param DBObject $oHostObject
  6468. * @param ormCustomFieldsValue|null $oValue (null is the default value)
  6469. */
  6470. public function WriteValue(DBObject $oHostObject, ormCustomFieldsValue $oValue = null)
  6471. {
  6472. if (is_null($oValue))
  6473. {
  6474. $oHandler = $this->GetHandler();
  6475. $aValues = array();
  6476. }
  6477. else
  6478. {
  6479. // Pass the values through the form to make sure that they are correct
  6480. $oHandler = $this->GetHandler($oValue->GetValues());
  6481. $oHandler->BuildForm($oHostObject, '');
  6482. $oForm = $oHandler->GetForm();
  6483. $aValues = $oForm->GetCurrentValues();
  6484. }
  6485. return $oHandler->WriteValues($oHostObject, $aValues);
  6486. }
  6487. /**
  6488. * The part of the current attribute in the object's signature, for the supplied value
  6489. * @param $value The value of this attribute for the object
  6490. * @return string The "signature" for this field/attribute
  6491. */
  6492. public function Fingerprint($value)
  6493. {
  6494. $oHandler = $this->GetHandler($value->GetValues());
  6495. return $oHandler->GetValueFingerprint();
  6496. }
  6497. /**
  6498. * Check the validity of the data
  6499. * @param DBObject $oHostObject
  6500. * @param $value
  6501. * @return bool|string true or error message
  6502. */
  6503. public function CheckValue(DBObject $oHostObject, $value)
  6504. {
  6505. try
  6506. {
  6507. $oHandler = $this->GetHandler($value->GetValues());
  6508. $oHandler->BuildForm($oHostObject, '');
  6509. $oForm = $oHandler->GetForm();
  6510. $oForm->Validate();
  6511. if ($oForm->GetValid())
  6512. {
  6513. $ret = true;
  6514. }
  6515. else
  6516. {
  6517. $aMessages = array();
  6518. foreach ($oForm->GetErrorMessages() as $sFieldId => $aFieldMessages)
  6519. {
  6520. $aMessages[] = $sFieldId.': '.implode(', ', $aFieldMessages);
  6521. }
  6522. $ret = 'Invalid value: '.implode(', ', $aMessages);
  6523. }
  6524. }
  6525. catch (Exception $e)
  6526. {
  6527. $ret = $e->getMessage();
  6528. }
  6529. return $ret;
  6530. }
  6531. /**
  6532. * Cleanup data upon object deletion (object id still available here)
  6533. * @param DBObject $oHostObject
  6534. */
  6535. public function DeleteValue(DBObject $oHostObject)
  6536. {
  6537. $oValue = $oHostObject->Get($this->GetCode());
  6538. $oHandler = $this->GetHandler($oValue->GetValues());
  6539. return $oHandler->DeleteValues($oHostObject);
  6540. }
  6541. public function GetAsHTML($value, $oHostObject = null, $bLocalize = true)
  6542. {
  6543. try
  6544. {
  6545. $sRet = $value->GetAsHTML($bLocalize);
  6546. }
  6547. catch (Exception $e)
  6548. {
  6549. $sRet = 'Custom field error: '.htmlentities($e->getMessage(), ENT_QUOTES, 'UTF-8');
  6550. }
  6551. return $sRet;
  6552. }
  6553. public function GetAsXML($value, $oHostObject = null, $bLocalize = true)
  6554. {
  6555. try
  6556. {
  6557. $sRet = $value->GetAsXML($bLocalize);
  6558. }
  6559. catch (Exception $e)
  6560. {
  6561. $sRet = Str::pure2xml('Custom field error: '.$e->getMessage());
  6562. }
  6563. return $sRet;
  6564. }
  6565. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null, $bLocalize = true, $bConvertToPlainText = false)
  6566. {
  6567. try
  6568. {
  6569. $sRet = $value->GetAsCSV($sSeparator, $sTextQualifier, $bLocalize, $bConvertToPlainText);
  6570. }
  6571. catch (Exception $e)
  6572. {
  6573. $sFrom = array("\r\n", $sTextQualifier);
  6574. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  6575. $sEscaped = str_replace($sFrom, $sTo, 'Custom field error: '.$e->getMessage());
  6576. $sRet = $sTextQualifier.$sEscaped.$sTextQualifier;
  6577. }
  6578. return $sRet;
  6579. }
  6580. /**
  6581. * List the available verbs for 'GetForTemplate'
  6582. */
  6583. public function EnumTemplateVerbs()
  6584. {
  6585. $sHandlerClass = $this->Get('handler_class');
  6586. return $sHandlerClass::EnumTemplateVerbs();
  6587. }
  6588. /**
  6589. * Get various representations of the value, for insertion into a template (e.g. in Notifications)
  6590. * @param $value mixed The current value of the field
  6591. * @param $sVerb string The verb specifying the representation of the value
  6592. * @param $oHostObject DBObject The object
  6593. * @param $bLocalize bool Whether or not to localize the value
  6594. */
  6595. public function GetForTemplate($value, $sVerb, $oHostObject = null, $bLocalize = true)
  6596. {
  6597. try
  6598. {
  6599. $sRet = $value->GetForTemplate($sVerb, $bLocalize);
  6600. }
  6601. catch (Exception $e)
  6602. {
  6603. $sRet = 'Custom field error: '.$e->getMessage();
  6604. }
  6605. return $sRet;
  6606. }
  6607. public function MakeValueFromString($sProposedValue, $bLocalizedValue = false, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  6608. {
  6609. return null;
  6610. }
  6611. /**
  6612. * Helper to get a value that will be JSON encoded
  6613. * The operation is the opposite to FromJSONToValue
  6614. */
  6615. public function GetForJSON($value)
  6616. {
  6617. return null;
  6618. }
  6619. /**
  6620. * Helper to form a value, given JSON decoded data
  6621. * The operation is the opposite to GetForJSON
  6622. */
  6623. public function FromJSONToValue($json)
  6624. {
  6625. return null;
  6626. }
  6627. public function Equals($val1, $val2)
  6628. {
  6629. try
  6630. {
  6631. $bEquals = $val1->Equals($val2);
  6632. }
  6633. catch (Exception $e)
  6634. {
  6635. false;
  6636. }
  6637. return $bEquals;
  6638. }
  6639. }