attributedef.class.inc.php 73 KB

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