attributedef.class.inc.php 214 KB

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