attributedef.class.inc.php 52 KB

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