attributedef.class.inc.php 50 KB

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