attributedef.class.inc.php 48 KB

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