attributedef.class.inc.php 216 KB

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