attributedef.class.inc.php 122 KB

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