attributedef.class.inc.php 157 KB

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