attributedef.class.inc.php 55 KB

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