attributedef.class.inc.php 187 KB

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