attributedef.class.inc.php 135 KB

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