attributedef.class.inc.php 66 KB

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