attributedef.class.inc.php 50 KB

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