attributedef.class.inc.php 49 KB

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