attributedef.class.inc.php 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340
  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('ormpassword.class.inc.php');
  27. require_once('ormcaselog.class.inc.php');
  28. /**
  29. * MissingColumnException - sent if an attribute is being created but the column is missing in the row
  30. *
  31. * @package iTopORM
  32. */
  33. class MissingColumnException extends Exception
  34. {}
  35. /**
  36. * add some description here...
  37. *
  38. * @package iTopORM
  39. */
  40. define('EXTKEY_RELATIVE', 1);
  41. /**
  42. * add some description here...
  43. *
  44. * @package iTopORM
  45. */
  46. define('EXTKEY_ABSOLUTE', 2);
  47. /**
  48. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  49. *
  50. * @package iTopORM
  51. */
  52. define('DEL_MANUAL', 1);
  53. /**
  54. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  55. *
  56. * @package iTopORM
  57. */
  58. define('DEL_AUTO', 2);
  59. define('DEL_SILENT', 2);
  60. /**
  61. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  62. *
  63. * @package iTopORM
  64. */
  65. abstract class AttributeDefinition
  66. {
  67. public function GetType()
  68. {
  69. return Dict::S('Core:'.get_class($this));
  70. }
  71. public function GetTypeDesc()
  72. {
  73. return Dict::S('Core:'.get_class($this).'+');
  74. }
  75. abstract public function GetEditClass();
  76. protected $m_sCode;
  77. private $m_aParams = array();
  78. protected $m_sHostClass = '!undefined!';
  79. protected function Get($sParamName) {return $this->m_aParams[$sParamName];}
  80. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  81. protected function GetOptional($sParamName, $default)
  82. {
  83. if (array_key_exists($sParamName, $this->m_aParams))
  84. {
  85. return $this->m_aParams[$sParamName];
  86. }
  87. else
  88. {
  89. return $default;
  90. }
  91. }
  92. public function __construct($sCode, $aParams)
  93. {
  94. $this->m_sCode = $sCode;
  95. $this->m_aParams = $aParams;
  96. $this->ConsistencyCheck();
  97. }
  98. public function OverloadParams($aParams)
  99. {
  100. foreach ($aParams as $sParam => $value)
  101. {
  102. if (!array_key_exists($sParam, $this->m_aParams))
  103. {
  104. throw new CoreException("Unknown attribute definition parameter '$sParam', please select a value in {".implode(", ", array_keys($this->m_aParams))."}");
  105. }
  106. else
  107. {
  108. $this->m_aParams[$sParam] = $value;
  109. }
  110. }
  111. }
  112. public function SetHostClass($sHostClass)
  113. {
  114. $this->m_sHostClass = $sHostClass;
  115. }
  116. public function GetHostClass()
  117. {
  118. return $this->m_sHostClass;
  119. }
  120. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  121. // to be overloaded
  122. static protected function ListExpectedParams()
  123. {
  124. return array();
  125. }
  126. private function ConsistencyCheck()
  127. {
  128. // Check that any mandatory param has been specified
  129. //
  130. $aExpectedParams = $this->ListExpectedParams();
  131. foreach($aExpectedParams as $sParamName)
  132. {
  133. if (!array_key_exists($sParamName, $this->m_aParams))
  134. {
  135. $aBacktrace = debug_backtrace();
  136. $sTargetClass = $aBacktrace[2]["class"];
  137. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  138. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  139. }
  140. }
  141. }
  142. // table, key field, name field
  143. public function ListDBJoins()
  144. {
  145. return "";
  146. // e.g: return array("Site", "infrid", "name");
  147. }
  148. public function IsDirectField() {return false;}
  149. public function IsScalar() {return false;}
  150. public function IsLinkSet() {return false;}
  151. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  152. public function IsHierarchicalKey() {return false;}
  153. public function IsExternalField() {return false;}
  154. public function IsWritable() {return false;}
  155. public function IsNullAllowed() {return true;}
  156. public function GetCode() {return $this->m_sCode;}
  157. public function GetLabel() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $this->m_sCode);}
  158. public function GetLabel_Obsolete()
  159. {
  160. // Written for compatibility with a data model written prior to version 0.9.1
  161. if (array_key_exists('label', $this->m_aParams))
  162. {
  163. return $this->m_aParams['label'];
  164. }
  165. else
  166. {
  167. return $this->GetLabel();
  168. }
  169. }
  170. public function GetDescription() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', '');}
  171. public function GetHelpOnEdition() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', '');}
  172. public function GetHelpOnSmartSearch()
  173. {
  174. $aParents = array_merge(array(get_class($this) => get_class($this)), class_parents($this));
  175. foreach ($aParents as $sClass)
  176. {
  177. $sHelp = Dict::S("Core:$sClass?SmartSearch", '-missing-');
  178. if ($sHelp != '-missing-')
  179. {
  180. return $sHelp;
  181. }
  182. }
  183. return '';
  184. }
  185. public function GetDescription_Obsolete()
  186. {
  187. // Written for compatibility with a data model written prior to version 0.9.1
  188. if (array_key_exists('description', $this->m_aParams))
  189. {
  190. return $this->m_aParams['description'];
  191. }
  192. else
  193. {
  194. return $this->GetDescription();
  195. }
  196. }
  197. public function GetValuesDef() {return null;}
  198. public function GetPrerequisiteAttributes() {return array();}
  199. public function GetNullValue() {return null;}
  200. public function IsNull($proposedValue) {return is_null($proposedValue);}
  201. public function MakeRealValue($proposedValue, $oHostObj) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  202. public function Equals($val1, $val2) {return ($val1 == $val2);}
  203. public function GetSQLExpressions($sPrefix = '') {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  204. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  205. public function GetSQLColumns() {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  206. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  207. public function RequiresIndex() {return false;}
  208. // Import - differs slightly from SQL input, but identical in most cases
  209. //
  210. public function GetImportColumns() {return $this->GetSQLColumns();}
  211. public function FromImportToValue($aCols, $sPrefix = '')
  212. {
  213. $aValues = array();
  214. foreach ($this->GetSQLExpressions($sPrefix) as $sAlias => $sExpr)
  215. {
  216. // This is working, based on the assumption that importable fields
  217. // are not computed fields => the expression is the name of a column
  218. $aValues[$sPrefix.$sAlias] = $aCols[$sExpr];
  219. }
  220. return $this->FromSQLToValue($aValues, $sPrefix);
  221. }
  222. public function GetValidationPattern()
  223. {
  224. return '';
  225. }
  226. public function CheckFormat($value)
  227. {
  228. return true;
  229. }
  230. public function GetMaxSize()
  231. {
  232. return null;
  233. }
  234. public function MakeValue()
  235. {
  236. $sComputeFunc = $this->Get("compute_func");
  237. if (empty($sComputeFunc)) return null;
  238. return call_user_func($sComputeFunc);
  239. }
  240. abstract public function GetDefaultValue();
  241. //
  242. // To be overloaded in subclasses
  243. //
  244. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  245. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  246. //abstract protected GetBasicFilterHTMLInput();
  247. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  248. public function GetFilterDefinitions()
  249. {
  250. return array();
  251. }
  252. public function GetEditValue($sValue)
  253. {
  254. return (string)$sValue;
  255. }
  256. public function GetAsHTML($sValue, $oHostObject = null)
  257. {
  258. return Str::pure2html((string)$sValue);
  259. }
  260. public function GetAsXML($sValue, $oHostObject = null)
  261. {
  262. return Str::pure2xml((string)$sValue);
  263. }
  264. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  265. {
  266. return (string)$sValue;
  267. }
  268. public function GetAllowedValues($aArgs = array(), $sContains = '')
  269. {
  270. $oValSetDef = $this->GetValuesDef();
  271. if (!$oValSetDef) return null;
  272. return $oValSetDef->GetValues($aArgs, $sContains);
  273. }
  274. /**
  275. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  276. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  277. * does nothing special, and just calls the default (loose) operator
  278. * @param string $sSearchText The search string to analyze for smart patterns
  279. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  280. * @param Hash $aParams Values of the query parameters
  281. * @return Expression The search condition to be added (AND) to the current search
  282. */
  283. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  284. {
  285. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  286. $oRightExpr = new VariableExpression($sParamName);
  287. $sOperator = $this->GetBasicFilterLooseOperator();
  288. switch ($sOperator)
  289. {
  290. case 'Contains':
  291. $aParams[$sParamName] = "%$sSearchText%";
  292. $sSQLOperator = 'LIKE';
  293. break;
  294. default:
  295. $sSQLOperator = $sOperator;
  296. $aParams[$sParamName] = $sSearchText;
  297. }
  298. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  299. return $oNewCondition;
  300. }
  301. }
  302. /**
  303. * Set of objects directly linked to an object, and being part of its definition
  304. *
  305. * @package iTopORM
  306. */
  307. class AttributeLinkedSet extends AttributeDefinition
  308. {
  309. static protected function ListExpectedParams()
  310. {
  311. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  312. }
  313. public function GetEditClass() {return "List";}
  314. public function IsWritable() {return true;}
  315. public function IsLinkSet() {return true;}
  316. public function IsIndirect() {return false;}
  317. public function GetValuesDef() {return $this->Get("allowed_values");}
  318. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  319. public function GetDefaultValue($aArgs = array())
  320. {
  321. // Note: so far, this feature is a prototype,
  322. // later, the argument 'this' should always be present in the arguments
  323. //
  324. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  325. {
  326. $aValues = $this->Get('default_value')->GetValues($aArgs);
  327. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  328. return $oSet;
  329. }
  330. else
  331. {
  332. return DBObjectSet::FromScratch($this->Get('linked_class'));
  333. }
  334. }
  335. public function GetLinkedClass() {return $this->Get('linked_class');}
  336. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  337. public function GetBasicFilterOperators() {return array();}
  338. public function GetBasicFilterLooseOperator() {return '';}
  339. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  340. public function GetAsHTML($sValue, $oHostObject = null)
  341. {
  342. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  343. {
  344. $sValue->Rewind();
  345. $aItems = array();
  346. while ($oObj = $sValue->Fetch())
  347. {
  348. // Show only relevant information (hide the external key to the current object)
  349. $aAttributes = array();
  350. foreach(MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef)
  351. {
  352. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  353. if ($oAttDef->IsExternalField()) continue;
  354. $sAttValue = $oObj->GetAsHTML($sAttCode);
  355. if (strlen($sAttValue) > 0)
  356. {
  357. $aAttributes[] = $sAttValue;
  358. }
  359. }
  360. $sAttributes = implode(', ', $aAttributes);
  361. $aItems[] = $sAttributes;
  362. }
  363. return implode('<br/>', $aItems);
  364. }
  365. return null;
  366. }
  367. public function GetAsXML($sValue, $oHostObject = null)
  368. {
  369. return "Sorry, no yet implemented";
  370. }
  371. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  372. {
  373. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  374. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  375. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  376. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  377. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  378. {
  379. $sValue->Rewind();
  380. $aItems = array();
  381. while ($oObj = $sValue->Fetch())
  382. {
  383. $sObjClass = get_class($oObj);
  384. // Show only relevant information (hide the external key to the current object)
  385. $aAttributes = array();
  386. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  387. {
  388. if ($sAttCode == 'finalclass')
  389. {
  390. if ($sObjClass == $this->GetLinkedClass())
  391. {
  392. // Simplify the output if the exact class could be determined implicitely
  393. continue;
  394. }
  395. }
  396. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  397. if ($oAttDef->IsExternalField()) continue;
  398. if (!$oAttDef->IsDirectField()) continue;
  399. if (!$oAttDef->IsScalar()) continue;
  400. $sAttValue = $oObj->GetAsCSV($sAttCode, $sSepValue, '');
  401. if (strlen($sAttValue) > 0)
  402. {
  403. $sAttributeData = str_replace($sAttributeQualifier, $sAttributeQualifier.$sAttributeQualifier, $sAttCode.$sSepValue.$sAttValue);
  404. $aAttributes[] = $sAttributeQualifier.$sAttributeData.$sAttributeQualifier;
  405. }
  406. }
  407. $sAttributes = implode($sSepAttribute, $aAttributes);
  408. $aItems[] = $sAttributes;
  409. }
  410. $sRes = implode($sSepItem, $aItems);
  411. }
  412. else
  413. {
  414. $sRes = '';
  415. }
  416. $sRes = str_replace($sTextQualifier, $sTextQualifier.$sTextQualifier, $sRes);
  417. $sRes = $sTextQualifier.$sRes.$sTextQualifier;
  418. return $sRes;
  419. }
  420. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  421. public function GetImportColumns()
  422. {
  423. $aColumns = array();
  424. $aColumns[$this->GetCode()] = 'TEXT';
  425. return $aColumns;
  426. }
  427. // Specific to this kind of attribute : transform a string into a value
  428. public function MakeValueFromString($sProposedValue, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  429. {
  430. if (is_null($sSepItem) || empty($sSepItem))
  431. {
  432. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  433. }
  434. if (is_null($sSepAttribute) || empty($sSepAttribute))
  435. {
  436. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  437. }
  438. if (is_null($sSepValue) || empty($sSepValue))
  439. {
  440. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  441. }
  442. if (is_null($sAttributeQualifier) || empty($sAttributeQualifier))
  443. {
  444. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  445. }
  446. $sTargetClass = $this->Get('linked_class');
  447. $sInput = str_replace($sSepItem, "\n", $sProposedValue);
  448. $oCSVParser = new CSVParser($sInput, $sSepAttribute, $sAttributeQualifier);
  449. $aInput = $oCSVParser->ToArray(0 /* do not skip lines */);
  450. $aLinks = array();
  451. foreach($aInput as $aRow)
  452. {
  453. // 1st - get the values, split the extkey->searchkey specs, and eventually get the finalclass value
  454. $aExtKeys = array();
  455. $aValues = array();
  456. foreach($aRow as $sCell)
  457. {
  458. $iSepPos = strpos($sCell, $sSepValue);
  459. if ($iSepPos === false)
  460. {
  461. // Houston...
  462. throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell));
  463. }
  464. $sAttCode = trim(substr($sCell, 0, $iSepPos));
  465. $sValue = substr($sCell, $iSepPos + strlen($sSepValue));
  466. if (preg_match('/^(.+)->(.+)$/', $sAttCode, $aMatches))
  467. {
  468. $sKeyAttCode = $aMatches[1];
  469. $sRemoteAttCode = $aMatches[2];
  470. $aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue;
  471. if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode))
  472. {
  473. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sKeyAttCode));
  474. }
  475. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  476. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  477. if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode))
  478. {
  479. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode));
  480. }
  481. }
  482. else
  483. {
  484. if(!MetaModel::IsValidAttCode($sTargetClass, $sAttCode))
  485. {
  486. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sAttCode));
  487. }
  488. $aValues[$sAttCode] = $sValue;
  489. }
  490. }
  491. // 2nd - Instanciate the object and set the value
  492. if (isset($aValues['finalclass']))
  493. {
  494. $sLinkClass = $aValues['finalclass'];
  495. if (!is_subclass_of($sLinkClass, $sTargetClass))
  496. {
  497. throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
  498. }
  499. }
  500. elseif (MetaModel::IsAbstract($sTargetClass))
  501. {
  502. throw new CoreException('Missing finalclass for link attribute specification');
  503. }
  504. else
  505. {
  506. $sLinkClass = $sTargetClass;
  507. }
  508. $oLink = MetaModel::NewObject($sLinkClass);
  509. foreach ($aValues as $sAttCode => $sValue)
  510. {
  511. $oLink->Set($sAttCode, $sValue);
  512. }
  513. // 3rd - Set external keys from search conditions
  514. foreach ($aExtKeys as $sKeyAttCode => $aReconciliation)
  515. {
  516. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  517. $sKeyClass = $oKeyAttDef->GetTargetClass();
  518. $oExtKeyFilter = new CMDBSearchFilter($sKeyClass);
  519. $aReconciliationDesc = array();
  520. foreach($aReconciliation as $sRemoteAttCode => $sValue)
  521. {
  522. $oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '=');
  523. $aReconciliationDesc[] = "$sRemoteAttCode=$sValue";
  524. }
  525. $oExtKeySet = new CMDBObjectSet($oExtKeyFilter);
  526. switch($oExtKeySet->Count())
  527. {
  528. case 0:
  529. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  530. throw new CoreException("Found no match", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  531. break;
  532. case 1:
  533. $oRemoteObj = $oExtKeySet->Fetch();
  534. $oLink->Set($sKeyAttCode, $oRemoteObj->GetKey());
  535. break;
  536. default:
  537. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  538. throw new CoreException("Found several matches", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  539. // Found several matches, ambiguous
  540. }
  541. }
  542. $aLinks[] = $oLink;
  543. }
  544. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  545. return $oSet;
  546. }
  547. public function Equals($val1, $val2)
  548. {
  549. if ($val1 === $val2) return true;
  550. if (is_object($val1) != is_object($val2))
  551. {
  552. return false;
  553. }
  554. if (!is_object($val1))
  555. {
  556. // string ?
  557. // todo = implement this case ?
  558. return false;
  559. }
  560. // Both values are Object sets
  561. return $val1->HasSameContents($val2);
  562. }
  563. }
  564. /**
  565. * Set of objects linked to an object (n-n), and being part of its definition
  566. *
  567. * @package iTopORM
  568. */
  569. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  570. {
  571. static protected function ListExpectedParams()
  572. {
  573. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  574. }
  575. public function IsIndirect() {return true;}
  576. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  577. public function GetEditClass() {return "LinkedSet";}
  578. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  579. }
  580. /**
  581. * Abstract class implementing default filters for a DB column
  582. *
  583. * @package iTopORM
  584. */
  585. class AttributeDBFieldVoid extends AttributeDefinition
  586. {
  587. static protected function ListExpectedParams()
  588. {
  589. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  590. }
  591. // To be overriden, used in GetSQLColumns
  592. protected function GetSQLCol() {return "VARCHAR(255)";}
  593. public function GetEditClass() {return "String";}
  594. public function GetValuesDef() {return $this->Get("allowed_values");}
  595. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  596. public function IsDirectField() {return true;}
  597. public function IsScalar() {return true;}
  598. public function IsWritable() {return true;}
  599. public function GetSQLExpr() {return $this->Get("sql");}
  600. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  601. public function IsNullAllowed() {return false;}
  602. //
  603. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  604. public function GetSQLExpressions($sPrefix = '')
  605. {
  606. $aColumns = array();
  607. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  608. $aColumns[''] = $this->Get("sql");
  609. return $aColumns;
  610. }
  611. public function FromSQLToValue($aCols, $sPrefix = '')
  612. {
  613. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  614. return $value;
  615. }
  616. public function GetSQLValues($value)
  617. {
  618. $aValues = array();
  619. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  620. return $aValues;
  621. }
  622. public function GetSQLColumns()
  623. {
  624. $aColumns = array();
  625. $aColumns[$this->Get("sql")] = $this->GetSQLCol();
  626. return $aColumns;
  627. }
  628. public function GetFilterDefinitions()
  629. {
  630. return array($this->GetCode() => new FilterFromAttribute($this));
  631. }
  632. public function GetBasicFilterOperators()
  633. {
  634. return array("="=>"equals", "!="=>"differs from");
  635. }
  636. public function GetBasicFilterLooseOperator()
  637. {
  638. return "=";
  639. }
  640. public function GetBasicFilterSQLExpr($sOpCode, $value)
  641. {
  642. $sQValue = CMDBSource::Quote($value);
  643. switch ($sOpCode)
  644. {
  645. case '!=':
  646. return $this->GetSQLExpr()." != $sQValue";
  647. break;
  648. case '=':
  649. default:
  650. return $this->GetSQLExpr()." = $sQValue";
  651. }
  652. }
  653. }
  654. /**
  655. * Base class for all kind of DB attributes, with the exception of external keys
  656. *
  657. * @package iTopORM
  658. */
  659. class AttributeDBField extends AttributeDBFieldVoid
  660. {
  661. static protected function ListExpectedParams()
  662. {
  663. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  664. }
  665. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"), null);}
  666. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  667. }
  668. /**
  669. * Map an integer column to an attribute
  670. *
  671. * @package iTopORM
  672. */
  673. class AttributeInteger extends AttributeDBField
  674. {
  675. static protected function ListExpectedParams()
  676. {
  677. return parent::ListExpectedParams();
  678. //return array_merge(parent::ListExpectedParams(), array());
  679. }
  680. public function GetEditClass() {return "String";}
  681. protected function GetSQLCol() {return "INT(11)";}
  682. public function GetValidationPattern()
  683. {
  684. return "^[0-9]+$";
  685. }
  686. public function GetBasicFilterOperators()
  687. {
  688. return array(
  689. "!="=>"differs from",
  690. "="=>"equals",
  691. ">"=>"greater (strict) than",
  692. ">="=>"greater than",
  693. "<"=>"less (strict) than",
  694. "<="=>"less than",
  695. "in"=>"in"
  696. );
  697. }
  698. public function GetBasicFilterLooseOperator()
  699. {
  700. // Unless we implement an "equals approximately..." or "same order of magnitude"
  701. return "=";
  702. }
  703. public function GetBasicFilterSQLExpr($sOpCode, $value)
  704. {
  705. $sQValue = CMDBSource::Quote($value);
  706. switch ($sOpCode)
  707. {
  708. case '!=':
  709. return $this->GetSQLExpr()." != $sQValue";
  710. break;
  711. case '>':
  712. return $this->GetSQLExpr()." > $sQValue";
  713. break;
  714. case '>=':
  715. return $this->GetSQLExpr()." >= $sQValue";
  716. break;
  717. case '<':
  718. return $this->GetSQLExpr()." < $sQValue";
  719. break;
  720. case '<=':
  721. return $this->GetSQLExpr()." <= $sQValue";
  722. break;
  723. case 'in':
  724. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  725. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  726. break;
  727. case '=':
  728. default:
  729. return $this->GetSQLExpr()." = \"$value\"";
  730. }
  731. }
  732. public function GetNullValue()
  733. {
  734. return null;
  735. }
  736. public function IsNull($proposedValue)
  737. {
  738. return is_null($proposedValue);
  739. }
  740. public function MakeRealValue($proposedValue, $oHostObj)
  741. {
  742. if (is_null($proposedValue)) return null;
  743. if ($proposedValue === '') return null; // 0 is transformed into '' !
  744. return (int)$proposedValue;
  745. }
  746. public function ScalarToSQL($value)
  747. {
  748. assert(is_numeric($value) || is_null($value));
  749. return $value; // supposed to be an int
  750. }
  751. }
  752. /**
  753. * Map a decimal value column (suitable for financial computations) to an attribute
  754. * internally in PHP such numbers are represented as string. Should you want to perform
  755. * a calculation on them, it is recommended to use the BC Math functions in order to
  756. * retain the precision
  757. *
  758. * @package iTopORM
  759. */
  760. class AttributeDecimal extends AttributeDBField
  761. {
  762. static protected function ListExpectedParams()
  763. {
  764. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  765. }
  766. public function GetEditClass() {return "String";}
  767. protected function GetSQLCol() {return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")";}
  768. public function GetValidationPattern()
  769. {
  770. $iNbDigits = $this->Get('digits');
  771. $iPrecision = $this->Get('decimals');
  772. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  773. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  774. }
  775. public function GetBasicFilterOperators()
  776. {
  777. return array(
  778. "!="=>"differs from",
  779. "="=>"equals",
  780. ">"=>"greater (strict) than",
  781. ">="=>"greater than",
  782. "<"=>"less (strict) than",
  783. "<="=>"less than",
  784. "in"=>"in"
  785. );
  786. }
  787. public function GetBasicFilterLooseOperator()
  788. {
  789. // Unless we implement an "equals approximately..." or "same order of magnitude"
  790. return "=";
  791. }
  792. public function GetBasicFilterSQLExpr($sOpCode, $value)
  793. {
  794. $sQValue = CMDBSource::Quote($value);
  795. switch ($sOpCode)
  796. {
  797. case '!=':
  798. return $this->GetSQLExpr()." != $sQValue";
  799. break;
  800. case '>':
  801. return $this->GetSQLExpr()." > $sQValue";
  802. break;
  803. case '>=':
  804. return $this->GetSQLExpr()." >= $sQValue";
  805. break;
  806. case '<':
  807. return $this->GetSQLExpr()." < $sQValue";
  808. break;
  809. case '<=':
  810. return $this->GetSQLExpr()." <= $sQValue";
  811. break;
  812. case 'in':
  813. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  814. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  815. break;
  816. case '=':
  817. default:
  818. return $this->GetSQLExpr()." = \"$value\"";
  819. }
  820. }
  821. public function GetNullValue()
  822. {
  823. return null;
  824. }
  825. public function IsNull($proposedValue)
  826. {
  827. return is_null($proposedValue);
  828. }
  829. public function MakeRealValue($proposedValue, $oHostObj)
  830. {
  831. if (is_null($proposedValue)) return null;
  832. if ($proposedValue == '') return null;
  833. return (string)$proposedValue;
  834. }
  835. public function ScalarToSQL($value)
  836. {
  837. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  838. return (string)$value; // treated as a string
  839. }
  840. }
  841. /**
  842. * Map a boolean column to an attribute
  843. *
  844. * @package iTopORM
  845. */
  846. class AttributeBoolean extends AttributeInteger
  847. {
  848. static protected function ListExpectedParams()
  849. {
  850. return parent::ListExpectedParams();
  851. //return array_merge(parent::ListExpectedParams(), array());
  852. }
  853. public function GetEditClass() {return "Integer";}
  854. protected function GetSQLCol() {return "TINYINT(1)";}
  855. public function MakeRealValue($proposedValue, $oHostObj)
  856. {
  857. if (is_null($proposedValue)) return null;
  858. if ($proposedValue === '') return null;
  859. if ((int)$proposedValue) return true;
  860. return false;
  861. }
  862. public function ScalarToSQL($value)
  863. {
  864. if ($value) return 1;
  865. return 0;
  866. }
  867. }
  868. /**
  869. * Map a varchar column (size < ?) to an attribute
  870. *
  871. * @package iTopORM
  872. */
  873. class AttributeString extends AttributeDBField
  874. {
  875. static protected function ListExpectedParams()
  876. {
  877. return parent::ListExpectedParams();
  878. //return array_merge(parent::ListExpectedParams(), array());
  879. }
  880. public function GetEditClass() {return "String";}
  881. protected function GetSQLCol() {return "VARCHAR(255)";}
  882. public function GetValidationPattern()
  883. {
  884. $sPattern = $this->GetOptional('validation_pattern', '');
  885. if (empty($sPattern))
  886. {
  887. return parent::GetValidationPattern();
  888. }
  889. else
  890. {
  891. return $sPattern;
  892. }
  893. }
  894. public function CheckFormat($value)
  895. {
  896. $sRegExp = $this->GetValidationPattern();
  897. if (empty($sRegExp))
  898. {
  899. return true;
  900. }
  901. else
  902. {
  903. $sRegExp = str_replace('/', '\\/', $sRegExp);
  904. return preg_match("/$sRegExp/", $value);
  905. }
  906. }
  907. public function GetMaxSize()
  908. {
  909. return 255;
  910. }
  911. public function GetBasicFilterOperators()
  912. {
  913. return array(
  914. "="=>"equals",
  915. "!="=>"differs from",
  916. "Like"=>"equals (no case)",
  917. "NotLike"=>"differs from (no case)",
  918. "Contains"=>"contains",
  919. "Begins with"=>"begins with",
  920. "Finishes with"=>"finishes with"
  921. );
  922. }
  923. public function GetBasicFilterLooseOperator()
  924. {
  925. return "Contains";
  926. }
  927. public function GetBasicFilterSQLExpr($sOpCode, $value)
  928. {
  929. $sQValue = CMDBSource::Quote($value);
  930. switch ($sOpCode)
  931. {
  932. case '=':
  933. case '!=':
  934. return $this->GetSQLExpr()." $sOpCode $sQValue";
  935. case 'Begins with':
  936. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  937. case 'Finishes with':
  938. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  939. case 'Contains':
  940. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  941. case 'NotLike':
  942. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  943. case 'Like':
  944. default:
  945. return $this->GetSQLExpr()." LIKE $sQValue";
  946. }
  947. }
  948. public function GetNullValue()
  949. {
  950. return '';
  951. }
  952. public function IsNull($proposedValue)
  953. {
  954. return ($proposedValue == '');
  955. }
  956. public function MakeRealValue($proposedValue, $oHostObj)
  957. {
  958. if (is_null($proposedValue)) return '';
  959. return (string)$proposedValue;
  960. }
  961. public function ScalarToSQL($value)
  962. {
  963. if (!is_string($value) && !is_null($value))
  964. {
  965. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  966. }
  967. return $value;
  968. }
  969. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  970. {
  971. $sFrom = array("\r\n", $sTextQualifier);
  972. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  973. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  974. return $sTextQualifier.$sEscaped.$sTextQualifier;
  975. }
  976. }
  977. /**
  978. * An attibute that matches an object class
  979. *
  980. * @package iTopORM
  981. */
  982. class AttributeClass extends AttributeString
  983. {
  984. static protected function ListExpectedParams()
  985. {
  986. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  987. }
  988. public function __construct($sCode, $aParams)
  989. {
  990. $this->m_sCode = $sCode;
  991. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  992. parent::__construct($sCode, $aParams);
  993. }
  994. public function GetDefaultValue()
  995. {
  996. $sDefault = parent::GetDefaultValue();
  997. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  998. {
  999. // For this kind of attribute specifying null as default value
  1000. // is authorized even if null is not allowed
  1001. // Pick the first one...
  1002. $aClasses = $this->GetAllowedValues();
  1003. $sDefault = key($aClasses);
  1004. }
  1005. return $sDefault;
  1006. }
  1007. public function GetAsHTML($sValue, $oHostObject = null)
  1008. {
  1009. if (empty($sValue)) return '';
  1010. return MetaModel::GetName($sValue);
  1011. }
  1012. public function RequiresIndex()
  1013. {
  1014. return true;
  1015. }
  1016. public function GetBasicFilterLooseOperator()
  1017. {
  1018. return '=';
  1019. }
  1020. }
  1021. /**
  1022. * An attibute that matches one of the language codes availables in the dictionnary
  1023. *
  1024. * @package iTopORM
  1025. */
  1026. class AttributeApplicationLanguage extends AttributeString
  1027. {
  1028. static protected function ListExpectedParams()
  1029. {
  1030. return parent::ListExpectedParams();
  1031. }
  1032. public function __construct($sCode, $aParams)
  1033. {
  1034. $this->m_sCode = $sCode;
  1035. $aAvailableLanguages = Dict::GetLanguages();
  1036. $aLanguageCodes = array();
  1037. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  1038. {
  1039. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  1040. }
  1041. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  1042. parent::__construct($sCode, $aParams);
  1043. }
  1044. public function RequiresIndex()
  1045. {
  1046. return true;
  1047. }
  1048. public function GetBasicFilterLooseOperator()
  1049. {
  1050. return '=';
  1051. }
  1052. }
  1053. /**
  1054. * The attribute dedicated to the finalclass automatic attribute
  1055. *
  1056. * @package iTopORM
  1057. */
  1058. class AttributeFinalClass extends AttributeString
  1059. {
  1060. public function __construct($sCode, $aParams)
  1061. {
  1062. $this->m_sCode = $sCode;
  1063. $aParams["allowed_values"] = null;
  1064. parent::__construct($sCode, $aParams);
  1065. $this->m_sValue = $this->Get("default_value");
  1066. }
  1067. public function IsWritable()
  1068. {
  1069. return false;
  1070. }
  1071. public function RequiresIndex()
  1072. {
  1073. return true;
  1074. }
  1075. public function SetFixedValue($sValue)
  1076. {
  1077. $this->m_sValue = $sValue;
  1078. }
  1079. public function GetDefaultValue()
  1080. {
  1081. return $this->m_sValue;
  1082. }
  1083. public function GetAsHTML($sValue, $oHostObject = null)
  1084. {
  1085. if (empty($sValue)) return '';
  1086. return MetaModel::GetName($sValue);
  1087. }
  1088. public function GetBasicFilterLooseOperator()
  1089. {
  1090. return '=';
  1091. }
  1092. }
  1093. /**
  1094. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  1095. *
  1096. * @package iTopORM
  1097. */
  1098. class AttributePassword extends AttributeString
  1099. {
  1100. static protected function ListExpectedParams()
  1101. {
  1102. return parent::ListExpectedParams();
  1103. //return array_merge(parent::ListExpectedParams(), array());
  1104. }
  1105. public function GetEditClass() {return "Password";}
  1106. protected function GetSQLCol() {return "VARCHAR(64)";}
  1107. public function GetMaxSize()
  1108. {
  1109. return 64;
  1110. }
  1111. public function GetFilterDefinitions()
  1112. {
  1113. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  1114. // not allowed to search on passwords!
  1115. return array();
  1116. }
  1117. public function GetAsHTML($sValue, $oHostObject = null)
  1118. {
  1119. if (strlen($sValue) == 0)
  1120. {
  1121. return '';
  1122. }
  1123. else
  1124. {
  1125. return '******';
  1126. }
  1127. }
  1128. }
  1129. /**
  1130. * Map a text column (size < 255) to an attribute that is encrypted in the database
  1131. * The encryption is based on a key set per iTop instance. Thus if you export your
  1132. * database (in SQL) to someone else without providing the key at the same time
  1133. * the encrypted fields will remain encrypted
  1134. *
  1135. * @package iTopORM
  1136. */
  1137. class AttributeEncryptedString extends AttributeString
  1138. {
  1139. static $sKey = null; // Encryption key used for all encrypted fields
  1140. public function __construct($sCode, $aParams)
  1141. {
  1142. parent::__construct($sCode, $aParams);
  1143. if (self::$sKey == null)
  1144. {
  1145. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1146. }
  1147. }
  1148. protected function GetSQLCol() {return "TINYBLOB";}
  1149. public function GetMaxSize()
  1150. {
  1151. return 255;
  1152. }
  1153. public function GetFilterDefinitions()
  1154. {
  1155. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  1156. // not allowed to search on encrypted fields !
  1157. return array();
  1158. }
  1159. public function MakeRealValue($proposedValue, $oHostObj)
  1160. {
  1161. if (is_null($proposedValue)) return null;
  1162. return (string)$proposedValue;
  1163. }
  1164. /**
  1165. * Decrypt the value when reading from the database
  1166. */
  1167. public function FromSQLToValue($aCols, $sPrefix = '')
  1168. {
  1169. $oSimpleCrypt = new SimpleCrypt();
  1170. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  1171. return $sValue;
  1172. }
  1173. /**
  1174. * Encrypt the value before storing it in the database
  1175. */
  1176. public function GetSQLValues($value)
  1177. {
  1178. $oSimpleCrypt = new SimpleCrypt();
  1179. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  1180. $aValues = array();
  1181. $aValues[$this->Get("sql")] = $encryptedValue;
  1182. return $aValues;
  1183. }
  1184. }
  1185. // Wiki formatting - experimental
  1186. //
  1187. // [[<objClass>:<objName>]]
  1188. // Example: [[Server:db1.tnut.com]]
  1189. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  1190. // <url>
  1191. // Example: http://romain:trustno1@127.0.0.1:8888/iTop-trunk/modules/itop-caches/itop-caches.php?agument=machin%20#monAncre
  1192. 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");
  1193. // SHEME............. USER.................... PASSWORD...................... HOST/IP......... PORT.......... PATH...................... GET................................... ANCHOR....................
  1194. // Origin of this regexp: http://www.php.net/manual/fr/function.preg-match.php#93824
  1195. /**
  1196. * Map a text column (size > ?) to an attribute
  1197. *
  1198. * @package iTopORM
  1199. */
  1200. class AttributeText extends AttributeString
  1201. {
  1202. public function GetEditClass() {return "Text";}
  1203. protected function GetSQLCol() {return "TEXT";}
  1204. public function GetMaxSize()
  1205. {
  1206. // Is there a way to know the current limitation for mysql?
  1207. // See mysql_field_len()
  1208. return 65535;
  1209. }
  1210. static public function RenderWikiHtml($sText)
  1211. {
  1212. if (preg_match_all(WIKI_URL, $sText, $aAllMatches, PREG_SET_ORDER /* important !*/ |PREG_OFFSET_CAPTURE /* important ! */))
  1213. {
  1214. $aUrls = array();
  1215. $i = count($aAllMatches);
  1216. // Replace the URLs by an actual hyperlink <a href="...">...</a>
  1217. // Let's do it backwards so that the initial positions are not modified by the replacement
  1218. // This works if the matches are captured: in the order they occur in the string AND
  1219. // with their offset (i.e. position) inside the string
  1220. while($i > 0)
  1221. {
  1222. $i--;
  1223. $sUrl = $aAllMatches[$i][0][0]; // String corresponding to the main pattern
  1224. $iPos = $aAllMatches[$i][0][1]; // Position of the main pattern
  1225. $sText = substr_replace($sText, "<a href=\"$sUrl\">$sUrl</a>", $iPos, strlen($sUrl));
  1226. }
  1227. }
  1228. if (preg_match_all(WIKI_OBJECT_REGEXP, $sText, $aAllMatches, PREG_SET_ORDER))
  1229. {
  1230. foreach($aAllMatches as $iPos => $aMatches)
  1231. {
  1232. $sClass = $aMatches[1];
  1233. $sName = $aMatches[2];
  1234. if (MetaModel::IsValidClass($sClass))
  1235. {
  1236. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  1237. if (is_object($oObj))
  1238. {
  1239. // Propose a std link to the object
  1240. $sText = str_replace($aMatches[0], $oObj->GetHyperlink(), $sText);
  1241. }
  1242. else
  1243. {
  1244. // Propose a std link to the object
  1245. $sClassLabel = MetaModel::GetName($sClass);
  1246. $sText = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sText);
  1247. // Later: propose a link to create a new object
  1248. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  1249. //$sText = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="'.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sText);
  1250. }
  1251. }
  1252. }
  1253. }
  1254. return $sText;
  1255. }
  1256. public function GetAsHTML($sValue, $oHostObject = null)
  1257. {
  1258. $sValue = parent::GetAsHTML($sValue);
  1259. $sValue = self::RenderWikiHtml($sValue);
  1260. $aStyles = array();
  1261. if ($this->GetWidth() != '')
  1262. {
  1263. $aStyles[] = 'width:'.$this->GetWidth();
  1264. }
  1265. if ($this->GetHeight() != '')
  1266. {
  1267. $aStyles[] = 'height:'.$this->GetHeight();
  1268. }
  1269. $sStyle = '';
  1270. if (count($aStyles) > 0)
  1271. {
  1272. $aStyles[] = 'overflow:auto';
  1273. $sStyle = 'style="'.implode(';', $aStyles).'"';
  1274. }
  1275. return "<div $sStyle>".str_replace("\n", "<br>\n", $sValue).'</div>';
  1276. }
  1277. public function GetEditValue($sValue)
  1278. {
  1279. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1280. {
  1281. foreach($aAllMatches as $iPos => $aMatches)
  1282. {
  1283. $sClass = $aMatches[1];
  1284. $sName = $aMatches[2];
  1285. if (MetaModel::IsValidClass($sClass))
  1286. {
  1287. $sClassLabel = MetaModel::GetName($sClass);
  1288. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  1289. }
  1290. }
  1291. }
  1292. return $sValue;
  1293. }
  1294. public function MakeRealValue($proposedValue, $oHostObj)
  1295. {
  1296. $sValue = $proposedValue;
  1297. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1298. {
  1299. foreach($aAllMatches as $iPos => $aMatches)
  1300. {
  1301. $sClassLabel = $aMatches[1];
  1302. $sName = $aMatches[2];
  1303. if (!MetaModel::IsValidClass($sClassLabel))
  1304. {
  1305. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  1306. if ($sClass)
  1307. {
  1308. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  1309. }
  1310. }
  1311. }
  1312. }
  1313. return $sValue;
  1314. }
  1315. public function GetAsXML($value, $oHostObject = null)
  1316. {
  1317. return Str::pure2xml($value);
  1318. }
  1319. public function GetWidth()
  1320. {
  1321. return $this->GetOptional('width', '');
  1322. }
  1323. public function GetHeight()
  1324. {
  1325. return $this->GetOptional('height', '');
  1326. }
  1327. }
  1328. /**
  1329. * Map a log to an attribute
  1330. *
  1331. * @package iTopORM
  1332. */
  1333. class AttributeLongText extends AttributeText
  1334. {
  1335. protected function GetSQLCol() {return "LONGTEXT";}
  1336. public function GetMaxSize()
  1337. {
  1338. // Is there a way to know the current limitation for mysql?
  1339. // See mysql_field_len()
  1340. return 65535*1024; // Limited... still 64 Mb!
  1341. }
  1342. }
  1343. /**
  1344. * An attibute that stores a case log (i.e journal)
  1345. *
  1346. * @package iTopORM
  1347. */
  1348. class AttributeCaseLog extends AttributeText
  1349. {
  1350. public function GetNullValue()
  1351. {
  1352. return '';
  1353. }
  1354. public function IsNull($proposedValue)
  1355. {
  1356. if (!($proposedValue instanceof ormCaseLog))
  1357. {
  1358. return ($proposedValue == '');
  1359. }
  1360. return ($proposedValue->GetText() == '');
  1361. }
  1362. public function ScalarToSQL($value)
  1363. {
  1364. if (!is_string($value) && !is_null($value))
  1365. {
  1366. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  1367. }
  1368. return $value;
  1369. }
  1370. public function GetEditClass() {return "CaseLog";}
  1371. public function GetEditValue($sValue) { return ''; } // New 'edit' value is always blank since it will be appended to the existing log
  1372. public function GetDefaultValue() {return new ormCaseLog();}
  1373. public function Equals($val1, $val2) {return ($val1->GetText() == $val2->GetText());}
  1374. // Facilitate things: allow the user to Set the value from a string
  1375. public function MakeRealValue($proposedValue, $oHostObj)
  1376. {
  1377. if (!($proposedValue instanceof ormCaseLog))
  1378. {
  1379. // Append the new value if an instance of the object is supplied
  1380. //
  1381. $oPreviousLog = null;
  1382. if ($oHostObj != null)
  1383. {
  1384. $oPreviousLog = $oHostObj->Get($this->GetCode());
  1385. if (!is_object($oPreviousLog))
  1386. {
  1387. $oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
  1388. }
  1389. }
  1390. if (is_object($oPreviousLog))
  1391. {
  1392. $oCaseLog = clone($oPreviousLog);
  1393. }
  1394. else
  1395. {
  1396. $oCaseLog = new ormCaseLog();
  1397. }
  1398. if (strlen($proposedValue) > 0)
  1399. {
  1400. $oCaseLog->AddLogEntry(parent::MakeRealValue($proposedValue, $oHostObj));
  1401. }
  1402. return $oCaseLog;
  1403. }
  1404. return $proposedValue;
  1405. }
  1406. public function GetSQLExpressions($sPrefix = '')
  1407. {
  1408. if ($sPrefix == '')
  1409. {
  1410. $sPrefix = $this->GetCode();
  1411. }
  1412. $aColumns = array();
  1413. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1414. $aColumns[''] = $sPrefix;
  1415. $aColumns['_index'] = $sPrefix.'_index';
  1416. return $aColumns;
  1417. }
  1418. public function FromSQLToValue($aCols, $sPrefix = '')
  1419. {
  1420. if (!isset($aCols[$sPrefix]))
  1421. {
  1422. $sAvailable = implode(', ', array_keys($aCols));
  1423. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1424. }
  1425. $sLog = $aCols[$sPrefix];
  1426. if (isset($aCols[$sPrefix.'_index']))
  1427. {
  1428. $sIndex = $aCols[$sPrefix.'_index'];
  1429. }
  1430. else
  1431. {
  1432. // For backward compatibility, allow the current state to be: 1 log, no index
  1433. $sIndex = '';
  1434. }
  1435. if (strlen($sIndex) > 0)
  1436. {
  1437. $aIndex = unserialize($sIndex);
  1438. $value = new ormCaseLog($sLog, $aIndex);
  1439. }
  1440. else
  1441. {
  1442. $value = new ormCaseLog($sLog);
  1443. }
  1444. return $value;
  1445. }
  1446. public function GetSQLValues($value)
  1447. {
  1448. if (!($value instanceOf ormCaseLog))
  1449. {
  1450. $value = new ormCaseLog('');
  1451. }
  1452. $aValues = array();
  1453. $aValues[$this->GetCode()] = $value->GetText();
  1454. $aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
  1455. return $aValues;
  1456. }
  1457. public function GetSQLColumns()
  1458. {
  1459. $aColumns = array();
  1460. $aColumns[$this->GetCode()] = 'LONGTEXT'; // 2^32 (4 Gb)
  1461. $aColumns[$this->GetCode().'_index'] = 'BLOB';
  1462. return $aColumns;
  1463. }
  1464. public function GetAsHTML($value, $oHostObject = null)
  1465. {
  1466. if ($value instanceOf ormCaseLog)
  1467. {
  1468. $sContent = $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
  1469. }
  1470. else
  1471. {
  1472. $sContent = '';
  1473. }
  1474. $aStyles = array();
  1475. if ($this->GetWidth() != '')
  1476. {
  1477. $aStyles[] = 'width:'.$this->GetWidth();
  1478. }
  1479. if ($this->GetHeight() != '')
  1480. {
  1481. $aStyles[] = 'height:'.$this->GetHeight();
  1482. }
  1483. $sStyle = '';
  1484. if (count($aStyles) > 0)
  1485. {
  1486. $sStyle = 'style="'.implode(';', $aStyles).'"';
  1487. }
  1488. return "<div class=\"caselog\" $sStyle>".$sContent.'</div>'; }
  1489. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1490. {
  1491. if ($value instanceOf ormCaseLog)
  1492. {
  1493. return parent::GetAsCSV($value->GetText(), $sSeparator, $sTextQualifier, $oHostObject);
  1494. }
  1495. else
  1496. {
  1497. return '';
  1498. }
  1499. }
  1500. public function GetAsXML($value, $oHostObject = null)
  1501. {
  1502. if ($value instanceOf ormCaseLog)
  1503. {
  1504. return parent::GetAsXML($value->GetText(), $oHostObject);
  1505. }
  1506. else
  1507. {
  1508. return '';
  1509. }
  1510. }
  1511. }
  1512. /**
  1513. * Map a text column (size > ?), containing HTML code, to an attribute
  1514. *
  1515. * @package iTopORM
  1516. */
  1517. class AttributeHTML extends AttributeText
  1518. {
  1519. public function GetEditClass() {return "HTML";}
  1520. public function GetAsHTML($sValue, $oHostObject = null)
  1521. {
  1522. return $sValue;
  1523. }
  1524. }
  1525. /**
  1526. * Specialization of a string: email
  1527. *
  1528. * @package iTopORM
  1529. */
  1530. class AttributeEmailAddress extends AttributeString
  1531. {
  1532. public function GetValidationPattern()
  1533. {
  1534. // return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  1535. return "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$";
  1536. }
  1537. public function GetAsHTML($sValue, $oHostObject = null)
  1538. {
  1539. if (empty($sValue)) return '';
  1540. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  1541. }
  1542. }
  1543. /**
  1544. * Specialization of a string: IP address
  1545. *
  1546. * @package iTopORM
  1547. */
  1548. class AttributeIPAddress extends AttributeString
  1549. {
  1550. public function GetValidationPattern()
  1551. {
  1552. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  1553. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  1554. }
  1555. }
  1556. /**
  1557. * Specialization of a string: OQL expression
  1558. *
  1559. * @package iTopORM
  1560. */
  1561. class AttributeOQL extends AttributeText
  1562. {
  1563. }
  1564. /**
  1565. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1566. *
  1567. * @package iTopORM
  1568. */
  1569. class AttributeTemplateString extends AttributeString
  1570. {
  1571. }
  1572. /**
  1573. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1574. *
  1575. * @package iTopORM
  1576. */
  1577. class AttributeTemplateText extends AttributeText
  1578. {
  1579. }
  1580. /**
  1581. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1582. *
  1583. * @package iTopORM
  1584. */
  1585. class AttributeTemplateHTML extends AttributeText
  1586. {
  1587. public function GetEditClass() {return "HTML";}
  1588. public function GetAsHTML($sValue, $oHostObject = null)
  1589. {
  1590. return $sValue;
  1591. }
  1592. }
  1593. /**
  1594. * Map a enum column to an attribute
  1595. *
  1596. * @package iTopORM
  1597. */
  1598. class AttributeEnum extends AttributeString
  1599. {
  1600. static protected function ListExpectedParams()
  1601. {
  1602. return parent::ListExpectedParams();
  1603. //return array_merge(parent::ListExpectedParams(), array());
  1604. }
  1605. public function GetEditClass() {return "String";}
  1606. protected function GetSQLCol()
  1607. {
  1608. $oValDef = $this->GetValuesDef();
  1609. if ($oValDef)
  1610. {
  1611. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  1612. }
  1613. else
  1614. {
  1615. $aValues = array();
  1616. }
  1617. if (count($aValues) > 0)
  1618. {
  1619. // The syntax used here do matters
  1620. // In particular, I had to remove unnecessary spaces to
  1621. // make sure that this string will match the field type returned by the DB
  1622. // (used to perform a comparison between the current DB format and the data model)
  1623. return "ENUM(".implode(",", $aValues).")";
  1624. }
  1625. else
  1626. {
  1627. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  1628. }
  1629. }
  1630. public function ScalarToSQL($value)
  1631. {
  1632. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  1633. // but that wasn't working for enums, because '' is NOT one of the allowed values
  1634. // that's why a null value must be forced to a real null
  1635. $value = parent::ScalarToSQL($value);
  1636. if ($this->IsNull($value))
  1637. {
  1638. return null;
  1639. }
  1640. else
  1641. {
  1642. return $value;
  1643. }
  1644. }
  1645. public function RequiresIndex()
  1646. {
  1647. return false;
  1648. }
  1649. public function GetBasicFilterOperators()
  1650. {
  1651. return parent::GetBasicFilterOperators();
  1652. }
  1653. public function GetBasicFilterLooseOperator()
  1654. {
  1655. return '=';
  1656. }
  1657. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1658. {
  1659. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1660. }
  1661. public function GetAsHTML($sValue, $oHostObject = null)
  1662. {
  1663. if (is_null($sValue))
  1664. {
  1665. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1666. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  1667. }
  1668. else
  1669. {
  1670. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1671. }
  1672. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', $sValue);
  1673. // later, we could imagine a detailed description in the title
  1674. return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  1675. }
  1676. public function GetEditValue($sValue)
  1677. {
  1678. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1679. return $sLabel;
  1680. }
  1681. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1682. {
  1683. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  1684. if (is_null($aRawValues)) return null;
  1685. $aLocalizedValues = array();
  1686. foreach ($aRawValues as $sKey => $sValue)
  1687. {
  1688. $aLocalizedValues[$sKey] = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sKey, $sKey);
  1689. }
  1690. return $aLocalizedValues;
  1691. }
  1692. /**
  1693. * Processes the input value to align it with the values supported
  1694. * by this type of attribute. In this case: turns empty strings into nulls
  1695. * @param mixed $proposedValue The value to be set for the attribute
  1696. * @return mixed The actual value that will be set
  1697. */
  1698. public function MakeRealValue($proposedValue, $oHostObj)
  1699. {
  1700. if ($proposedValue == '') return null;
  1701. return parent::MakeRealValue($proposedValue, $oHostObj);
  1702. }
  1703. }
  1704. /**
  1705. * Map a date+time column to an attribute
  1706. *
  1707. * @package iTopORM
  1708. */
  1709. class AttributeDateTime extends AttributeDBField
  1710. {
  1711. static protected function GetDateFormat()
  1712. {
  1713. return "Y-m-d H:i:s";
  1714. }
  1715. static protected function ListExpectedParams()
  1716. {
  1717. return parent::ListExpectedParams();
  1718. //return array_merge(parent::ListExpectedParams(), array());
  1719. }
  1720. public function GetEditClass() {return "DateTime";}
  1721. protected function GetSQLCol() {return "TIMESTAMP";}
  1722. public static function GetAsUnixSeconds($value)
  1723. {
  1724. $oDeadlineDateTime = new DateTime($value);
  1725. $iUnixSeconds = $oDeadlineDateTime->format('U');
  1726. return $iUnixSeconds;
  1727. }
  1728. // #@# THIS HAS TO REVISED
  1729. // Having null not allowed was interpreted by mySQL
  1730. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  1731. // Then, on each update of the record, the field was modified.
  1732. // We will have to specify the default value if we want to restore this option
  1733. // In fact, we could also have more verbs dedicated to the DB:
  1734. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  1735. public function IsNullAllowed() {return true;}
  1736. public function GetDefaultValue()
  1737. {
  1738. $default = parent::GetDefaultValue();
  1739. if (!parent::IsNullAllowed())
  1740. {
  1741. if (empty($default))
  1742. {
  1743. $default = date(self::GetDateFormat());
  1744. }
  1745. }
  1746. return $default;
  1747. }
  1748. // END OF THE WORKAROUND
  1749. ///////////////////////////////////////////////////////////////
  1750. public function GetValidationPattern()
  1751. {
  1752. 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$";
  1753. }
  1754. public function GetBasicFilterOperators()
  1755. {
  1756. return array(
  1757. "="=>"equals",
  1758. "!="=>"differs from",
  1759. "<"=>"before",
  1760. "<="=>"before",
  1761. ">"=>"after (strictly)",
  1762. ">="=>"after",
  1763. "SameDay"=>"same day (strip time)",
  1764. "SameMonth"=>"same year/month",
  1765. "SameYear"=>"same year",
  1766. "Today"=>"today",
  1767. ">|"=>"after today + N days",
  1768. "<|"=>"before today + N days",
  1769. "=|"=>"equals today + N days",
  1770. );
  1771. }
  1772. public function GetBasicFilterLooseOperator()
  1773. {
  1774. // Unless we implement a "same xxx, depending on given precision" !
  1775. return "=";
  1776. }
  1777. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1778. {
  1779. $sQValue = CMDBSource::Quote($value);
  1780. switch ($sOpCode)
  1781. {
  1782. case '=':
  1783. case '!=':
  1784. case '<':
  1785. case '<=':
  1786. case '>':
  1787. case '>=':
  1788. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1789. case 'SameDay':
  1790. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  1791. case 'SameMonth':
  1792. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  1793. case 'SameYear':
  1794. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  1795. case 'Today':
  1796. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  1797. case '>|':
  1798. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1799. case '<|':
  1800. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1801. case '=|':
  1802. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1803. default:
  1804. return $this->GetSQLExpr()." = $sQValue";
  1805. }
  1806. }
  1807. public function MakeRealValue($proposedValue, $oHostObj)
  1808. {
  1809. if (is_null($proposedValue))
  1810. {
  1811. return null;
  1812. }
  1813. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  1814. {
  1815. return null;
  1816. }
  1817. if (!is_numeric($proposedValue))
  1818. {
  1819. return $proposedValue;
  1820. }
  1821. return date(self::GetDateFormat(), $proposedValue);
  1822. }
  1823. public function ScalarToSQL($value)
  1824. {
  1825. if (is_null($value))
  1826. {
  1827. return null;
  1828. }
  1829. elseif (empty($value))
  1830. {
  1831. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  1832. return '0000-00-00 00:00:00';
  1833. }
  1834. return $value;
  1835. }
  1836. public function GetAsHTML($value, $oHostObject = null)
  1837. {
  1838. return Str::pure2html($value);
  1839. }
  1840. public function GetAsXML($value, $oHostObject = null)
  1841. {
  1842. return Str::pure2xml($value);
  1843. }
  1844. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1845. {
  1846. $sFrom = array("\r\n", $sTextQualifier);
  1847. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1848. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1849. return '"'.$sEscaped.'"';
  1850. }
  1851. /**
  1852. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  1853. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  1854. * does nothing special, and just calls the default (loose) operator
  1855. * @param string $sSearchText The search string to analyze for smart patterns
  1856. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  1857. * @param Hash $aParams Values of the query parameters
  1858. * @return Expression The search condition to be added (AND) to the current search
  1859. */
  1860. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  1861. {
  1862. // Possible smart patterns
  1863. $aPatterns = array(
  1864. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  1865. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  1866. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  1867. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  1868. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  1869. );
  1870. $sPatternFound = '';
  1871. $aMatches = array();
  1872. foreach($aPatterns as $sPatName => $sPattern)
  1873. {
  1874. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  1875. {
  1876. $sPatternFound = $sPatName;
  1877. break;
  1878. }
  1879. }
  1880. switch($sPatternFound)
  1881. {
  1882. case 'between':
  1883. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  1884. $oRightExpr = new VariableExpression($sParamName1);
  1885. $aParams[$sParamName1] = $aMatches[1];
  1886. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  1887. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  1888. $oRightExpr = new VariableExpression($sParamName2);
  1889. $sOperator = $this->GetBasicFilterLooseOperator();
  1890. $aParams[$sParamName2] = $aMatches[2];
  1891. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  1892. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  1893. break;
  1894. case 'greater than':
  1895. case 'greater than or equal':
  1896. case 'less than':
  1897. case 'less than or equal':
  1898. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  1899. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  1900. $oRightExpr = new VariableExpression($sParamName);
  1901. $aParams[$sParamName] = $aMatches[1];
  1902. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  1903. break;
  1904. default:
  1905. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  1906. }
  1907. return $oNewCondition;
  1908. }
  1909. }
  1910. /**
  1911. * Store a duration as a number of seconds
  1912. *
  1913. * @package iTopORM
  1914. */
  1915. class AttributeDuration extends AttributeInteger
  1916. {
  1917. public function GetEditClass() {return "Duration";}
  1918. protected function GetSQLCol() {return "INT(11) UNSIGNED";}
  1919. public function GetNullValue() {return '0';}
  1920. public function GetDefaultValue()
  1921. {
  1922. return 0;
  1923. }
  1924. public function MakeRealValue($proposedValue, $oHostObj)
  1925. {
  1926. if (is_null($proposedValue)) return null;
  1927. if (!is_numeric($proposedValue)) return null;
  1928. if ( ((int)$proposedValue) < 0) return null;
  1929. return (int)$proposedValue;
  1930. }
  1931. public function ScalarToSQL($value)
  1932. {
  1933. if (is_null($value))
  1934. {
  1935. return null;
  1936. }
  1937. return $value;
  1938. }
  1939. public function GetAsHTML($value, $oHostObject = null)
  1940. {
  1941. return Str::pure2html(self::FormatDuration($value));
  1942. }
  1943. static function FormatDuration($duration)
  1944. {
  1945. $aDuration = self::SplitDuration($duration);
  1946. $sResult = '';
  1947. if ($duration < 60)
  1948. {
  1949. // Less than 1 min
  1950. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  1951. }
  1952. else if ($duration < 3600)
  1953. {
  1954. // less than 1 hour, display it in minutes/seconds
  1955. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  1956. }
  1957. else if ($duration < 86400)
  1958. {
  1959. // Less than 1 day, display it in hours/minutes/seconds
  1960. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  1961. }
  1962. else
  1963. {
  1964. // more than 1 day, display it in days/hours/minutes/seconds
  1965. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  1966. }
  1967. return $sResult;
  1968. }
  1969. static function SplitDuration($duration)
  1970. {
  1971. $duration = (int) $duration;
  1972. $days = floor($duration / 86400);
  1973. $hours = floor(($duration - (86400*$days)) / 3600);
  1974. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  1975. $seconds = ($duration % 60); // modulo
  1976. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  1977. }
  1978. }
  1979. /**
  1980. * Map a date+time column to an attribute
  1981. *
  1982. * @package iTopORM
  1983. */
  1984. class AttributeDate extends AttributeDateTime
  1985. {
  1986. const MYDATEFORMAT = "Y-m-d";
  1987. static protected function GetDateFormat()
  1988. {
  1989. return "Y-m-d";
  1990. }
  1991. static protected function ListExpectedParams()
  1992. {
  1993. return parent::ListExpectedParams();
  1994. //return array_merge(parent::ListExpectedParams(), array());
  1995. }
  1996. public function GetEditClass() {return "Date";}
  1997. protected function GetSQLCol() {return "DATE";}
  1998. public function GetValidationPattern()
  1999. {
  2000. 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)))$";
  2001. }
  2002. }
  2003. /**
  2004. * A dead line stored as a date & time
  2005. * The only difference with the DateTime attribute is the display:
  2006. * relative to the current time
  2007. */
  2008. class AttributeDeadline extends AttributeDateTime
  2009. {
  2010. public function GetAsHTML($value, $oHostObject = null)
  2011. {
  2012. $sResult = '';
  2013. if ($value !== null)
  2014. {
  2015. $value = AttributeDateTime::GetAsUnixSeconds($value);
  2016. $difference = $value - time();
  2017. if ($difference >= 0)
  2018. {
  2019. $sResult = self::FormatDuration($difference);
  2020. }
  2021. else
  2022. {
  2023. $sResult = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  2024. }
  2025. }
  2026. return $sResult;
  2027. }
  2028. static function FormatDuration($duration)
  2029. {
  2030. $days = floor($duration / 86400);
  2031. $hours = floor(($duration - (86400*$days)) / 3600);
  2032. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2033. $sResult = '';
  2034. if ($duration < 60)
  2035. {
  2036. // Less than 1 min
  2037. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  2038. }
  2039. else if ($duration < 3600)
  2040. {
  2041. // less than 1 hour, display it in minutes
  2042. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  2043. }
  2044. else if ($duration < 86400)
  2045. {
  2046. // Less that 1 day, display it in hours/minutes
  2047. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  2048. }
  2049. else
  2050. {
  2051. // Less that 1 day, display it in hours/minutes
  2052. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  2053. }
  2054. return $sResult;
  2055. }
  2056. }
  2057. /**
  2058. * Map a foreign key to an attribute
  2059. * AttributeExternalKey and AttributeExternalField may be an external key
  2060. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  2061. * where an AttributeExternalField corresponds to a column into another table (class)
  2062. *
  2063. * @package iTopORM
  2064. */
  2065. class AttributeExternalKey extends AttributeDBFieldVoid
  2066. {
  2067. static protected function ListExpectedParams()
  2068. {
  2069. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  2070. }
  2071. public function GetEditClass() {return "ExtKey";}
  2072. protected function GetSQLCol() {return "INT(11)";}
  2073. public function RequiresIndex()
  2074. {
  2075. return true;
  2076. }
  2077. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  2078. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  2079. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2080. public function GetKeyAttCode() {return $this->GetCode();}
  2081. public function GetDefaultValue() {return 0;}
  2082. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  2083. public function GetBasicFilterOperators()
  2084. {
  2085. return parent::GetBasicFilterOperators();
  2086. }
  2087. public function GetBasicFilterLooseOperator()
  2088. {
  2089. return parent::GetBasicFilterLooseOperator();
  2090. }
  2091. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2092. {
  2093. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2094. }
  2095. // overloaded here so that an ext key always have the answer to
  2096. // "what are your possible values?"
  2097. public function GetValuesDef()
  2098. {
  2099. $oValSetDef = $this->Get("allowed_values");
  2100. if (!$oValSetDef)
  2101. {
  2102. // Let's propose every existing value
  2103. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2104. }
  2105. return $oValSetDef;
  2106. }
  2107. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2108. {
  2109. //throw new Exception("GetAllowedValues on ext key has been deprecated");
  2110. try
  2111. {
  2112. return parent::GetAllowedValues($aArgs, $sContains);
  2113. }
  2114. catch (MissingQueryArgument $e)
  2115. {
  2116. // Some required arguments could not be found, enlarge to any existing value
  2117. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2118. return $oValSetDef->GetValues($aArgs, $sContains);
  2119. }
  2120. }
  2121. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  2122. {
  2123. $oValSetDef = $this->GetValuesDef();
  2124. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  2125. return $oSet;
  2126. }
  2127. public function GetDeletionPropagationOption()
  2128. {
  2129. return $this->Get("on_target_delete");
  2130. }
  2131. public function GetNullValue()
  2132. {
  2133. return 0;
  2134. }
  2135. public function IsNull($proposedValue)
  2136. {
  2137. return ($proposedValue == 0);
  2138. }
  2139. public function MakeRealValue($proposedValue, $oHostObj)
  2140. {
  2141. if (is_null($proposedValue)) return 0;
  2142. if ($proposedValue === '') return 0;
  2143. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  2144. return (int)$proposedValue;
  2145. }
  2146. public function GetMaximumComboLength()
  2147. {
  2148. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  2149. }
  2150. public function GetMinAutoCompleteChars()
  2151. {
  2152. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  2153. }
  2154. public function AllowTargetCreation()
  2155. {
  2156. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  2157. }
  2158. }
  2159. /**
  2160. * Special kind of External Key to manage a hierarchy of objects
  2161. */
  2162. class AttributeHierarchicalKey extends AttributeExternalKey
  2163. {
  2164. static protected function ListExpectedParams()
  2165. {
  2166. $aParams = parent::ListExpectedParams();
  2167. $idx = array_search('targetclass', $aParams);
  2168. unset($aParams[$idx]);
  2169. $idx = array_search('jointype', $aParams);
  2170. unset($aParams[$idx]);
  2171. return $aParams; // TODO: mettre les bons parametres ici !!
  2172. }
  2173. public function GetEditClass() {return "ExtKey";}
  2174. public function RequiresIndex()
  2175. {
  2176. return true;
  2177. }
  2178. public function IsHierarchicalKey() {return true;}
  2179. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->GetHostClass();}
  2180. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2181. public function GetKeyAttCode() {return $this->GetCode();}
  2182. public function GetBasicFilterOperators()
  2183. {
  2184. return parent::GetBasicFilterOperators();
  2185. }
  2186. public function GetBasicFilterLooseOperator()
  2187. {
  2188. return parent::GetBasicFilterLooseOperator();
  2189. }
  2190. public function GetSQLColumns()
  2191. {
  2192. $aColumns = array();
  2193. $aColumns[$this->GetCode()] = 'INT(11)';
  2194. $aColumns[$this->GetSQLLeft()] = 'INT(11)';
  2195. $aColumns[$this->GetSQLRight()] = 'INT(11)';
  2196. return $aColumns;
  2197. }
  2198. public function GetSQLRight()
  2199. {
  2200. return $this->GetCode().'_right';
  2201. }
  2202. public function GetSQLLeft()
  2203. {
  2204. return $this->GetCode().'_left';
  2205. }
  2206. public function GetSQLValues($value)
  2207. {
  2208. if (!is_array($value))
  2209. {
  2210. $aValues[$this->GetCode()] = $value;
  2211. }
  2212. else
  2213. {
  2214. $aValues = array();
  2215. $aValues[$this->GetCode()] = $value[$this->GetCode()];
  2216. $aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
  2217. $aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
  2218. }
  2219. return $aValues;
  2220. }
  2221. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2222. {
  2223. if (array_key_exists('this', $aArgs))
  2224. {
  2225. // Hierarchical keys have one more constraint: the "parent value" cannot be
  2226. // "under" themselves
  2227. $iRootId = $aArgs['this']->GetKey();
  2228. if ($iRootId > 0) // ignore objects that do no exist in the database...
  2229. {
  2230. $oValSetDef = $this->GetValuesDef();
  2231. $sClass = $this->GetHostClass(); // host class == target class for HK
  2232. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  2233. $oValSetDef->AddCondition($oFilter);
  2234. }
  2235. }
  2236. else
  2237. {
  2238. return parent::GetAllowedValues($aArgs, $sContains);
  2239. }
  2240. }
  2241. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  2242. {
  2243. $oValSetDef = $this->GetValuesDef();
  2244. if (array_key_exists('this', $aArgs))
  2245. {
  2246. // Hierarchical keys have one more constraint: the "parent value" cannot be
  2247. // "under" themselves
  2248. $iRootId = $aArgs['this']->GetKey();
  2249. if ($iRootId > 0) // ignore objects that do no exist in the database...
  2250. {
  2251. $aValuesSetDef = $this->GetValuesDef();
  2252. $sClass = $this->GetHostClass(); // host class == target class for HK
  2253. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  2254. $oValSetDef->AddCondition($oFilter);
  2255. }
  2256. }
  2257. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  2258. return $oSet;
  2259. }
  2260. }
  2261. /**
  2262. * An attribute which corresponds to an external key (direct or indirect)
  2263. *
  2264. * @package iTopORM
  2265. */
  2266. class AttributeExternalField extends AttributeDefinition
  2267. {
  2268. static protected function ListExpectedParams()
  2269. {
  2270. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  2271. }
  2272. public function GetEditClass() {return "ExtField";}
  2273. protected function GetSQLCol()
  2274. {
  2275. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  2276. $oExtAttDef = $this->GetExtAttDef();
  2277. return $oExtAttDef->GetSQLCol();
  2278. }
  2279. public function GetSQLExpressions($sPrefix = '')
  2280. {
  2281. if ($sPrefix == '')
  2282. {
  2283. return array('' => $this->GetCode());
  2284. }
  2285. else
  2286. {
  2287. return $sPrefix;
  2288. }
  2289. }
  2290. public function GetLabel()
  2291. {
  2292. $oRemoteAtt = $this->GetExtAttDef();
  2293. $sDefault = $oRemoteAtt->GetLabel();
  2294. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $sDefault);
  2295. }
  2296. public function GetDescription()
  2297. {
  2298. $oRemoteAtt = $this->GetExtAttDef();
  2299. $sDefault = $oRemoteAtt->GetDescription();
  2300. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', $sDefault);
  2301. }
  2302. public function GetHelpOnEdition()
  2303. {
  2304. $oRemoteAtt = $this->GetExtAttDef();
  2305. $sDefault = $oRemoteAtt->GetHelpOnEdition();
  2306. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', $sDefault);
  2307. }
  2308. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  2309. {
  2310. switch($iType)
  2311. {
  2312. case EXTKEY_ABSOLUTE:
  2313. // see further
  2314. $oRemoteAtt = $this->GetExtAttDef();
  2315. return $oRemoteAtt->IsExternalKey($iType);
  2316. case EXTKEY_RELATIVE:
  2317. return false;
  2318. default:
  2319. throw new CoreException("Unexpected value for argument iType: '$iType'");
  2320. }
  2321. }
  2322. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  2323. {
  2324. return $this->GetKeyAttDef($iType)->GetTargetClass();
  2325. }
  2326. public function IsExternalField() {return true;}
  2327. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  2328. public function GetExtAttCode() {return $this->Get("target_attcode");}
  2329. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  2330. {
  2331. switch($iType)
  2332. {
  2333. case EXTKEY_ABSOLUTE:
  2334. // see further
  2335. $oRemoteAtt = $this->GetExtAttDef();
  2336. if ($oRemoteAtt->IsExternalField())
  2337. {
  2338. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  2339. }
  2340. else if ($oRemoteAtt->IsExternalKey())
  2341. {
  2342. return $oRemoteAtt;
  2343. }
  2344. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  2345. case EXTKEY_RELATIVE:
  2346. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  2347. default:
  2348. throw new CoreException("Unexpected value for argument iType: '$iType'");
  2349. }
  2350. }
  2351. public function GetExtAttDef()
  2352. {
  2353. $oKeyAttDef = $this->GetKeyAttDef();
  2354. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $this->Get("target_attcode"));
  2355. 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"));
  2356. return $oExtAttDef;
  2357. }
  2358. public function GetSQLExpr()
  2359. {
  2360. $oExtAttDef = $this->GetExtAttDef();
  2361. return $oExtAttDef->GetSQLExpr();
  2362. }
  2363. public function GetDefaultValue()
  2364. {
  2365. $oExtAttDef = $this->GetExtAttDef();
  2366. return $oExtAttDef->GetDefaultValue();
  2367. }
  2368. public function IsNullAllowed()
  2369. {
  2370. $oExtAttDef = $this->GetExtAttDef();
  2371. return $oExtAttDef->IsNullAllowed();
  2372. }
  2373. public function IsScalar()
  2374. {
  2375. $oExtAttDef = $this->GetExtAttDef();
  2376. return $oExtAttDef->IsScalar();
  2377. }
  2378. public function GetFilterDefinitions()
  2379. {
  2380. return array($this->GetCode() => new FilterFromAttribute($this));
  2381. }
  2382. public function GetBasicFilterOperators()
  2383. {
  2384. $oExtAttDef = $this->GetExtAttDef();
  2385. return $oExtAttDef->GetBasicFilterOperators();
  2386. }
  2387. public function GetBasicFilterLooseOperator()
  2388. {
  2389. $oExtAttDef = $this->GetExtAttDef();
  2390. return $oExtAttDef->GetBasicFilterLooseOperator();
  2391. }
  2392. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2393. {
  2394. $oExtAttDef = $this->GetExtAttDef();
  2395. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  2396. }
  2397. public function GetNullValue()
  2398. {
  2399. $oExtAttDef = $this->GetExtAttDef();
  2400. return $oExtAttDef->GetNullValue();
  2401. }
  2402. public function IsNull($proposedValue)
  2403. {
  2404. $oExtAttDef = $this->GetExtAttDef();
  2405. return $oExtAttDef->IsNull($proposedValue);
  2406. }
  2407. public function MakeRealValue($proposedValue, $oHostObj)
  2408. {
  2409. $oExtAttDef = $this->GetExtAttDef();
  2410. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  2411. }
  2412. public function ScalarToSQL($value)
  2413. {
  2414. // This one could be used in case of filtering only
  2415. $oExtAttDef = $this->GetExtAttDef();
  2416. return $oExtAttDef->ScalarToSQL($value);
  2417. }
  2418. // Do not overload GetSQLExpression here because this is handled in the joins
  2419. //public function GetSQLExpressions($sPrefix = '') {return array();}
  2420. // Here, we get the data...
  2421. public function FromSQLToValue($aCols, $sPrefix = '')
  2422. {
  2423. $oExtAttDef = $this->GetExtAttDef();
  2424. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  2425. }
  2426. public function GetAsHTML($value, $oHostObject = null)
  2427. {
  2428. $oExtAttDef = $this->GetExtAttDef();
  2429. return $oExtAttDef->GetAsHTML($value);
  2430. }
  2431. public function GetAsXML($value, $oHostObject = null)
  2432. {
  2433. $oExtAttDef = $this->GetExtAttDef();
  2434. return $oExtAttDef->GetAsXML($value);
  2435. }
  2436. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null)
  2437. {
  2438. $oExtAttDef = $this->GetExtAttDef();
  2439. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  2440. }
  2441. }
  2442. /**
  2443. * Map a varchar column to an URL (formats the ouput in HMTL)
  2444. *
  2445. * @package iTopORM
  2446. */
  2447. class AttributeURL extends AttributeString
  2448. {
  2449. static protected function ListExpectedParams()
  2450. {
  2451. //return parent::ListExpectedParams();
  2452. return array_merge(parent::ListExpectedParams(), array("target"));
  2453. }
  2454. public function GetEditClass() {return "String";}
  2455. public function GetAsHTML($sValue, $oHostObject = null)
  2456. {
  2457. $sTarget = $this->Get("target");
  2458. if (empty($sTarget)) $sTarget = "_blank";
  2459. $sLabel = Str::pure2html($sValue);
  2460. if (strlen($sLabel) > 40)
  2461. {
  2462. // Truncate the length to about 40 characters, by removing the middle
  2463. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  2464. }
  2465. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  2466. }
  2467. public function GetValidationPattern()
  2468. {
  2469. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  2470. }
  2471. }
  2472. /**
  2473. * A blob is an ormDocument, it is stored as several columns in the database
  2474. *
  2475. * @package iTopORM
  2476. */
  2477. class AttributeBlob extends AttributeDefinition
  2478. {
  2479. static protected function ListExpectedParams()
  2480. {
  2481. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  2482. }
  2483. public function GetEditClass() {return "Document";}
  2484. public function IsDirectField() {return true;}
  2485. public function IsScalar() {return true;}
  2486. public function IsWritable() {return true;}
  2487. public function GetDefaultValue() {return "";}
  2488. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2489. // Facilitate things: allow the user to Set the value from a string
  2490. public function MakeRealValue($proposedValue, $oHostObj)
  2491. {
  2492. if (!is_object($proposedValue))
  2493. {
  2494. return new ormDocument($proposedValue, 'text/plain');
  2495. }
  2496. return $proposedValue;
  2497. }
  2498. public function GetSQLExpressions($sPrefix = '')
  2499. {
  2500. if ($sPrefix == '')
  2501. {
  2502. $sPrefix = $this->GetCode();
  2503. }
  2504. $aColumns = array();
  2505. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2506. $aColumns[''] = $sPrefix.'_mimetype';
  2507. $aColumns['_data'] = $sPrefix.'_data';
  2508. $aColumns['_filename'] = $sPrefix.'_filename';
  2509. return $aColumns;
  2510. }
  2511. public function FromSQLToValue($aCols, $sPrefix = '')
  2512. {
  2513. if (!isset($aCols[$sPrefix]))
  2514. {
  2515. $sAvailable = implode(', ', array_keys($aCols));
  2516. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2517. }
  2518. $sMimeType = $aCols[$sPrefix];
  2519. if (!isset($aCols[$sPrefix.'_data']))
  2520. {
  2521. $sAvailable = implode(', ', array_keys($aCols));
  2522. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  2523. }
  2524. $data = $aCols[$sPrefix.'_data'];
  2525. if (!isset($aCols[$sPrefix.'_filename']))
  2526. {
  2527. $sAvailable = implode(', ', array_keys($aCols));
  2528. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  2529. }
  2530. $sFileName = $aCols[$sPrefix.'_filename'];
  2531. $value = new ormDocument($data, $sMimeType, $sFileName);
  2532. return $value;
  2533. }
  2534. public function GetSQLValues($value)
  2535. {
  2536. // #@# Optimization: do not load blobs anytime
  2537. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2538. // using memory in case a temporary table has to be created
  2539. // (temporary tables created on disk)
  2540. // We will have to remove the blobs from the list of attributes when doing the select
  2541. // then the use of Get() should finalize the load
  2542. if ($value instanceOf ormDocument)
  2543. {
  2544. $aValues = array();
  2545. $aValues[$this->GetCode().'_data'] = $value->GetData();
  2546. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  2547. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  2548. }
  2549. else
  2550. {
  2551. $aValues = array();
  2552. $aValues[$this->GetCode().'_data'] = '';
  2553. $aValues[$this->GetCode().'_mimetype'] = '';
  2554. $aValues[$this->GetCode().'_filename'] = '';
  2555. }
  2556. return $aValues;
  2557. }
  2558. public function GetSQLColumns()
  2559. {
  2560. $aColumns = array();
  2561. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  2562. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  2563. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  2564. return $aColumns;
  2565. }
  2566. public function GetFilterDefinitions()
  2567. {
  2568. return array();
  2569. // still not working... see later...
  2570. return array(
  2571. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  2572. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  2573. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  2574. );
  2575. }
  2576. public function GetBasicFilterOperators()
  2577. {
  2578. return array();
  2579. }
  2580. public function GetBasicFilterLooseOperator()
  2581. {
  2582. return '=';
  2583. }
  2584. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2585. {
  2586. return 'true';
  2587. }
  2588. public function GetAsHTML($value, $oHostObject = null)
  2589. {
  2590. if (is_object($value))
  2591. {
  2592. return $value->GetAsHTML();
  2593. }
  2594. }
  2595. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2596. {
  2597. return ''; // Not exportable in CSV !
  2598. }
  2599. public function GetAsXML($value, $oHostObject = null)
  2600. {
  2601. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  2602. }
  2603. }
  2604. /**
  2605. * One way encrypted (hashed) password
  2606. */
  2607. class AttributeOneWayPassword extends AttributeDefinition
  2608. {
  2609. static protected function ListExpectedParams()
  2610. {
  2611. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  2612. }
  2613. public function GetEditClass() {return "One Way Password";}
  2614. public function IsDirectField() {return true;}
  2615. public function IsScalar() {return true;}
  2616. public function IsWritable() {return true;}
  2617. public function GetDefaultValue() {return "";}
  2618. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2619. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  2620. public function MakeRealValue($proposedValue, $oHostObj)
  2621. {
  2622. $oPassword = $proposedValue;
  2623. if (!is_object($oPassword))
  2624. {
  2625. $oPassword = new ormPassword('', '');
  2626. $oPassword->SetPassword($proposedValue);
  2627. }
  2628. return $oPassword;
  2629. }
  2630. public function GetSQLExpressions($sPrefix = '')
  2631. {
  2632. if ($sPrefix == '')
  2633. {
  2634. $sPrefix = $this->GetCode();
  2635. }
  2636. $aColumns = array();
  2637. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2638. $aColumns[''] = $sPrefix.'_hash';
  2639. $aColumns['_salt'] = $sPrefix.'_salt';
  2640. return $aColumns;
  2641. }
  2642. public function FromSQLToValue($aCols, $sPrefix = '')
  2643. {
  2644. if (!isset($aCols[$sPrefix]))
  2645. {
  2646. $sAvailable = implode(', ', array_keys($aCols));
  2647. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2648. }
  2649. $hashed = $aCols[$sPrefix];
  2650. if (!isset($aCols[$sPrefix.'_salt']))
  2651. {
  2652. $sAvailable = implode(', ', array_keys($aCols));
  2653. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  2654. }
  2655. $sSalt = $aCols[$sPrefix.'_salt'];
  2656. $value = new ormPassword($hashed, $sSalt);
  2657. return $value;
  2658. }
  2659. public function GetSQLValues($value)
  2660. {
  2661. // #@# Optimization: do not load blobs anytime
  2662. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2663. // using memory in case a temporary table has to be created
  2664. // (temporary tables created on disk)
  2665. // We will have to remove the blobs from the list of attributes when doing the select
  2666. // then the use of Get() should finalize the load
  2667. if ($value instanceOf ormPassword)
  2668. {
  2669. $aValues = array();
  2670. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  2671. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  2672. }
  2673. else
  2674. {
  2675. $aValues = array();
  2676. $aValues[$this->GetCode().'_hash'] = '';
  2677. $aValues[$this->GetCode().'_salt'] = '';
  2678. }
  2679. return $aValues;
  2680. }
  2681. public function GetSQLColumns()
  2682. {
  2683. $aColumns = array();
  2684. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  2685. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  2686. return $aColumns;
  2687. }
  2688. public function GetImportColumns()
  2689. {
  2690. $aColumns = array();
  2691. $aColumns[$this->GetCode()] = 'TINYTEXT';
  2692. return $aColumns;
  2693. }
  2694. public function FromImportToValue($aCols, $sPrefix = '')
  2695. {
  2696. if (!isset($aCols[$sPrefix]))
  2697. {
  2698. $sAvailable = implode(', ', array_keys($aCols));
  2699. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2700. }
  2701. $sClearPwd = $aCols[$sPrefix];
  2702. $oPassword = new ormPassword('', '');
  2703. $oPassword->SetPassword($sClearPwd);
  2704. return $oPassword;
  2705. }
  2706. public function GetFilterDefinitions()
  2707. {
  2708. return array();
  2709. // still not working... see later...
  2710. }
  2711. public function GetBasicFilterOperators()
  2712. {
  2713. return array();
  2714. }
  2715. public function GetBasicFilterLooseOperator()
  2716. {
  2717. return '=';
  2718. }
  2719. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2720. {
  2721. return 'true';
  2722. }
  2723. public function GetAsHTML($value, $oHostObject = null)
  2724. {
  2725. if (is_object($value))
  2726. {
  2727. return $value->GetAsHTML();
  2728. }
  2729. }
  2730. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2731. {
  2732. return ''; // Not exportable in CSV
  2733. }
  2734. public function GetAsXML($value, $oHostObject = null)
  2735. {
  2736. return ''; // Not exportable in XML
  2737. }
  2738. }
  2739. // Indexed array having two dimensions
  2740. class AttributeTable extends AttributeText
  2741. {
  2742. public function GetEditClass() {return "Text";}
  2743. protected function GetSQLCol() {return "TEXT";}
  2744. public function GetMaxSize()
  2745. {
  2746. return null;
  2747. }
  2748. // Facilitate things: allow the user to Set the value from a string
  2749. public function MakeRealValue($proposedValue, $oHostObj)
  2750. {
  2751. if (!is_array($proposedValue))
  2752. {
  2753. return array(0 => array(0 => $proposedValue));
  2754. }
  2755. return $proposedValue;
  2756. }
  2757. public function FromSQLToValue($aCols, $sPrefix = '')
  2758. {
  2759. try
  2760. {
  2761. $value = @unserialize($aCols[$sPrefix.'']);
  2762. if ($value === false)
  2763. {
  2764. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  2765. }
  2766. }
  2767. catch(Exception $e)
  2768. {
  2769. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  2770. }
  2771. return $value;
  2772. }
  2773. public function GetSQLValues($value)
  2774. {
  2775. $aValues = array();
  2776. $aValues[$this->Get("sql")] = serialize($value);
  2777. return $aValues;
  2778. }
  2779. public function GetAsHTML($value, $oHostObject = null)
  2780. {
  2781. if (!is_array($value))
  2782. {
  2783. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2784. }
  2785. if (count($value) == 0)
  2786. {
  2787. return "";
  2788. }
  2789. $sRes = "<TABLE class=\"listResults\">";
  2790. $sRes .= "<TBODY>";
  2791. foreach($value as $iRow => $aRawData)
  2792. {
  2793. $sRes .= "<TR>";
  2794. foreach ($aRawData as $iCol => $cell)
  2795. {
  2796. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  2797. $sRes .= "<TD>$sCell</TD>";
  2798. }
  2799. $sRes .= "</TR>";
  2800. }
  2801. $sRes .= "</TBODY>";
  2802. $sRes .= "</TABLE>";
  2803. return $sRes;
  2804. }
  2805. }
  2806. // The PHP value is a hash array, it is stored as a TEXT column
  2807. class AttributePropertySet extends AttributeTable
  2808. {
  2809. public function GetEditClass() {return "Text";}
  2810. protected function GetSQLCol() {return "TEXT";}
  2811. // Facilitate things: allow the user to Set the value from a string
  2812. public function MakeRealValue($proposedValue, $oHostObj)
  2813. {
  2814. if (!is_array($proposedValue))
  2815. {
  2816. return array('?' => (string)$proposedValue);
  2817. }
  2818. return $proposedValue;
  2819. }
  2820. public function GetAsHTML($value, $oHostObject = null)
  2821. {
  2822. if (!is_array($value))
  2823. {
  2824. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2825. }
  2826. if (count($value) == 0)
  2827. {
  2828. return "";
  2829. }
  2830. $sRes = "<TABLE class=\"listResults\">";
  2831. $sRes .= "<TBODY>";
  2832. foreach($value as $sProperty => $sValue)
  2833. {
  2834. $sRes .= "<TR>";
  2835. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  2836. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  2837. $sRes .= "</TR>";
  2838. }
  2839. $sRes .= "</TBODY>";
  2840. $sRes .= "</TABLE>";
  2841. return $sRes;
  2842. }
  2843. }
  2844. /**
  2845. * The attribute dedicated to the friendly name automatic attribute (not written)
  2846. *
  2847. * @package iTopORM
  2848. */
  2849. class AttributeComputedFieldVoid extends AttributeDefinition
  2850. {
  2851. static protected function ListExpectedParams()
  2852. {
  2853. return array_merge(parent::ListExpectedParams(), array());
  2854. }
  2855. public function GetEditClass() {return "";}
  2856. public function GetValuesDef() {return null;}
  2857. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  2858. public function IsDirectField() {return true;}
  2859. public function IsScalar() {return true;}
  2860. public function IsWritable() {return false;}
  2861. public function GetSQLExpr() {return null;}
  2862. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  2863. public function IsNullAllowed() {return false;}
  2864. //
  2865. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  2866. public function GetSQLExpressions($sPrefix = '')
  2867. {
  2868. if ($sPrefix == '')
  2869. {
  2870. $sPrefix = $this->GetCode();
  2871. }
  2872. return array('' => $sPrefix);
  2873. }
  2874. public function FromSQLToValue($aCols, $sPrefix = '')
  2875. {
  2876. return null;
  2877. }
  2878. public function GetSQLValues($value)
  2879. {
  2880. return array();
  2881. }
  2882. public function GetSQLColumns()
  2883. {
  2884. return array();
  2885. }
  2886. public function GetFilterDefinitions()
  2887. {
  2888. return array($this->GetCode() => new FilterFromAttribute($this));
  2889. }
  2890. public function GetBasicFilterOperators()
  2891. {
  2892. return array();
  2893. }
  2894. public function GetBasicFilterLooseOperator()
  2895. {
  2896. return "=";
  2897. }
  2898. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2899. {
  2900. $sQValue = CMDBSource::Quote($value);
  2901. switch ($sOpCode)
  2902. {
  2903. case '!=':
  2904. return $this->GetSQLExpr()." != $sQValue";
  2905. break;
  2906. case '=':
  2907. default:
  2908. return $this->GetSQLExpr()." = $sQValue";
  2909. }
  2910. }
  2911. }
  2912. /**
  2913. * The attribute dedicated to the friendly name automatic attribute (not written)
  2914. *
  2915. * @package iTopORM
  2916. */
  2917. class AttributeFriendlyName extends AttributeComputedFieldVoid
  2918. {
  2919. public function __construct($sCode, $sExtKeyAttCode)
  2920. {
  2921. $this->m_sCode = $sCode;
  2922. $aParams = array();
  2923. // $aParams["is_null_allowed"] = false,
  2924. $aParams["default_value"] = '';
  2925. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  2926. parent::__construct($sCode, $aParams);
  2927. $this->m_sValue = $this->Get("default_value");
  2928. }
  2929. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  2930. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  2931. protected function GetSQLCol() {return "";}
  2932. public function FromSQLToValue($aCols, $sPrefix = '')
  2933. {
  2934. $sValue = $aCols[$sPrefix];
  2935. return $sValue;
  2936. }
  2937. /**
  2938. * Encrypt the value before storing it in the database
  2939. */
  2940. public function GetSQLValues($value)
  2941. {
  2942. return array();
  2943. }
  2944. public function IsWritable()
  2945. {
  2946. return false;
  2947. }
  2948. public function IsDirectField()
  2949. {
  2950. return false;
  2951. }
  2952. public function SetFixedValue($sValue)
  2953. {
  2954. $this->m_sValue = $sValue;
  2955. }
  2956. public function GetDefaultValue()
  2957. {
  2958. return $this->m_sValue;
  2959. }
  2960. public function GetAsHTML($sValue, $oHostObject = null)
  2961. {
  2962. return Str::pure2html((string)$sValue);
  2963. }
  2964. }
  2965. ?>