attributedef.class.inc.php 50 KB

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