attributedef.class.inc.php 51 KB

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