attributedef.class.inc.php 127 KB

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