attributedef.class.inc.php 49 KB

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