attributedef.class.inc.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818
  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. * An attibute that matches one of the language codes availables in the dictionnary
  608. *
  609. * @package iTopORM
  610. */
  611. class AttributeApplicationLanguage extends AttributeString
  612. {
  613. static protected function ListExpectedParams()
  614. {
  615. return parent::ListExpectedParams();
  616. }
  617. public function __construct($sCode, $aParams)
  618. {
  619. $this->m_sCode = $sCode;
  620. $aAvailableLanguages = Dict::GetLanguages();
  621. $aLanguageCodes = array();
  622. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  623. {
  624. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  625. }
  626. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  627. parent::__construct($sCode, $aParams);
  628. }
  629. public function RequiresIndex()
  630. {
  631. return true;
  632. }
  633. }
  634. /**
  635. * The attribute dedicated to the finalclass automatic attribute
  636. *
  637. * @package iTopORM
  638. */
  639. class AttributeFinalClass extends AttributeString
  640. {
  641. public function __construct($sCode, $aParams)
  642. {
  643. $this->m_sCode = $sCode;
  644. $aParams["allowed_values"] = null;
  645. parent::__construct($sCode, $aParams);
  646. $this->m_sValue = $this->Get("default_value");
  647. }
  648. public function IsWritable()
  649. {
  650. return false;
  651. }
  652. public function RequiresIndex()
  653. {
  654. return true;
  655. }
  656. public function SetFixedValue($sValue)
  657. {
  658. $this->m_sValue = $sValue;
  659. }
  660. public function GetDefaultValue()
  661. {
  662. return $this->m_sValue;
  663. }
  664. public function GetAsHTML($sValue)
  665. {
  666. return MetaModel::GetName($sValue);
  667. }
  668. }
  669. /**
  670. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  671. *
  672. * @package iTopORM
  673. */
  674. class AttributePassword extends AttributeString
  675. {
  676. static protected function ListExpectedParams()
  677. {
  678. return parent::ListExpectedParams();
  679. //return array_merge(parent::ListExpectedParams(), array());
  680. }
  681. public function GetEditClass() {return "Password";}
  682. protected function GetSQLCol() {return "VARCHAR(64)";}
  683. public function GetFilterDefinitions()
  684. {
  685. // not allowed to search on passwords!
  686. return array();
  687. }
  688. }
  689. /**
  690. * Map a text column (size > ?) to an attribute
  691. *
  692. * @package iTopORM
  693. */
  694. class AttributeText extends AttributeString
  695. {
  696. public function GetType() {return "Text";}
  697. public function GetTypeDesc() {return "Multiline character string";}
  698. public function GetEditClass() {return "Text";}
  699. protected function GetSQLCol() {return "TEXT";}
  700. public function GetAsHTML($sValue)
  701. {
  702. return str_replace("\n", "<br>\n", parent::GetAsHTML($sValue));
  703. }
  704. public function GetAsXML($value)
  705. {
  706. return Str::pure2xml($value);
  707. }
  708. }
  709. /**
  710. * Specialization of a string: email
  711. *
  712. * @package iTopORM
  713. */
  714. class AttributeEmailAddress extends AttributeString
  715. {
  716. public function GetTypeDesc() {return "Email address(es)";}
  717. public function GetValidationPattern()
  718. {
  719. return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  720. }
  721. }
  722. /**
  723. * Specialization of a string: IP address
  724. *
  725. * @package iTopORM
  726. */
  727. class AttributeIPAddress extends AttributeString
  728. {
  729. public function GetTypeDesc() {return "IP address";}
  730. public function GetValidationPattern()
  731. {
  732. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  733. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  734. }
  735. }
  736. /**
  737. * Specialization of a string: OQL expression
  738. *
  739. * @package iTopORM
  740. */
  741. class AttributeOQL extends AttributeString
  742. {
  743. public function GetTypeDesc() {return "OQL expression";}
  744. }
  745. /**
  746. * Specialization of a string: template
  747. *
  748. * @package iTopORM
  749. */
  750. class AttributeTemplateString extends AttributeString
  751. {
  752. public function GetTypeDesc() {return "Template string";}
  753. }
  754. /**
  755. * Specialization of a text: template
  756. *
  757. * @package iTopORM
  758. */
  759. class AttributeTemplateText extends AttributeText
  760. {
  761. public function GetTypeDesc() {return "Multiline template string";}
  762. }
  763. /**
  764. * Map a enum column to an attribute
  765. *
  766. * @package iTopORM
  767. */
  768. class AttributeEnum extends AttributeString
  769. {
  770. static protected function ListExpectedParams()
  771. {
  772. return parent::ListExpectedParams();
  773. //return array_merge(parent::ListExpectedParams(), array());
  774. }
  775. public function GetType() {return "Enum";}
  776. public function GetTypeDesc() {return "List of predefined alphanumeric strings";}
  777. public function GetEditClass() {return "String";}
  778. protected function GetSQLCol()
  779. {
  780. $oValDef = $this->GetValuesDef();
  781. if ($oValDef)
  782. {
  783. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  784. }
  785. else
  786. {
  787. $aValues = array();
  788. }
  789. if (count($aValues) > 0)
  790. {
  791. // The syntax used here do matters
  792. // In particular, I had to remove unnecessary spaces to
  793. // make sure that this string will match the field type returned by the DB
  794. // (used to perform a comparison between the current DB format and the data model)
  795. return "ENUM(".implode(",", $aValues).")";
  796. }
  797. else
  798. {
  799. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  800. }
  801. }
  802. public function RequiresIndex()
  803. {
  804. return false;
  805. }
  806. public function GetBasicFilterOperators()
  807. {
  808. return parent::GetBasicFilterOperators();
  809. }
  810. public function GetBasicFilterLooseOperator()
  811. {
  812. return parent::GetBasicFilterLooseOperator();
  813. }
  814. public function GetBasicFilterSQLExpr($sOpCode, $value)
  815. {
  816. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  817. }
  818. public function GetAsHTML($sValue)
  819. {
  820. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  821. // later, we could imagine a detailed description in the title
  822. return "<span title=\"\">".parent::GetAsHtml($sLabel)."</span>";
  823. }
  824. public function GetEditValue($sValue)
  825. {
  826. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  827. return $sLabel;
  828. }
  829. public function GetAllowedValues($aArgs = array(), $sBeginsWith = '')
  830. {
  831. $aRawValues = parent::GetAllowedValues($aArgs, $sBeginsWith);
  832. $aLocalizedValues = array();
  833. foreach ($aRawValues as $sKey => $sValue)
  834. {
  835. $aLocalizedValues[$sKey] = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sKey, $sKey);
  836. }
  837. return $aLocalizedValues;
  838. }
  839. }
  840. /**
  841. * Map a date+time column to an attribute
  842. *
  843. * @package iTopORM
  844. */
  845. class AttributeDate extends AttributeDBField
  846. {
  847. const MYDATEFORMAT = "Y-m-d";
  848. static public function InitStatics()
  849. {
  850. // Nothing to do...
  851. }
  852. static protected function ListExpectedParams()
  853. {
  854. return parent::ListExpectedParams();
  855. //return array_merge(parent::ListExpectedParams(), array());
  856. }
  857. public function GetType() {return "Date";}
  858. public function GetTypeDesc() {return "Date";}
  859. public function GetEditClass() {return "Date";}
  860. protected function GetSQLCol() {return "DATE";}
  861. // #@# THIS HAS TO REVISED
  862. // Having null not allowed was interpreted by mySQL
  863. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  864. // Then, on each update of the record, the field was modified.
  865. // We will have to specify the default value if we want to restore this option
  866. // In fact, we could also have more verbs dedicated to the DB:
  867. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  868. public function IsNullAllowed() {return true;}
  869. public function GetDefaultValue()
  870. {
  871. $default = parent::GetDefaultValue();
  872. if (!parent::IsNullAllowed())
  873. {
  874. if (empty($default))
  875. {
  876. $default = date("Y-m-d");
  877. }
  878. }
  879. return $default;
  880. }
  881. // END OF THE WORKAROUND
  882. ///////////////////////////////////////////////////////////////
  883. public function GetValidationPattern()
  884. {
  885. 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)))$";
  886. }
  887. public function GetBasicFilterOperators()
  888. {
  889. return array(
  890. "="=>"equals",
  891. "!="=>"differs from",
  892. "<"=>"before",
  893. "<="=>"before",
  894. ">"=>"after (strictly)",
  895. ">="=>"after",
  896. "SameMonth"=>"same year/month",
  897. "SameYear"=>"same year",
  898. "Today"=>"today",
  899. ">|"=>"after today + N days",
  900. "<|"=>"before today + N days",
  901. "=|"=>"equals today + N days",
  902. );
  903. }
  904. public function GetBasicFilterLooseOperator()
  905. {
  906. // Unless we implement a "same xxx, depending on given precision" !
  907. return "=";
  908. }
  909. public function GetBasicFilterSQLExpr($sOpCode, $value)
  910. {
  911. $sQValue = CMDBSource::Quote($value);
  912. switch ($sOpCode)
  913. {
  914. case '=':
  915. case '!=':
  916. case '<':
  917. case '<=':
  918. case '>':
  919. case '>=':
  920. return $this->GetSQLExpr()." $sOpCode $sQValue";
  921. case 'SameMonth':
  922. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  923. case 'SameYear':
  924. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  925. case 'Today':
  926. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  927. case '>|':
  928. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  929. case '<|':
  930. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  931. case '=|':
  932. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  933. default:
  934. return $this->GetSQLExpr()." = $sQValue";
  935. }
  936. }
  937. public function MakeRealValue($proposedValue)
  938. {
  939. if (!is_numeric($proposedValue))
  940. {
  941. return $proposedValue;
  942. }
  943. else
  944. {
  945. return date("Y-m-d", $proposedValue);
  946. }
  947. throw new CoreException("Invalid type for a date (found ".gettype($proposedValue)." and accepting string/int/DateTime)");
  948. return null;
  949. }
  950. public function ScalarToSQL($value)
  951. {
  952. if (empty($value))
  953. {
  954. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  955. return '0000-00-00';
  956. }
  957. return $value;
  958. }
  959. public function GetAsHTML($value)
  960. {
  961. return Str::pure2html($value);
  962. }
  963. public function GetAsXML($value)
  964. {
  965. return Str::pure2xml($value);
  966. }
  967. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  968. {
  969. $sFrom = array("\r\n", $sTextQualifier);
  970. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  971. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  972. return '"'.$sEscaped.'"';
  973. }
  974. }
  975. // Init static constant once for all (remove when PHP allows real static const)
  976. AttributeDate::InitStatics();
  977. /**
  978. * Map a date+time column to an attribute
  979. *
  980. * @package iTopORM
  981. */
  982. class AttributeDateTime extends AttributeDBField
  983. {
  984. const MYDATEFORMAT = "Y-m-d H:i:s";
  985. //const MYDATETIMEZONE = "UTC";
  986. const MYDATETIMEZONE = "Europe/Paris";
  987. static protected $const_TIMEZONE = null; // set once for all upon object construct
  988. static public function InitStatics()
  989. {
  990. // Init static constant once for all (remove when PHP allows real static const)
  991. self::$const_TIMEZONE = new DateTimeZone(self::MYDATETIMEZONE);
  992. // #@# Init default timezone -> do not get a notice... to be improved !!!
  993. // duplicated in the email test page (the mail function does trigger a notice as well)
  994. date_default_timezone_set(self::MYDATETIMEZONE);
  995. }
  996. static protected function ListExpectedParams()
  997. {
  998. return parent::ListExpectedParams();
  999. //return array_merge(parent::ListExpectedParams(), array());
  1000. }
  1001. public function GetType() {return "Date";}
  1002. public function GetTypeDesc() {return "Date and time";}
  1003. public function GetEditClass() {return "DateTime";}
  1004. protected function GetSQLCol() {return "TIMESTAMP";}
  1005. // #@# THIS HAS TO REVISED
  1006. // Having null not allowed was interpreted by mySQL
  1007. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  1008. // Then, on each update of the record, the field was modified.
  1009. // We will have to specify the default value if we want to restore this option
  1010. // In fact, we could also have more verbs dedicated to the DB:
  1011. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  1012. public function IsNullAllowed() {return true;}
  1013. public function GetDefaultValue()
  1014. {
  1015. $default = parent::GetDefaultValue();
  1016. if (!parent::IsNullAllowed())
  1017. {
  1018. if (empty($default))
  1019. {
  1020. $default = date("Y-m-d H:i");
  1021. }
  1022. }
  1023. return $default;
  1024. }
  1025. // END OF THE WORKAROUND
  1026. ///////////////////////////////////////////////////////////////
  1027. public function GetValidationPattern()
  1028. {
  1029. 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$";
  1030. }
  1031. public function GetBasicFilterOperators()
  1032. {
  1033. return array(
  1034. "="=>"equals",
  1035. "!="=>"differs from",
  1036. "<"=>"before",
  1037. "<="=>"before",
  1038. ">"=>"after (strictly)",
  1039. ">="=>"after",
  1040. "SameDay"=>"same day (strip time)",
  1041. "SameMonth"=>"same year/month",
  1042. "SameYear"=>"same year",
  1043. "Today"=>"today",
  1044. ">|"=>"after today + N days",
  1045. "<|"=>"before today + N days",
  1046. "=|"=>"equals today + N days",
  1047. );
  1048. }
  1049. public function GetBasicFilterLooseOperator()
  1050. {
  1051. // Unless we implement a "same xxx, depending on given precision" !
  1052. return "=";
  1053. }
  1054. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1055. {
  1056. $sQValue = CMDBSource::Quote($value);
  1057. switch ($sOpCode)
  1058. {
  1059. case '=':
  1060. case '!=':
  1061. case '<':
  1062. case '<=':
  1063. case '>':
  1064. case '>=':
  1065. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1066. case 'SameDay':
  1067. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  1068. case 'SameMonth':
  1069. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  1070. case 'SameYear':
  1071. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  1072. case 'Today':
  1073. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  1074. case '>|':
  1075. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1076. case '<|':
  1077. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1078. case '=|':
  1079. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1080. default:
  1081. return $this->GetSQLExpr()." = $sQValue";
  1082. }
  1083. }
  1084. public function MakeRealValue($proposedValue)
  1085. {
  1086. if (!is_numeric($proposedValue))
  1087. {
  1088. return $proposedValue;
  1089. }
  1090. else
  1091. {
  1092. return date("Y-m-d H:i:s", $proposedValue);
  1093. }
  1094. throw new CoreException("Invalid type for a date (found ".gettype($proposedValue)." and accepting string/int/DateTime)");
  1095. return null;
  1096. }
  1097. public function ScalarToSQL($value)
  1098. {
  1099. if (empty($value))
  1100. {
  1101. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  1102. return '0000-00-00 00:00:00';
  1103. }
  1104. return $value;
  1105. }
  1106. public function GetAsHTML($value)
  1107. {
  1108. return Str::pure2html($value);
  1109. }
  1110. public function GetAsXML($value)
  1111. {
  1112. return Str::pure2xml($value);
  1113. }
  1114. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1115. {
  1116. $sFrom = array("\r\n", $sTextQualifier);
  1117. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1118. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1119. return '"'.$sEscaped.'"';
  1120. }
  1121. }
  1122. // Init static constant once for all (remove when PHP allows real static const)
  1123. AttributeDateTime::InitStatics();
  1124. /**
  1125. * Map a foreign key to an attribute
  1126. * AttributeExternalKey and AttributeExternalField may be an external key
  1127. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  1128. * where an AttributeExternalField corresponds to a column into another table (class)
  1129. *
  1130. * @package iTopORM
  1131. */
  1132. class AttributeExternalKey extends AttributeDBFieldVoid
  1133. {
  1134. static protected function ListExpectedParams()
  1135. {
  1136. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  1137. }
  1138. public function GetType() {return "Extkey";}
  1139. public function GetTypeDesc() {return "Link to another object";}
  1140. public function GetEditClass() {return "ExtKey";}
  1141. protected function GetSQLCol() {return "INT(11)";}
  1142. public function RequiresIndex()
  1143. {
  1144. return true;
  1145. }
  1146. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  1147. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  1148. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  1149. public function GetKeyAttCode() {return $this->GetCode();}
  1150. public function GetDefaultValue() {return 0;}
  1151. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  1152. public function GetNullValue() {return 0;}
  1153. public function GetBasicFilterOperators()
  1154. {
  1155. return parent::GetBasicFilterOperators();
  1156. }
  1157. public function GetBasicFilterLooseOperator()
  1158. {
  1159. return parent::GetBasicFilterLooseOperator();
  1160. }
  1161. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1162. {
  1163. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1164. }
  1165. // overloaded here so that an ext key always have the answer to
  1166. // "what are your possible values?"
  1167. public function GetValuesDef()
  1168. {
  1169. $oValSetDef = $this->Get("allowed_values");
  1170. if (!$oValSetDef)
  1171. {
  1172. // Let's propose every existing value
  1173. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1174. }
  1175. return $oValSetDef;
  1176. }
  1177. public function GetAllowedValues($aArgs = array(), $sBeginsWith = '')
  1178. {
  1179. try
  1180. {
  1181. return parent::GetAllowedValues($aArgs, $sBeginsWith);
  1182. }
  1183. catch (MissingQueryArgument $e)
  1184. {
  1185. // Some required arguments could not be found, enlarge to any existing value
  1186. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1187. return $oValSetDef->GetValues($aArgs, $sBeginsWith);
  1188. }
  1189. }
  1190. public function GetDeletionPropagationOption()
  1191. {
  1192. return $this->Get("on_target_delete");
  1193. }
  1194. public function MakeRealValue($proposedValue)
  1195. {
  1196. return (int)$proposedValue;
  1197. }
  1198. }
  1199. /**
  1200. * An attribute which corresponds to an external key (direct or indirect)
  1201. *
  1202. * @package iTopORM
  1203. */
  1204. class AttributeExternalField extends AttributeDefinition
  1205. {
  1206. static protected function ListExpectedParams()
  1207. {
  1208. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  1209. }
  1210. public function GetType() {return "ExtkeyField";}
  1211. public function GetTypeDesc() {return "Field of an object pointed to by the current object";}
  1212. public function GetEditClass() {return "ExtField";}
  1213. protected function GetSQLCol()
  1214. {
  1215. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  1216. $oExtAttDef = $this->GetExtAttDef();
  1217. return $oExtAttDef->GetSQLCol();
  1218. }
  1219. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  1220. {
  1221. switch($iType)
  1222. {
  1223. case EXTKEY_ABSOLUTE:
  1224. // see further
  1225. $oRemoteAtt = $this->GetExtAttDef();
  1226. return $oRemoteAtt->IsExternalKey($iType);
  1227. case EXTKEY_RELATIVE:
  1228. return false;
  1229. default:
  1230. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1231. }
  1232. }
  1233. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  1234. {
  1235. return $this->GetKeyAttDef($iType)->GetTargetClass();
  1236. }
  1237. public function IsExternalField() {return true;}
  1238. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  1239. public function GetExtAttCode() {return $this->Get("target_attcode");}
  1240. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  1241. {
  1242. switch($iType)
  1243. {
  1244. case EXTKEY_ABSOLUTE:
  1245. // see further
  1246. $oRemoteAtt = $this->GetExtAttDef();
  1247. if ($oRemoteAtt->IsExternalField())
  1248. {
  1249. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1250. }
  1251. else if ($oRemoteAtt->IsExternalKey())
  1252. {
  1253. return $oRemoteAtt;
  1254. }
  1255. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  1256. case EXTKEY_RELATIVE:
  1257. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  1258. default:
  1259. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1260. }
  1261. }
  1262. public function GetExtAttDef()
  1263. {
  1264. $oKeyAttDef = $this->GetKeyAttDef();
  1265. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->Get("targetclass"), $this->Get("target_attcode"));
  1266. 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"));
  1267. return $oExtAttDef;
  1268. }
  1269. public function GetSQLExpr()
  1270. {
  1271. $oExtAttDef = $this->GetExtAttDef();
  1272. return $oExtAttDef->GetSQLExpr();
  1273. }
  1274. public function GetDefaultValue()
  1275. {
  1276. $oExtAttDef = $this->GetExtAttDef();
  1277. return $oExtAttDef->GetDefaultValue();
  1278. }
  1279. public function IsNullAllowed()
  1280. {
  1281. $oExtAttDef = $this->GetExtAttDef();
  1282. return $oExtAttDef->IsNullAllowed();
  1283. }
  1284. public function IsScalar()
  1285. {
  1286. $oExtAttDef = $this->GetExtAttDef();
  1287. return $oExtAttDef->IsScalar();
  1288. }
  1289. public function GetFilterDefinitions()
  1290. {
  1291. return array($this->GetCode() => new FilterFromAttribute($this));
  1292. }
  1293. public function GetBasicFilterOperators()
  1294. {
  1295. $oExtAttDef = $this->GetExtAttDef();
  1296. return $oExtAttDef->GetBasicFilterOperators();
  1297. }
  1298. public function GetBasicFilterLooseOperator()
  1299. {
  1300. $oExtAttDef = $this->GetExtAttDef();
  1301. return $oExtAttDef->GetBasicFilterLooseOperator();
  1302. }
  1303. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1304. {
  1305. $oExtAttDef = $this->GetExtAttDef();
  1306. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  1307. }
  1308. public function MakeRealValue($proposedValue)
  1309. {
  1310. $oExtAttDef = $this->GetExtAttDef();
  1311. return $oExtAttDef->MakeRealValue($proposedValue);
  1312. }
  1313. public function ScalarToSQL($value)
  1314. {
  1315. // This one could be used in case of filtering only
  1316. $oExtAttDef = $this->GetExtAttDef();
  1317. return $oExtAttDef->ScalarToSQL($value);
  1318. }
  1319. // Do not overload GetSQLExpression here because this is handled in the joins
  1320. //public function GetSQLExpressions() {return array();}
  1321. // Here, we get the data...
  1322. public function FromSQLToValue($aCols, $sPrefix = '')
  1323. {
  1324. $oExtAttDef = $this->GetExtAttDef();
  1325. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  1326. }
  1327. public function GetAsHTML($value)
  1328. {
  1329. $oExtAttDef = $this->GetExtAttDef();
  1330. return $oExtAttDef->GetAsHTML($value);
  1331. }
  1332. public function GetAsXML($value)
  1333. {
  1334. $oExtAttDef = $this->GetExtAttDef();
  1335. return $oExtAttDef->GetAsXML($value);
  1336. }
  1337. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"')
  1338. {
  1339. $oExtAttDef = $this->GetExtAttDef();
  1340. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  1341. }
  1342. }
  1343. /**
  1344. * Map a varchar column to an URL (formats the ouput in HMTL)
  1345. *
  1346. * @package iTopORM
  1347. */
  1348. class AttributeURL extends AttributeString
  1349. {
  1350. static protected function ListExpectedParams()
  1351. {
  1352. //return parent::ListExpectedParams();
  1353. return array_merge(parent::ListExpectedParams(), array("target"));
  1354. }
  1355. public function GetType() {return "Url";}
  1356. public function GetTypeDesc() {return "Absolute or relative URL as a text string";}
  1357. public function GetEditClass() {return "String";}
  1358. public function GetAsHTML($sValue)
  1359. {
  1360. $sTarget = $this->Get("target");
  1361. if (empty($sTarget)) $sTarget = "_blank";
  1362. $sLabel = Str::pure2html($sValue);
  1363. if (strlen($sLabel) > 40)
  1364. {
  1365. // Truncate the length to about 40 characters, by removing the middle
  1366. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  1367. }
  1368. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  1369. }
  1370. public function GetValidationPattern()
  1371. {
  1372. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  1373. }
  1374. }
  1375. /**
  1376. * A blob is an ormDocument, it is stored as several columns in the database
  1377. *
  1378. * @package iTopORM
  1379. */
  1380. class AttributeBlob extends AttributeDefinition
  1381. {
  1382. static protected function ListExpectedParams()
  1383. {
  1384. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  1385. }
  1386. public function GetType() {return "Blob";}
  1387. public function GetTypeDesc() {return "Document";}
  1388. public function GetEditClass() {return "Document";}
  1389. public function IsDirectField() {return true;}
  1390. public function IsScalar() {return true;}
  1391. public function IsWritable() {return true;}
  1392. public function GetDefaultValue() {return "";}
  1393. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  1394. // Facilitate things: allow the user to Set the value from a string
  1395. public function MakeRealValue($proposedValue)
  1396. {
  1397. if (!is_object($proposedValue))
  1398. {
  1399. return new ormDocument($proposedValue, 'text/plain');
  1400. }
  1401. return $proposedValue;
  1402. }
  1403. public function GetSQLExpressions()
  1404. {
  1405. $aColumns = array();
  1406. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1407. $aColumns[''] = $this->GetCode().'_mimetype';
  1408. $aColumns['_data'] = $this->GetCode().'_data';
  1409. $aColumns['_filename'] = $this->GetCode().'_filename';
  1410. return $aColumns;
  1411. }
  1412. public function FromSQLToValue($aCols, $sPrefix = '')
  1413. {
  1414. if (!isset($aCols[$sPrefix]))
  1415. {
  1416. $sAvailable = implode(', ', array_keys($aCols));
  1417. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1418. }
  1419. $sMimeType = $aCols[$sPrefix];
  1420. if (!isset($aCols[$sPrefix.'_data']))
  1421. {
  1422. $sAvailable = implode(', ', array_keys($aCols));
  1423. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  1424. }
  1425. $data = $aCols[$sPrefix.'_data'];
  1426. if (!isset($aCols[$sPrefix.'_filename']))
  1427. {
  1428. $sAvailable = implode(', ', array_keys($aCols));
  1429. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  1430. }
  1431. $sFileName = $aCols[$sPrefix.'_filename'];
  1432. $value = new ormDocument($data, $sMimeType, $sFileName);
  1433. return $value;
  1434. }
  1435. public function GetSQLValues($value)
  1436. {
  1437. // #@# Optimization: do not load blobs anytime
  1438. // As per mySQL doc, selecting blob columns will prevent mySQL from
  1439. // using memory in case a temporary table has to be created
  1440. // (temporary tables created on disk)
  1441. // We will have to remove the blobs from the list of attributes when doing the select
  1442. // then the use of Get() should finalize the load
  1443. if ($value instanceOf ormDocument)
  1444. {
  1445. $aValues = array();
  1446. $aValues[$this->GetCode().'_data'] = $value->GetData();
  1447. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  1448. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  1449. }
  1450. else
  1451. {
  1452. $aValues = array();
  1453. $aValues[$this->GetCode().'_data'] = '';
  1454. $aValues[$this->GetCode().'_mimetype'] = '';
  1455. $aValues[$this->GetCode().'_filename'] = '';
  1456. }
  1457. return $aValues;
  1458. }
  1459. public function GetSQLColumns()
  1460. {
  1461. $aColumns = array();
  1462. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  1463. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  1464. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  1465. return $aColumns;
  1466. }
  1467. public function GetFilterDefinitions()
  1468. {
  1469. return array();
  1470. // still not working... see later...
  1471. return array(
  1472. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  1473. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  1474. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  1475. );
  1476. }
  1477. public function GetBasicFilterOperators()
  1478. {
  1479. return array();
  1480. }
  1481. public function GetBasicFilterLooseOperator()
  1482. {
  1483. return '=';
  1484. }
  1485. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1486. {
  1487. return 'true';
  1488. }
  1489. public function GetAsHTML($value)
  1490. {
  1491. if (is_object($value))
  1492. {
  1493. return $value->GetAsHTML();
  1494. }
  1495. }
  1496. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1497. {
  1498. return ''; // Not exportable in CSV !
  1499. }
  1500. public function GetAsXML($value)
  1501. {
  1502. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  1503. }
  1504. }
  1505. // Indexed array having two dimensions
  1506. class AttributeTable extends AttributeText
  1507. {
  1508. public function GetType() {return "Table";}
  1509. public function GetTypeDesc() {return "Array with 2 dimensions";}
  1510. public function GetEditClass() {return "Text";}
  1511. protected function GetSQLCol() {return "TEXT";}
  1512. // Facilitate things: allow the user to Set the value from a string
  1513. public function MakeRealValue($proposedValue)
  1514. {
  1515. if (!is_array($proposedValue))
  1516. {
  1517. return array(0 => array(0 => $proposedValue));
  1518. }
  1519. return $proposedValue;
  1520. }
  1521. public function FromSQLToValue($aCols, $sPrefix = '')
  1522. {
  1523. try
  1524. {
  1525. $value = @unserialize($aCols[$sPrefix.'']);
  1526. if ($value === false)
  1527. {
  1528. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  1529. }
  1530. }
  1531. catch(Exception $e)
  1532. {
  1533. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  1534. }
  1535. return $value;
  1536. }
  1537. public function GetSQLValues($value)
  1538. {
  1539. $aValues = array();
  1540. $aValues[$this->Get("sql")] = serialize($value);
  1541. return $aValues;
  1542. }
  1543. public function GetAsHTML($value)
  1544. {
  1545. if (!is_array($value))
  1546. {
  1547. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  1548. }
  1549. if (count($value) == 0)
  1550. {
  1551. return "";
  1552. }
  1553. $sRes = "<TABLE class=\"listResults\">";
  1554. $sRes .= "<TBODY>";
  1555. foreach($value as $iRow => $aRawData)
  1556. {
  1557. $sRes .= "<TR>";
  1558. foreach ($aRawData as $iCol => $cell)
  1559. {
  1560. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  1561. $sRes .= "<TD>$sCell</TD>";
  1562. }
  1563. $sRes .= "</TR>";
  1564. }
  1565. $sRes .= "</TBODY>";
  1566. $sRes .= "</TABLE>";
  1567. return $sRes;
  1568. }
  1569. }
  1570. // The PHP value is a hash array, it is stored as a TEXT column
  1571. class AttributePropertySet extends AttributeTable
  1572. {
  1573. public function GetType() {return "PropertySet";}
  1574. public function GetTypeDesc() {return "List of properties (name and value)";}
  1575. public function GetEditClass() {return "Text";}
  1576. protected function GetSQLCol() {return "TEXT";}
  1577. // Facilitate things: allow the user to Set the value from a string
  1578. public function MakeRealValue($proposedValue)
  1579. {
  1580. if (!is_array($proposedValue))
  1581. {
  1582. return array('?' => (string)$proposedValue);
  1583. }
  1584. return $proposedValue;
  1585. }
  1586. public function GetAsHTML($value)
  1587. {
  1588. if (!is_array($value))
  1589. {
  1590. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  1591. }
  1592. if (count($value) == 0)
  1593. {
  1594. return "";
  1595. }
  1596. $sRes = "<TABLE class=\"listResults\">";
  1597. $sRes .= "<TBODY>";
  1598. foreach($value as $sProperty => $sValue)
  1599. {
  1600. $sRes .= "<TR>";
  1601. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  1602. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  1603. $sRes .= "</TR>";
  1604. }
  1605. $sRes .= "</TBODY>";
  1606. $sRes .= "</TABLE>";
  1607. return $sRes;
  1608. }
  1609. }
  1610. ?>