attributedef.class.inc.php 159 KB

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