attributedef.class.inc.php 140 KB

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