attributedef.class.inc.php 88 KB

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