attributedef.class.inc.php 88 KB

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