attributedef.class.inc.php 52 KB

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