attributedef.class.inc.php 49 KB

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