attributedef.class.inc.php 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403
  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. require_once('ormpassword.class.inc.php');
  27. /**
  28. * MissingColumnException - sent if an attribute is being created but the column is missing in the row
  29. *
  30. * @package iTopORM
  31. */
  32. class MissingColumnException extends Exception
  33. {}
  34. /**
  35. * add some description here...
  36. *
  37. * @package iTopORM
  38. */
  39. define('EXTKEY_RELATIVE', 1);
  40. /**
  41. * add some description here...
  42. *
  43. * @package iTopORM
  44. */
  45. define('EXTKEY_ABSOLUTE', 2);
  46. /**
  47. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  48. *
  49. * @package iTopORM
  50. */
  51. define('DEL_MANUAL', 1);
  52. /**
  53. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  54. *
  55. * @package iTopORM
  56. */
  57. define('DEL_AUTO', 2);
  58. /**
  59. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  60. *
  61. * @package iTopORM
  62. */
  63. abstract class AttributeDefinition
  64. {
  65. abstract public function GetType();
  66. abstract public function GetTypeDesc();
  67. abstract public function GetEditClass();
  68. protected $m_sCode;
  69. private $m_aParams = array();
  70. protected $m_sHostClass = '!undefined!';
  71. protected function Get($sParamName) {return $this->m_aParams[$sParamName];}
  72. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  73. protected function GetOptional($sParamName, $default)
  74. {
  75. if (array_key_exists($sParamName, $this->m_aParams))
  76. {
  77. return $this->m_aParams[$sParamName];
  78. }
  79. else
  80. {
  81. return $default;
  82. }
  83. }
  84. public function __construct($sCode, $aParams)
  85. {
  86. $this->m_sCode = $sCode;
  87. $this->m_aParams = $aParams;
  88. $this->ConsistencyCheck();
  89. }
  90. public function OverloadParams($aParams)
  91. {
  92. foreach ($aParams as $sParam => $value)
  93. {
  94. if (!array_key_exists($sParam, $this->m_aParams))
  95. {
  96. throw new CoreException("Unknown attribute definition parameter '$sParam', please select a value in {".implode(", ", array_keys($this->m_aParams))."}");
  97. }
  98. else
  99. {
  100. $this->m_aParams[$sParam] = $value;
  101. }
  102. }
  103. }
  104. public function SetHostClass($sHostClass)
  105. {
  106. $this->m_sHostClass = $sHostClass;
  107. }
  108. public function GetHostClass()
  109. {
  110. return $this->m_sHostClass;
  111. }
  112. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  113. // to be overloaded
  114. static protected function ListExpectedParams()
  115. {
  116. return array();
  117. }
  118. private function ConsistencyCheck()
  119. {
  120. // Check that any mandatory param has been specified
  121. //
  122. $aExpectedParams = $this->ListExpectedParams();
  123. foreach($aExpectedParams as $sParamName)
  124. {
  125. if (!array_key_exists($sParamName, $this->m_aParams))
  126. {
  127. $aBacktrace = debug_backtrace();
  128. $sTargetClass = $aBacktrace[2]["class"];
  129. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  130. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  131. }
  132. }
  133. }
  134. // table, key field, name field
  135. public function ListDBJoins()
  136. {
  137. return "";
  138. // e.g: return array("Site", "infrid", "name");
  139. }
  140. public function IsDirectField() {return false;}
  141. public function IsScalar() {return false;}
  142. public function IsLinkSet() {return false;}
  143. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  144. public function IsExternalField() {return false;}
  145. public function IsWritable() {return false;}
  146. public function IsNullAllowed() {return true;}
  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 GetNullValue() {return null;}
  178. public function IsNull($proposedValue) {return is_null($proposedValue);}
  179. public function MakeRealValue($proposedValue) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  180. public function GetSQLExpressions() {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  181. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  182. public function GetSQLColumns() {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  183. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  184. public function RequiresIndex() {return false;}
  185. public function GetValidationPattern()
  186. {
  187. return '';
  188. }
  189. public function CheckFormat($value)
  190. {
  191. return true;
  192. }
  193. public function GetMaxSize()
  194. {
  195. return null;
  196. }
  197. public function MakeValue()
  198. {
  199. $sComputeFunc = $this->Get("compute_func");
  200. if (empty($sComputeFunc)) return null;
  201. return call_user_func($sComputeFunc);
  202. }
  203. abstract public function GetDefaultValue();
  204. //
  205. // To be overloaded in subclasses
  206. //
  207. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  208. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  209. //abstract protected GetBasicFilterHTMLInput();
  210. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  211. public function GetFilterDefinitions()
  212. {
  213. return array();
  214. }
  215. public function GetEditValue($sValue)
  216. {
  217. return (string)$sValue;
  218. }
  219. public function GetAsHTML($sValue)
  220. {
  221. return Str::pure2html((string)$sValue);
  222. }
  223. public function GetAsXML($sValue)
  224. {
  225. return Str::pure2xml((string)$sValue);
  226. }
  227. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  228. {
  229. return (string)$sValue;
  230. }
  231. public function GetAllowedValues($aArgs = array(), $sBeginsWith = '')
  232. {
  233. $oValSetDef = $this->GetValuesDef();
  234. if (!$oValSetDef) return null;
  235. return $oValSetDef->GetValues($aArgs, $sBeginsWith);
  236. }
  237. /**
  238. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  239. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  240. * does nothing special, and just calls the default (loose) operator
  241. * @param string $sSearchText The search string to analyze for smart patterns
  242. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  243. * @param Hash $aParams Values of the query parameters
  244. * @return Expression The search condition to be added (AND) to the current search
  245. */
  246. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  247. {
  248. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  249. $oRightExpr = new VariableExpression($sParamName);
  250. $sOperator = $this->GetBasicFilterLooseOperator();
  251. switch ($sOperator)
  252. {
  253. case 'Contains':
  254. $aParams[$sParamName] = "%$sSearchText%";
  255. $sSQLOperator = 'LIKE';
  256. break;
  257. default:
  258. $sSQLOperator = $sOperator;
  259. $aParams[$sParamName] = $sSearchText;
  260. }
  261. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  262. return $oNewCondition;
  263. }
  264. }
  265. /**
  266. * Set of objects directly linked to an object, and being part of its definition
  267. *
  268. * @package iTopORM
  269. */
  270. class AttributeLinkedSet extends AttributeDefinition
  271. {
  272. static protected function ListExpectedParams()
  273. {
  274. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  275. }
  276. public function GetType() {return "Array of objects";}
  277. public function GetTypeDesc() {return "Any kind of objects [subclass] of the same class";}
  278. public function GetEditClass() {return "List";}
  279. public function IsWritable() {return true;}
  280. public function IsLinkSet() {return true;}
  281. public function IsIndirect() {return false;}
  282. public function GetValuesDef() {return $this->Get("allowed_values");}
  283. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  284. public function GetDefaultValue($aArgs = array())
  285. {
  286. // Note: so far, this feature is a prototype,
  287. // later, the argument 'this' should always be present in the arguments
  288. //
  289. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  290. {
  291. $aValues = $this->Get('default_value')->GetValues($aArgs);
  292. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  293. return $oSet;
  294. }
  295. else
  296. {
  297. return DBObjectSet::FromScratch($this->Get('linked_class'));
  298. }
  299. }
  300. public function GetLinkedClass() {return $this->Get('linked_class');}
  301. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  302. public function GetBasicFilterOperators() {return array();}
  303. public function GetBasicFilterLooseOperator() {return '';}
  304. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  305. public function GetAsHTML($sValue)
  306. {
  307. return "ERROR: LIST OF OBJECTS";
  308. }
  309. public function GetAsXML($sValue)
  310. {
  311. return "ERROR: LIST OF OBJECTS";
  312. }
  313. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  314. {
  315. return "ERROR: LIST OF OBJECTS";
  316. }
  317. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  318. }
  319. /**
  320. * Set of objects linked to an object (n-n), and being part of its definition
  321. *
  322. * @package iTopORM
  323. */
  324. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  325. {
  326. static protected function ListExpectedParams()
  327. {
  328. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  329. }
  330. public function IsIndirect() {return true;}
  331. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  332. public function GetEditClass() {return "LinkedSet";}
  333. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  334. }
  335. /**
  336. * Abstract class implementing default filters for a DB column
  337. *
  338. * @package iTopORM
  339. */
  340. class AttributeDBFieldVoid extends AttributeDefinition
  341. {
  342. static protected function ListExpectedParams()
  343. {
  344. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  345. }
  346. // To be overriden, used in GetSQLColumns
  347. protected function GetSQLCol() {return "VARCHAR(255)";}
  348. public function GetType() {return "Void";}
  349. public function GetTypeDesc() {return "Any kind of value, from the DB";}
  350. public function GetEditClass() {return "String";}
  351. public function GetValuesDef() {return $this->Get("allowed_values");}
  352. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  353. public function IsDirectField() {return true;}
  354. public function IsScalar() {return true;}
  355. public function IsWritable() {return true;}
  356. public function GetSQLExpr() {return $this->Get("sql");}
  357. public function GetDefaultValue() {return $this->MakeRealValue("");}
  358. public function IsNullAllowed() {return false;}
  359. //
  360. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  361. public function GetSQLExpressions()
  362. {
  363. $aColumns = array();
  364. // Note: to optimize things, the existence of the attribute is determine by the existence of one column with an empty suffix
  365. $aColumns[''] = $this->Get("sql");
  366. return $aColumns;
  367. }
  368. public function FromSQLToValue($aCols, $sPrefix = '')
  369. {
  370. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  371. return $value;
  372. }
  373. public function GetSQLValues($value)
  374. {
  375. $aValues = array();
  376. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  377. return $aValues;
  378. }
  379. public function GetSQLColumns()
  380. {
  381. $aColumns = array();
  382. $aColumns[$this->Get("sql")] = $this->GetSQLCol();
  383. return $aColumns;
  384. }
  385. public function GetFilterDefinitions()
  386. {
  387. return array($this->GetCode() => new FilterFromAttribute($this));
  388. }
  389. public function GetBasicFilterOperators()
  390. {
  391. return array("="=>"equals", "!="=>"differs from");
  392. }
  393. public function GetBasicFilterLooseOperator()
  394. {
  395. return "=";
  396. }
  397. public function GetBasicFilterSQLExpr($sOpCode, $value)
  398. {
  399. $sQValue = CMDBSource::Quote($value);
  400. switch ($sOpCode)
  401. {
  402. case '!=':
  403. return $this->GetSQLExpr()." != $sQValue";
  404. break;
  405. case '=':
  406. default:
  407. return $this->GetSQLExpr()." = $sQValue";
  408. }
  409. }
  410. }
  411. /**
  412. * Base class for all kind of DB attributes, with the exception of external keys
  413. *
  414. * @package iTopORM
  415. */
  416. class AttributeDBField extends AttributeDBFieldVoid
  417. {
  418. static protected function ListExpectedParams()
  419. {
  420. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  421. }
  422. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"));}
  423. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  424. }
  425. /**
  426. * Map an integer column to an attribute
  427. *
  428. * @package iTopORM
  429. */
  430. class AttributeInteger extends AttributeDBField
  431. {
  432. static protected function ListExpectedParams()
  433. {
  434. return parent::ListExpectedParams();
  435. //return array_merge(parent::ListExpectedParams(), array());
  436. }
  437. public function GetType() {return "Integer";}
  438. public function GetTypeDesc() {return "Numeric value (could be negative)";}
  439. public function GetEditClass() {return "String";}
  440. protected function GetSQLCol() {return "INT(11)";}
  441. public function GetValidationPattern()
  442. {
  443. return "^[0-9]+$";
  444. }
  445. public function GetBasicFilterOperators()
  446. {
  447. return array(
  448. "!="=>"differs from",
  449. "="=>"equals",
  450. ">"=>"greater (strict) than",
  451. ">="=>"greater than",
  452. "<"=>"less (strict) than",
  453. "<="=>"less than",
  454. "in"=>"in"
  455. );
  456. }
  457. public function GetBasicFilterLooseOperator()
  458. {
  459. // Unless we implement an "equals approximately..." or "same order of magnitude"
  460. return "=";
  461. }
  462. public function GetBasicFilterSQLExpr($sOpCode, $value)
  463. {
  464. $sQValue = CMDBSource::Quote($value);
  465. switch ($sOpCode)
  466. {
  467. case '!=':
  468. return $this->GetSQLExpr()." != $sQValue";
  469. break;
  470. case '>':
  471. return $this->GetSQLExpr()." > $sQValue";
  472. break;
  473. case '>=':
  474. return $this->GetSQLExpr()." >= $sQValue";
  475. break;
  476. case '<':
  477. return $this->GetSQLExpr()." < $sQValue";
  478. break;
  479. case '<=':
  480. return $this->GetSQLExpr()." <= $sQValue";
  481. break;
  482. case 'in':
  483. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  484. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  485. break;
  486. case '=':
  487. default:
  488. return $this->GetSQLExpr()." = \"$value\"";
  489. }
  490. }
  491. public function GetNullValue()
  492. {
  493. return null;
  494. }
  495. public function IsNull($proposedValue)
  496. {
  497. return is_null($proposedValue);
  498. }
  499. public function MakeRealValue($proposedValue)
  500. {
  501. if (is_null($proposedValue)) return null;
  502. if ($proposedValue == '') return null;
  503. return (int)$proposedValue;
  504. }
  505. public function ScalarToSQL($value)
  506. {
  507. assert(is_numeric($value) || is_null($value));
  508. return $value; // supposed to be an int
  509. }
  510. }
  511. /**
  512. * Map a decimal value column (suitable for financial computations) to an attribute
  513. * internally in PHP such numbers are represented as string. Should you want to perform
  514. * a calculation on them, it is recommended to use the BC Math functions in order to
  515. * retain the precision
  516. *
  517. * @package iTopORM
  518. */
  519. class AttributeDecimal extends AttributeDBField
  520. {
  521. static protected function ListExpectedParams()
  522. {
  523. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  524. }
  525. public function GetType() {return "Decimal";}
  526. public function GetTypeDesc() {return "Decimal value (could be negative)";}
  527. public function GetEditClass() {return "String";}
  528. protected function GetSQLCol() {return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")";}
  529. public function GetValidationPattern()
  530. {
  531. $iNbDigits = $this->Get('digits');
  532. $iPrecision = $this->Get('decimals');
  533. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  534. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  535. }
  536. public function GetBasicFilterOperators()
  537. {
  538. return array(
  539. "!="=>"differs from",
  540. "="=>"equals",
  541. ">"=>"greater (strict) than",
  542. ">="=>"greater than",
  543. "<"=>"less (strict) than",
  544. "<="=>"less than",
  545. "in"=>"in"
  546. );
  547. }
  548. public function GetBasicFilterLooseOperator()
  549. {
  550. // Unless we implement an "equals approximately..." or "same order of magnitude"
  551. return "=";
  552. }
  553. public function GetBasicFilterSQLExpr($sOpCode, $value)
  554. {
  555. $sQValue = CMDBSource::Quote($value);
  556. switch ($sOpCode)
  557. {
  558. case '!=':
  559. return $this->GetSQLExpr()." != $sQValue";
  560. break;
  561. case '>':
  562. return $this->GetSQLExpr()." > $sQValue";
  563. break;
  564. case '>=':
  565. return $this->GetSQLExpr()." >= $sQValue";
  566. break;
  567. case '<':
  568. return $this->GetSQLExpr()." < $sQValue";
  569. break;
  570. case '<=':
  571. return $this->GetSQLExpr()." <= $sQValue";
  572. break;
  573. case 'in':
  574. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  575. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  576. break;
  577. case '=':
  578. default:
  579. return $this->GetSQLExpr()." = \"$value\"";
  580. }
  581. }
  582. public function GetNullValue()
  583. {
  584. return null;
  585. }
  586. public function IsNull($proposedValue)
  587. {
  588. return is_null($proposedValue);
  589. }
  590. public function MakeRealValue($proposedValue)
  591. {
  592. if (is_null($proposedValue)) return null;
  593. if ($proposedValue == '') return null;
  594. return (string)$proposedValue;
  595. }
  596. public function ScalarToSQL($value)
  597. {
  598. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  599. return (string)$value; // treated as a string
  600. }
  601. }
  602. /**
  603. * Map a boolean column to an attribute
  604. *
  605. * @package iTopORM
  606. */
  607. class AttributeBoolean extends AttributeInteger
  608. {
  609. static protected function ListExpectedParams()
  610. {
  611. return parent::ListExpectedParams();
  612. //return array_merge(parent::ListExpectedParams(), array());
  613. }
  614. public function GetType() {return "Boolean";}
  615. public function GetTypeDesc() {return "Boolean";}
  616. public function GetEditClass() {return "Integer";}
  617. protected function GetSQLCol() {return "TINYINT(1)";}
  618. public function MakeRealValue($proposedValue)
  619. {
  620. if (is_null($proposedValue)) return null;
  621. if ($proposedValue == '') return null;
  622. if ((int)$proposedValue) return true;
  623. return false;
  624. }
  625. public function ScalarToSQL($value)
  626. {
  627. if ($value) return 1;
  628. return 0;
  629. }
  630. }
  631. /**
  632. * Map a varchar column (size < ?) to an attribute
  633. *
  634. * @package iTopORM
  635. */
  636. class AttributeString extends AttributeDBField
  637. {
  638. static protected function ListExpectedParams()
  639. {
  640. return parent::ListExpectedParams();
  641. //return array_merge(parent::ListExpectedParams(), array());
  642. }
  643. public function GetType() {return "String";}
  644. public function GetTypeDesc() {return "Alphanumeric string";}
  645. public function GetEditClass() {return "String";}
  646. protected function GetSQLCol() {return "VARCHAR(255)";}
  647. public function CheckFormat($value)
  648. {
  649. $sRegExp = $this->GetValidationPattern();
  650. if (empty($sRegExp))
  651. {
  652. return true;
  653. }
  654. else
  655. {
  656. $sRegExp = str_replace('/', '\\/', $sRegExp);
  657. return preg_match("/$sRegExp/", $value);
  658. }
  659. }
  660. public function GetMaxSize()
  661. {
  662. return 255;
  663. }
  664. public function GetBasicFilterOperators()
  665. {
  666. return array(
  667. "="=>"equals",
  668. "!="=>"differs from",
  669. "Like"=>"equals (no case)",
  670. "NotLike"=>"differs from (no case)",
  671. "Contains"=>"contains",
  672. "Begins with"=>"begins with",
  673. "Finishes with"=>"finishes with"
  674. );
  675. }
  676. public function GetBasicFilterLooseOperator()
  677. {
  678. return "Contains";
  679. }
  680. public function GetBasicFilterSQLExpr($sOpCode, $value)
  681. {
  682. $sQValue = CMDBSource::Quote($value);
  683. switch ($sOpCode)
  684. {
  685. case '=':
  686. case '!=':
  687. return $this->GetSQLExpr()." $sOpCode $sQValue";
  688. case 'Begins with':
  689. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  690. case 'Finishes with':
  691. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  692. case 'Contains':
  693. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  694. case 'NotLike':
  695. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  696. case 'Like':
  697. default:
  698. return $this->GetSQLExpr()." LIKE $sQValue";
  699. }
  700. }
  701. public function GetNullValue()
  702. {
  703. return '';
  704. }
  705. public function IsNull($proposedValue)
  706. {
  707. return ($proposedValue == '');
  708. }
  709. public function MakeRealValue($proposedValue)
  710. {
  711. if (is_null($proposedValue)) return '';
  712. return (string)$proposedValue;
  713. }
  714. public function ScalarToSQL($value)
  715. {
  716. if (!is_string($value) && !is_null($value))
  717. {
  718. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  719. }
  720. return $value;
  721. }
  722. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  723. {
  724. $sFrom = array("\r\n", $sTextQualifier);
  725. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  726. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  727. return '"'.$sEscaped.'"';
  728. }
  729. }
  730. /**
  731. * An attibute that matches an object class
  732. *
  733. * @package iTopORM
  734. */
  735. class AttributeClass extends AttributeString
  736. {
  737. static protected function ListExpectedParams()
  738. {
  739. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  740. }
  741. public function __construct($sCode, $aParams)
  742. {
  743. $this->m_sCode = $sCode;
  744. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  745. parent::__construct($sCode, $aParams);
  746. }
  747. public function GetDefaultValue()
  748. {
  749. $sDefault = parent::GetDefaultValue();
  750. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  751. {
  752. // For this kind of attribute specifying null as default value
  753. // is authorized even if null is not allowed
  754. // Pick the first one...
  755. $aClasses = $this->GetAllowedValues();
  756. $sDefault = key($aClasses);
  757. }
  758. return $sDefault;
  759. }
  760. public function GetAsHTML($sValue)
  761. {
  762. if (empty($sValue)) return '';
  763. return MetaModel::GetName($sValue);
  764. }
  765. public function RequiresIndex()
  766. {
  767. return true;
  768. }
  769. }
  770. /**
  771. * An attibute that matches one of the language codes availables in the dictionnary
  772. *
  773. * @package iTopORM
  774. */
  775. class AttributeApplicationLanguage extends AttributeString
  776. {
  777. static protected function ListExpectedParams()
  778. {
  779. return parent::ListExpectedParams();
  780. }
  781. public function __construct($sCode, $aParams)
  782. {
  783. $this->m_sCode = $sCode;
  784. $aAvailableLanguages = Dict::GetLanguages();
  785. $aLanguageCodes = array();
  786. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  787. {
  788. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  789. }
  790. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  791. parent::__construct($sCode, $aParams);
  792. }
  793. public function RequiresIndex()
  794. {
  795. return true;
  796. }
  797. }
  798. /**
  799. * The attribute dedicated to the finalclass automatic attribute
  800. *
  801. * @package iTopORM
  802. */
  803. class AttributeFinalClass extends AttributeString
  804. {
  805. public function __construct($sCode, $aParams)
  806. {
  807. $this->m_sCode = $sCode;
  808. $aParams["allowed_values"] = null;
  809. parent::__construct($sCode, $aParams);
  810. $this->m_sValue = $this->Get("default_value");
  811. }
  812. public function IsWritable()
  813. {
  814. return false;
  815. }
  816. public function RequiresIndex()
  817. {
  818. return true;
  819. }
  820. public function SetFixedValue($sValue)
  821. {
  822. $this->m_sValue = $sValue;
  823. }
  824. public function GetDefaultValue()
  825. {
  826. return $this->m_sValue;
  827. }
  828. public function GetAsHTML($sValue)
  829. {
  830. if (empty($sValue)) return '';
  831. return MetaModel::GetName($sValue);
  832. }
  833. }
  834. /**
  835. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  836. *
  837. * @package iTopORM
  838. */
  839. class AttributePassword extends AttributeString
  840. {
  841. static protected function ListExpectedParams()
  842. {
  843. return parent::ListExpectedParams();
  844. //return array_merge(parent::ListExpectedParams(), array());
  845. }
  846. public function GetEditClass() {return "Password";}
  847. protected function GetSQLCol() {return "VARCHAR(64)";}
  848. public function GetMaxSize()
  849. {
  850. return 64;
  851. }
  852. public function GetFilterDefinitions()
  853. {
  854. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  855. // not allowed to search on passwords!
  856. return array();
  857. }
  858. public function GetAsHTML($sValue)
  859. {
  860. if (strlen($sValue) == 0)
  861. {
  862. return '';
  863. }
  864. else
  865. {
  866. return '******';
  867. }
  868. }
  869. }
  870. /**
  871. * Map a text column (size < 255) to an attribute that is encrypted in the database
  872. * The encryption is based on a key set per iTop instance. Thus if you export your
  873. * database (in SQL) to someone else without providing the key at the same time
  874. * the encrypted fields will remain encrypted
  875. *
  876. * @package iTopORM
  877. */
  878. class AttributeEncryptedString extends AttributeString
  879. {
  880. static $sKey = null; // Encryption key used for all encrypted fields
  881. public function __construct($sCode, $aParams)
  882. {
  883. parent::__construct($sCode, $aParams);
  884. if (self::$sKey == null)
  885. {
  886. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  887. }
  888. }
  889. protected function GetSQLCol() {return "TINYBLOB";}
  890. public function GetMaxSize()
  891. {
  892. return 255;
  893. }
  894. public function GetFilterDefinitions()
  895. {
  896. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  897. // not allowed to search on encrypted fields !
  898. return array();
  899. }
  900. public function MakeRealValue($proposedValue)
  901. {
  902. if (is_null($proposedValue)) return null;
  903. return (string)$proposedValue;
  904. }
  905. /**
  906. * Decrypt the value when reading from the database
  907. */
  908. public function FromSQLToValue($aCols, $sPrefix = '')
  909. {
  910. $oSimpleCrypt = new SimpleCrypt();
  911. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  912. return $sValue;
  913. }
  914. /**
  915. * Encrypt the value before storing it in the database
  916. */
  917. public function GetSQLValues($value)
  918. {
  919. $oSimpleCrypt = new SimpleCrypt();
  920. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  921. $aValues = array();
  922. $aValues[$this->Get("sql")] = $encryptedValue;
  923. return $aValues;
  924. }
  925. }
  926. /**
  927. * Map a text column (size > ?) to an attribute
  928. *
  929. * @package iTopORM
  930. */
  931. class AttributeText extends AttributeString
  932. {
  933. public function GetType() {return "Text";}
  934. public function GetTypeDesc() {return "Multiline character string";}
  935. public function GetEditClass() {return "Text";}
  936. protected function GetSQLCol() {return "TEXT";}
  937. public function GetMaxSize()
  938. {
  939. // Is there a way to know the current limitation for mysql?
  940. // See mysql_field_len()
  941. return 65535;
  942. }
  943. public function GetAsHTML($sValue)
  944. {
  945. return str_replace("\n", "<br>\n", parent::GetAsHTML($sValue));
  946. }
  947. public function GetAsXML($value)
  948. {
  949. return Str::pure2xml($value);
  950. }
  951. }
  952. /**
  953. * Map a text column (size > ?), containing HTML code, to an attribute
  954. *
  955. * @package iTopORM
  956. */
  957. class AttributeHTML extends AttributeText
  958. {
  959. public function GetType() {return "HTML";}
  960. public function GetTypeDesc() {return "HTML string";}
  961. public function GetEditClass() {return "HTML";}
  962. public function GetAsHTML($sValue)
  963. {
  964. return $sValue;
  965. }
  966. }
  967. /**
  968. * Specialization of a string: email
  969. *
  970. * @package iTopORM
  971. */
  972. class AttributeEmailAddress extends AttributeString
  973. {
  974. public function GetTypeDesc() {return "Email address(es)";}
  975. public function GetValidationPattern()
  976. {
  977. return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  978. }
  979. public function GetAsHTML($sValue)
  980. {
  981. if (empty($sValue)) return '';
  982. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  983. }
  984. }
  985. /**
  986. * Specialization of a string: IP address
  987. *
  988. * @package iTopORM
  989. */
  990. class AttributeIPAddress extends AttributeString
  991. {
  992. public function GetTypeDesc() {return "IP address";}
  993. public function GetValidationPattern()
  994. {
  995. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  996. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  997. }
  998. }
  999. /**
  1000. * Specialization of a string: OQL expression
  1001. *
  1002. * @package iTopORM
  1003. */
  1004. class AttributeOQL extends AttributeText
  1005. {
  1006. public function GetTypeDesc() {return "OQL expression";}
  1007. }
  1008. /**
  1009. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1010. *
  1011. * @package iTopORM
  1012. */
  1013. class AttributeTemplateString extends AttributeString
  1014. {
  1015. public function GetTypeDesc() {return "Template string";}
  1016. }
  1017. /**
  1018. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1019. *
  1020. * @package iTopORM
  1021. */
  1022. class AttributeTemplateText extends AttributeText
  1023. {
  1024. public function GetTypeDesc() {return "Multiline template string";}
  1025. }
  1026. /**
  1027. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1028. *
  1029. * @package iTopORM
  1030. */
  1031. class AttributeTemplateHTML extends AttributeText
  1032. {
  1033. public function GetType() {return "HTML";}
  1034. public function GetTypeDesc() {return "HTML template";}
  1035. public function GetEditClass() {return "HTML";}
  1036. public function GetAsHTML($sValue)
  1037. {
  1038. return $sValue;
  1039. }
  1040. }
  1041. /**
  1042. * Specialization of a text: wiki formatting
  1043. *
  1044. * @package iTopORM
  1045. */
  1046. class AttributeWikiText extends AttributeText
  1047. {
  1048. public function GetTypeDesc() {return "Multiline string with special formatting such as links to objects";}
  1049. public function GetAsHTML($value)
  1050. {
  1051. // [SELECT xxxx.... [label]] => hyperlink to a result list
  1052. // {SELECT xxxx.... [label]} => result list displayed inline
  1053. // [myclass/nnn [label]] => hyperlink to an object
  1054. // {myclass/nnn/attcode} => attribute displayed inline
  1055. // etc.
  1056. return parent::GetAsHTML($value);
  1057. }
  1058. }
  1059. /**
  1060. * Map a enum column to an attribute
  1061. *
  1062. * @package iTopORM
  1063. */
  1064. class AttributeEnum extends AttributeString
  1065. {
  1066. static protected function ListExpectedParams()
  1067. {
  1068. return parent::ListExpectedParams();
  1069. //return array_merge(parent::ListExpectedParams(), array());
  1070. }
  1071. public function GetType() {return "Enum";}
  1072. public function GetTypeDesc() {return "List of predefined alphanumeric strings";}
  1073. public function GetEditClass() {return "String";}
  1074. protected function GetSQLCol()
  1075. {
  1076. $oValDef = $this->GetValuesDef();
  1077. if ($oValDef)
  1078. {
  1079. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  1080. }
  1081. else
  1082. {
  1083. $aValues = array();
  1084. }
  1085. if (count($aValues) > 0)
  1086. {
  1087. // The syntax used here do matters
  1088. // In particular, I had to remove unnecessary spaces to
  1089. // make sure that this string will match the field type returned by the DB
  1090. // (used to perform a comparison between the current DB format and the data model)
  1091. return "ENUM(".implode(",", $aValues).")";
  1092. }
  1093. else
  1094. {
  1095. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  1096. }
  1097. }
  1098. public function ScalarToSQL($value)
  1099. {
  1100. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  1101. // but that wasn't working for enums, because '' is NOT one of the allowed values
  1102. // that's why a null value must be forced to a real null
  1103. $value = parent::ScalarToSQL($value);
  1104. if ($this->IsNull($value))
  1105. {
  1106. return null;
  1107. }
  1108. else
  1109. {
  1110. return $value;
  1111. }
  1112. }
  1113. public function RequiresIndex()
  1114. {
  1115. return false;
  1116. }
  1117. public function GetBasicFilterOperators()
  1118. {
  1119. return parent::GetBasicFilterOperators();
  1120. }
  1121. public function GetBasicFilterLooseOperator()
  1122. {
  1123. return parent::GetBasicFilterLooseOperator();
  1124. }
  1125. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1126. {
  1127. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1128. }
  1129. public function GetAsHTML($sValue)
  1130. {
  1131. if (is_null($sValue))
  1132. {
  1133. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1134. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  1135. }
  1136. else
  1137. {
  1138. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1139. }
  1140. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', $sValue);
  1141. // later, we could imagine a detailed description in the title
  1142. return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  1143. }
  1144. public function GetEditValue($sValue)
  1145. {
  1146. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1147. return $sLabel;
  1148. }
  1149. public function GetAllowedValues($aArgs = array(), $sBeginsWith = '')
  1150. {
  1151. $aRawValues = parent::GetAllowedValues($aArgs, $sBeginsWith);
  1152. if (is_null($aRawValues)) return null;
  1153. $aLocalizedValues = array();
  1154. foreach ($aRawValues as $sKey => $sValue)
  1155. {
  1156. $aLocalizedValues[$sKey] = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sKey, $sKey);
  1157. }
  1158. return $aLocalizedValues;
  1159. }
  1160. /**
  1161. * Processes the input value to align it with the values supported
  1162. * by this type of attribute. In this case: turns empty strings into nulls
  1163. * @param mixed $proposedValue The value to be set for the attribute
  1164. * @return mixed The actual value that will be set
  1165. */
  1166. public function MakeRealValue($proposedValue)
  1167. {
  1168. if ($proposedValue == '') return null;
  1169. return parent::MakeRealValue($proposedValue);
  1170. }
  1171. }
  1172. /**
  1173. * Map a date+time column to an attribute
  1174. *
  1175. * @package iTopORM
  1176. */
  1177. class AttributeDateTime extends AttributeDBField
  1178. {
  1179. //const MYDATETIMEZONE = "UTC";
  1180. const MYDATETIMEZONE = "Europe/Paris";
  1181. static protected $const_TIMEZONE = null; // set once for all upon object construct
  1182. static public function InitStatics()
  1183. {
  1184. // Init static constant once for all (remove when PHP allows real static const)
  1185. self::$const_TIMEZONE = new DateTimeZone(self::MYDATETIMEZONE);
  1186. // #@# Init default timezone -> do not get a notice... to be improved !!!
  1187. // duplicated in the email test page (the mail function does trigger a notice as well)
  1188. date_default_timezone_set(self::MYDATETIMEZONE);
  1189. }
  1190. static protected function GetDateFormat()
  1191. {
  1192. return "Y-m-d H:i:s";
  1193. }
  1194. static protected function ListExpectedParams()
  1195. {
  1196. return parent::ListExpectedParams();
  1197. //return array_merge(parent::ListExpectedParams(), array());
  1198. }
  1199. public function GetType() {return "Date";}
  1200. public function GetTypeDesc() {return "Date and time";}
  1201. public function GetEditClass() {return "DateTime";}
  1202. protected function GetSQLCol() {return "TIMESTAMP";}
  1203. public static function GetAsUnixSeconds($value)
  1204. {
  1205. $oDeadlineDateTime = new DateTime($value, self::$const_TIMEZONE);
  1206. $iUnixSeconds = $oDeadlineDateTime->format('U');
  1207. return $iUnixSeconds;
  1208. }
  1209. // #@# THIS HAS TO REVISED
  1210. // Having null not allowed was interpreted by mySQL
  1211. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  1212. // Then, on each update of the record, the field was modified.
  1213. // We will have to specify the default value if we want to restore this option
  1214. // In fact, we could also have more verbs dedicated to the DB:
  1215. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  1216. public function IsNullAllowed() {return true;}
  1217. public function GetDefaultValue()
  1218. {
  1219. $default = parent::GetDefaultValue();
  1220. if (!parent::IsNullAllowed())
  1221. {
  1222. if (empty($default))
  1223. {
  1224. $default = date(self::GetDateFormat());
  1225. }
  1226. }
  1227. return $default;
  1228. }
  1229. // END OF THE WORKAROUND
  1230. ///////////////////////////////////////////////////////////////
  1231. public function GetValidationPattern()
  1232. {
  1233. 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$";
  1234. }
  1235. public function GetBasicFilterOperators()
  1236. {
  1237. return array(
  1238. "="=>"equals",
  1239. "!="=>"differs from",
  1240. "<"=>"before",
  1241. "<="=>"before",
  1242. ">"=>"after (strictly)",
  1243. ">="=>"after",
  1244. "SameDay"=>"same day (strip time)",
  1245. "SameMonth"=>"same year/month",
  1246. "SameYear"=>"same year",
  1247. "Today"=>"today",
  1248. ">|"=>"after today + N days",
  1249. "<|"=>"before today + N days",
  1250. "=|"=>"equals today + N days",
  1251. );
  1252. }
  1253. public function GetBasicFilterLooseOperator()
  1254. {
  1255. // Unless we implement a "same xxx, depending on given precision" !
  1256. return "=";
  1257. }
  1258. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1259. {
  1260. $sQValue = CMDBSource::Quote($value);
  1261. switch ($sOpCode)
  1262. {
  1263. case '=':
  1264. case '!=':
  1265. case '<':
  1266. case '<=':
  1267. case '>':
  1268. case '>=':
  1269. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1270. case 'SameDay':
  1271. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  1272. case 'SameMonth':
  1273. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  1274. case 'SameYear':
  1275. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  1276. case 'Today':
  1277. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  1278. case '>|':
  1279. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1280. case '<|':
  1281. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1282. case '=|':
  1283. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1284. default:
  1285. return $this->GetSQLExpr()." = $sQValue";
  1286. }
  1287. }
  1288. public function MakeRealValue($proposedValue)
  1289. {
  1290. if (is_null($proposedValue))
  1291. {
  1292. return null;
  1293. }
  1294. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  1295. {
  1296. return null;
  1297. }
  1298. if (!is_numeric($proposedValue))
  1299. {
  1300. return $proposedValue;
  1301. }
  1302. return date(self::GetDateFormat(), $proposedValue);
  1303. }
  1304. public function ScalarToSQL($value)
  1305. {
  1306. if (is_null($value))
  1307. {
  1308. return null;
  1309. }
  1310. elseif (empty($value))
  1311. {
  1312. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  1313. return '0000-00-00 00:00:00';
  1314. }
  1315. return $value;
  1316. }
  1317. public function GetAsHTML($value)
  1318. {
  1319. return Str::pure2html($value);
  1320. }
  1321. public function GetAsXML($value)
  1322. {
  1323. return Str::pure2xml($value);
  1324. }
  1325. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1326. {
  1327. $sFrom = array("\r\n", $sTextQualifier);
  1328. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1329. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1330. return '"'.$sEscaped.'"';
  1331. }
  1332. /**
  1333. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  1334. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  1335. * does nothing special, and just calls the default (loose) operator
  1336. * @param string $sSearchText The search string to analyze for smart patterns
  1337. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  1338. * @param Hash $aParams Values of the query parameters
  1339. * @return Expression The search condition to be added (AND) to the current search
  1340. */
  1341. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  1342. {
  1343. // Possible smart patterns
  1344. $aPatterns = array(
  1345. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  1346. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  1347. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  1348. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  1349. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  1350. );
  1351. $sPatternFound = '';
  1352. $aMatches = array();
  1353. foreach($aPatterns as $sPatName => $sPattern)
  1354. {
  1355. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  1356. {
  1357. $sPatternFound = $sPatName;
  1358. break;
  1359. }
  1360. }
  1361. switch($sPatternFound)
  1362. {
  1363. case 'between':
  1364. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  1365. $oRightExpr = new VariableExpression($sParamName1);
  1366. $aParams[$sParamName1] = $aMatches[1];
  1367. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  1368. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  1369. $oRightExpr = new VariableExpression($sParamName2);
  1370. $sOperator = $this->GetBasicFilterLooseOperator();
  1371. $aParams[$sParamName2] = $aMatches[2];
  1372. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  1373. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  1374. break;
  1375. case 'greater than':
  1376. case 'greater than or equal':
  1377. case 'less than':
  1378. case 'less than or equal':
  1379. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  1380. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  1381. $oRightExpr = new VariableExpression($sParamName);
  1382. $aParams[$sParamName] = $aMatches[1];
  1383. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  1384. break;
  1385. default:
  1386. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  1387. }
  1388. return $oNewCondition;
  1389. }
  1390. }
  1391. /**
  1392. * Map a date+time column to an attribute
  1393. *
  1394. * @package iTopORM
  1395. */
  1396. class AttributeDate extends AttributeDateTime
  1397. {
  1398. const MYDATEFORMAT = "Y-m-d";
  1399. static protected function GetDateFormat()
  1400. {
  1401. return "Y-m-d";
  1402. }
  1403. static public function InitStatics()
  1404. {
  1405. // Nothing to do...
  1406. }
  1407. static protected function ListExpectedParams()
  1408. {
  1409. return parent::ListExpectedParams();
  1410. //return array_merge(parent::ListExpectedParams(), array());
  1411. }
  1412. public function GetType() {return "Date";}
  1413. public function GetTypeDesc() {return "Date";}
  1414. public function GetEditClass() {return "Date";}
  1415. protected function GetSQLCol() {return "DATE";}
  1416. public function GetValidationPattern()
  1417. {
  1418. 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)))$";
  1419. }
  1420. }
  1421. // Init static constant once for all (remove when PHP allows real static const)
  1422. AttributeDate::InitStatics();
  1423. /**
  1424. * A dead line stored as a date & time
  1425. * The only difference with the DateTime attribute is the display:
  1426. * relative to the current time
  1427. */
  1428. class AttributeDeadline extends AttributeDateTime
  1429. {
  1430. public function GetAsHTML($value)
  1431. {
  1432. $sResult = '';
  1433. if ($value !== null)
  1434. {
  1435. $value = AttributeDateTime::GetAsUnixSeconds($value);
  1436. $difference = $value - time();
  1437. if ($difference >= 0)
  1438. {
  1439. $sResult = self::FormatDuration($difference);
  1440. }
  1441. else
  1442. {
  1443. $sResult = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  1444. }
  1445. }
  1446. return $sResult;
  1447. }
  1448. static function FormatDuration($duration)
  1449. {
  1450. $days = floor($duration / 86400);
  1451. $hours = floor(($duration - (86400*$days)) / 3600);
  1452. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  1453. $sResult = '';
  1454. if ($duration < 60)
  1455. {
  1456. // Less than 1 min
  1457. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  1458. }
  1459. else if ($duration < 3600)
  1460. {
  1461. // less than 1 hour, display it in minutes
  1462. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  1463. }
  1464. else if ($duration < 86400)
  1465. {
  1466. // Less that 1 day, display it in hours/minutes
  1467. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  1468. }
  1469. else
  1470. {
  1471. // Less that 1 day, display it in hours/minutes
  1472. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  1473. }
  1474. return $sResult;
  1475. }
  1476. }
  1477. // Init static constant once for all (remove when PHP allows real static const)
  1478. AttributeDateTime::InitStatics();
  1479. /**
  1480. * Map a foreign key to an attribute
  1481. * AttributeExternalKey and AttributeExternalField may be an external key
  1482. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  1483. * where an AttributeExternalField corresponds to a column into another table (class)
  1484. *
  1485. * @package iTopORM
  1486. */
  1487. class AttributeExternalKey extends AttributeDBFieldVoid
  1488. {
  1489. static protected function ListExpectedParams()
  1490. {
  1491. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  1492. }
  1493. public function GetType() {return "Extkey";}
  1494. public function GetTypeDesc() {return "Link to another object";}
  1495. public function GetEditClass() {return "ExtKey";}
  1496. protected function GetSQLCol() {return "INT(11)";}
  1497. public function RequiresIndex()
  1498. {
  1499. return true;
  1500. }
  1501. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  1502. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  1503. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  1504. public function GetKeyAttCode() {return $this->GetCode();}
  1505. public function GetDefaultValue() {return 0;}
  1506. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  1507. public function GetBasicFilterOperators()
  1508. {
  1509. return parent::GetBasicFilterOperators();
  1510. }
  1511. public function GetBasicFilterLooseOperator()
  1512. {
  1513. return parent::GetBasicFilterLooseOperator();
  1514. }
  1515. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1516. {
  1517. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1518. }
  1519. // overloaded here so that an ext key always have the answer to
  1520. // "what are your possible values?"
  1521. public function GetValuesDef()
  1522. {
  1523. $oValSetDef = $this->Get("allowed_values");
  1524. if (!$oValSetDef)
  1525. {
  1526. // Let's propose every existing value
  1527. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1528. }
  1529. return $oValSetDef;
  1530. }
  1531. public function GetAllowedValues($aArgs = array(), $sBeginsWith = '')
  1532. {
  1533. try
  1534. {
  1535. return parent::GetAllowedValues($aArgs, $sBeginsWith);
  1536. }
  1537. catch (MissingQueryArgument $e)
  1538. {
  1539. // Some required arguments could not be found, enlarge to any existing value
  1540. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1541. return $oValSetDef->GetValues($aArgs, $sBeginsWith);
  1542. }
  1543. }
  1544. public function GetDeletionPropagationOption()
  1545. {
  1546. return $this->Get("on_target_delete");
  1547. }
  1548. public function GetNullValue()
  1549. {
  1550. return 0;
  1551. }
  1552. public function IsNull($proposedValue)
  1553. {
  1554. return ($proposedValue == 0);
  1555. }
  1556. public function MakeRealValue($proposedValue)
  1557. {
  1558. if (is_null($proposedValue)) return 0;
  1559. if ($proposedValue === '') return 0;
  1560. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  1561. return (int)$proposedValue;
  1562. }
  1563. }
  1564. /**
  1565. * An attribute which corresponds to an external key (direct or indirect)
  1566. *
  1567. * @package iTopORM
  1568. */
  1569. class AttributeExternalField extends AttributeDefinition
  1570. {
  1571. static protected function ListExpectedParams()
  1572. {
  1573. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  1574. }
  1575. public function GetType() {return "ExtkeyField";}
  1576. public function GetTypeDesc() {return "Field of an object pointed to by the current object";}
  1577. public function GetEditClass() {return "ExtField";}
  1578. protected function GetSQLCol()
  1579. {
  1580. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  1581. $oExtAttDef = $this->GetExtAttDef();
  1582. return $oExtAttDef->GetSQLCol();
  1583. }
  1584. public function GetLabel()
  1585. {
  1586. $oRemoteAtt = $this->GetExtAttDef();
  1587. $sDefault = $oRemoteAtt->GetLabel();
  1588. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $sDefault);
  1589. }
  1590. public function GetDescription()
  1591. {
  1592. $oRemoteAtt = $this->GetExtAttDef();
  1593. $sDefault = $oRemoteAtt->GetDescription();
  1594. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', $sDefault);
  1595. }
  1596. public function GetHelpOnEdition()
  1597. {
  1598. $oRemoteAtt = $this->GetExtAttDef();
  1599. $sDefault = $oRemoteAtt->GetHelpOnEdition();
  1600. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', $sDefault);
  1601. }
  1602. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  1603. {
  1604. switch($iType)
  1605. {
  1606. case EXTKEY_ABSOLUTE:
  1607. // see further
  1608. $oRemoteAtt = $this->GetExtAttDef();
  1609. return $oRemoteAtt->IsExternalKey($iType);
  1610. case EXTKEY_RELATIVE:
  1611. return false;
  1612. default:
  1613. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1614. }
  1615. }
  1616. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  1617. {
  1618. return $this->GetKeyAttDef($iType)->GetTargetClass();
  1619. }
  1620. public function IsExternalField() {return true;}
  1621. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  1622. public function GetExtAttCode() {return $this->Get("target_attcode");}
  1623. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  1624. {
  1625. switch($iType)
  1626. {
  1627. case EXTKEY_ABSOLUTE:
  1628. // see further
  1629. $oRemoteAtt = $this->GetExtAttDef();
  1630. if ($oRemoteAtt->IsExternalField())
  1631. {
  1632. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1633. }
  1634. else if ($oRemoteAtt->IsExternalKey())
  1635. {
  1636. return $oRemoteAtt;
  1637. }
  1638. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  1639. case EXTKEY_RELATIVE:
  1640. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  1641. default:
  1642. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1643. }
  1644. }
  1645. public function GetExtAttDef()
  1646. {
  1647. $oKeyAttDef = $this->GetKeyAttDef();
  1648. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->Get("targetclass"), $this->Get("target_attcode"));
  1649. 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"));
  1650. return $oExtAttDef;
  1651. }
  1652. public function GetSQLExpr()
  1653. {
  1654. $oExtAttDef = $this->GetExtAttDef();
  1655. return $oExtAttDef->GetSQLExpr();
  1656. }
  1657. public function GetDefaultValue()
  1658. {
  1659. $oExtAttDef = $this->GetExtAttDef();
  1660. return $oExtAttDef->GetDefaultValue();
  1661. }
  1662. public function IsNullAllowed()
  1663. {
  1664. $oExtAttDef = $this->GetExtAttDef();
  1665. return $oExtAttDef->IsNullAllowed();
  1666. }
  1667. public function IsScalar()
  1668. {
  1669. $oExtAttDef = $this->GetExtAttDef();
  1670. return $oExtAttDef->IsScalar();
  1671. }
  1672. public function GetFilterDefinitions()
  1673. {
  1674. return array($this->GetCode() => new FilterFromAttribute($this));
  1675. }
  1676. public function GetBasicFilterOperators()
  1677. {
  1678. $oExtAttDef = $this->GetExtAttDef();
  1679. return $oExtAttDef->GetBasicFilterOperators();
  1680. }
  1681. public function GetBasicFilterLooseOperator()
  1682. {
  1683. $oExtAttDef = $this->GetExtAttDef();
  1684. return $oExtAttDef->GetBasicFilterLooseOperator();
  1685. }
  1686. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1687. {
  1688. $oExtAttDef = $this->GetExtAttDef();
  1689. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  1690. }
  1691. public function GetNullValue()
  1692. {
  1693. $oExtAttDef = $this->GetExtAttDef();
  1694. return $oExtAttDef->GetNullValue();
  1695. }
  1696. public function IsNull($proposedValue)
  1697. {
  1698. $oExtAttDef = $this->GetExtAttDef();
  1699. return $oExtAttDef->IsNull($proposedValue);
  1700. }
  1701. public function MakeRealValue($proposedValue)
  1702. {
  1703. $oExtAttDef = $this->GetExtAttDef();
  1704. return $oExtAttDef->MakeRealValue($proposedValue);
  1705. }
  1706. public function ScalarToSQL($value)
  1707. {
  1708. // This one could be used in case of filtering only
  1709. $oExtAttDef = $this->GetExtAttDef();
  1710. return $oExtAttDef->ScalarToSQL($value);
  1711. }
  1712. // Do not overload GetSQLExpression here because this is handled in the joins
  1713. //public function GetSQLExpressions() {return array();}
  1714. // Here, we get the data...
  1715. public function FromSQLToValue($aCols, $sPrefix = '')
  1716. {
  1717. $oExtAttDef = $this->GetExtAttDef();
  1718. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  1719. }
  1720. public function GetAsHTML($value)
  1721. {
  1722. $oExtAttDef = $this->GetExtAttDef();
  1723. return $oExtAttDef->GetAsHTML($value);
  1724. }
  1725. public function GetAsXML($value)
  1726. {
  1727. $oExtAttDef = $this->GetExtAttDef();
  1728. return $oExtAttDef->GetAsXML($value);
  1729. }
  1730. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"')
  1731. {
  1732. $oExtAttDef = $this->GetExtAttDef();
  1733. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  1734. }
  1735. }
  1736. /**
  1737. * Map a varchar column to an URL (formats the ouput in HMTL)
  1738. *
  1739. * @package iTopORM
  1740. */
  1741. class AttributeURL extends AttributeString
  1742. {
  1743. static protected function ListExpectedParams()
  1744. {
  1745. //return parent::ListExpectedParams();
  1746. return array_merge(parent::ListExpectedParams(), array("target"));
  1747. }
  1748. public function GetType() {return "Url";}
  1749. public function GetTypeDesc() {return "Absolute or relative URL as a text string";}
  1750. public function GetEditClass() {return "String";}
  1751. public function GetAsHTML($sValue)
  1752. {
  1753. $sTarget = $this->Get("target");
  1754. if (empty($sTarget)) $sTarget = "_blank";
  1755. $sLabel = Str::pure2html($sValue);
  1756. if (strlen($sLabel) > 40)
  1757. {
  1758. // Truncate the length to about 40 characters, by removing the middle
  1759. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  1760. }
  1761. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  1762. }
  1763. public function GetValidationPattern()
  1764. {
  1765. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  1766. }
  1767. }
  1768. /**
  1769. * A blob is an ormDocument, it is stored as several columns in the database
  1770. *
  1771. * @package iTopORM
  1772. */
  1773. class AttributeBlob extends AttributeDefinition
  1774. {
  1775. static protected function ListExpectedParams()
  1776. {
  1777. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  1778. }
  1779. public function GetType() {return "Blob";}
  1780. public function GetTypeDesc() {return "Document";}
  1781. public function GetEditClass() {return "Document";}
  1782. public function IsDirectField() {return true;}
  1783. public function IsScalar() {return true;}
  1784. public function IsWritable() {return true;}
  1785. public function GetDefaultValue() {return "";}
  1786. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  1787. // Facilitate things: allow the user to Set the value from a string
  1788. public function MakeRealValue($proposedValue)
  1789. {
  1790. if (!is_object($proposedValue))
  1791. {
  1792. return new ormDocument($proposedValue, 'text/plain');
  1793. }
  1794. return $proposedValue;
  1795. }
  1796. public function GetSQLExpressions()
  1797. {
  1798. $aColumns = array();
  1799. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1800. $aColumns[''] = $this->GetCode().'_mimetype';
  1801. $aColumns['_data'] = $this->GetCode().'_data';
  1802. $aColumns['_filename'] = $this->GetCode().'_filename';
  1803. return $aColumns;
  1804. }
  1805. public function FromSQLToValue($aCols, $sPrefix = '')
  1806. {
  1807. if (!isset($aCols[$sPrefix]))
  1808. {
  1809. $sAvailable = implode(', ', array_keys($aCols));
  1810. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1811. }
  1812. $sMimeType = $aCols[$sPrefix];
  1813. if (!isset($aCols[$sPrefix.'_data']))
  1814. {
  1815. $sAvailable = implode(', ', array_keys($aCols));
  1816. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  1817. }
  1818. $data = $aCols[$sPrefix.'_data'];
  1819. if (!isset($aCols[$sPrefix.'_filename']))
  1820. {
  1821. $sAvailable = implode(', ', array_keys($aCols));
  1822. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  1823. }
  1824. $sFileName = $aCols[$sPrefix.'_filename'];
  1825. $value = new ormDocument($data, $sMimeType, $sFileName);
  1826. return $value;
  1827. }
  1828. public function GetSQLValues($value)
  1829. {
  1830. // #@# Optimization: do not load blobs anytime
  1831. // As per mySQL doc, selecting blob columns will prevent mySQL from
  1832. // using memory in case a temporary table has to be created
  1833. // (temporary tables created on disk)
  1834. // We will have to remove the blobs from the list of attributes when doing the select
  1835. // then the use of Get() should finalize the load
  1836. if ($value instanceOf ormDocument)
  1837. {
  1838. $aValues = array();
  1839. $aValues[$this->GetCode().'_data'] = $value->GetData();
  1840. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  1841. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  1842. }
  1843. else
  1844. {
  1845. $aValues = array();
  1846. $aValues[$this->GetCode().'_data'] = '';
  1847. $aValues[$this->GetCode().'_mimetype'] = '';
  1848. $aValues[$this->GetCode().'_filename'] = '';
  1849. }
  1850. return $aValues;
  1851. }
  1852. public function GetSQLColumns()
  1853. {
  1854. $aColumns = array();
  1855. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  1856. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  1857. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  1858. return $aColumns;
  1859. }
  1860. public function GetFilterDefinitions()
  1861. {
  1862. return array();
  1863. // still not working... see later...
  1864. return array(
  1865. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  1866. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  1867. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  1868. );
  1869. }
  1870. public function GetBasicFilterOperators()
  1871. {
  1872. return array();
  1873. }
  1874. public function GetBasicFilterLooseOperator()
  1875. {
  1876. return '=';
  1877. }
  1878. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1879. {
  1880. return 'true';
  1881. }
  1882. public function GetAsHTML($value)
  1883. {
  1884. if (is_object($value))
  1885. {
  1886. return $value->GetAsHTML();
  1887. }
  1888. }
  1889. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1890. {
  1891. return ''; // Not exportable in CSV !
  1892. }
  1893. public function GetAsXML($value)
  1894. {
  1895. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  1896. }
  1897. }
  1898. /**
  1899. * One way encrypted (hashed) password
  1900. */
  1901. class AttributeOneWayPassword extends AttributeDefinition
  1902. {
  1903. static protected function ListExpectedParams()
  1904. {
  1905. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  1906. }
  1907. public function GetType() {return "One Way Password";}
  1908. public function GetTypeDesc() {return "One Way Password";}
  1909. public function GetEditClass() {return "One Way Password";}
  1910. public function IsDirectField() {return true;}
  1911. public function IsScalar() {return true;}
  1912. public function IsWritable() {return true;}
  1913. public function GetDefaultValue() {return "";}
  1914. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  1915. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  1916. public function MakeRealValue($proposedValue)
  1917. {
  1918. $oPassword = $proposedValue;
  1919. if (!is_object($oPassword))
  1920. {
  1921. $oPassword = new ormPassword('', '');
  1922. $oPassword->SetPassword($proposedValue);
  1923. }
  1924. return $oPassword;
  1925. }
  1926. public function GetSQLExpressions()
  1927. {
  1928. $aColumns = array();
  1929. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1930. $aColumns[''] = $this->GetCode().'_hash';
  1931. $aColumns['_salt'] = $this->GetCode().'_salt';
  1932. return $aColumns;
  1933. }
  1934. public function FromSQLToValue($aCols, $sPrefix = '')
  1935. {
  1936. if (!isset($aCols[$sPrefix]))
  1937. {
  1938. $sAvailable = implode(', ', array_keys($aCols));
  1939. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1940. }
  1941. $hashed = $aCols[$sPrefix];
  1942. if (!isset($aCols[$sPrefix.'_salt']))
  1943. {
  1944. $sAvailable = implode(', ', array_keys($aCols));
  1945. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  1946. }
  1947. $sSalt = $aCols[$sPrefix.'_salt'];
  1948. $value = new ormPassword($hashed, $sSalt);
  1949. return $value;
  1950. }
  1951. public function GetSQLValues($value)
  1952. {
  1953. // #@# Optimization: do not load blobs anytime
  1954. // As per mySQL doc, selecting blob columns will prevent mySQL from
  1955. // using memory in case a temporary table has to be created
  1956. // (temporary tables created on disk)
  1957. // We will have to remove the blobs from the list of attributes when doing the select
  1958. // then the use of Get() should finalize the load
  1959. if ($value instanceOf ormPassword)
  1960. {
  1961. $aValues = array();
  1962. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  1963. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  1964. }
  1965. else
  1966. {
  1967. $aValues = array();
  1968. $aValues[$this->GetCode().'_hash'] = '';
  1969. $aValues[$this->GetCode().'_salt'] = '';
  1970. }
  1971. return $aValues;
  1972. }
  1973. public function GetSQLColumns()
  1974. {
  1975. $aColumns = array();
  1976. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  1977. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  1978. return $aColumns;
  1979. }
  1980. public function GetFilterDefinitions()
  1981. {
  1982. return array();
  1983. // still not working... see later...
  1984. }
  1985. public function GetBasicFilterOperators()
  1986. {
  1987. return array();
  1988. }
  1989. public function GetBasicFilterLooseOperator()
  1990. {
  1991. return '=';
  1992. }
  1993. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1994. {
  1995. return 'true';
  1996. }
  1997. public function GetAsHTML($value)
  1998. {
  1999. if (is_object($value))
  2000. {
  2001. return $value->GetAsHTML();
  2002. }
  2003. }
  2004. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  2005. {
  2006. return ''; // Not exportable in CSV
  2007. }
  2008. public function GetAsXML($value)
  2009. {
  2010. return ''; // Not exportable in XML
  2011. }
  2012. }
  2013. // Indexed array having two dimensions
  2014. class AttributeTable extends AttributeText
  2015. {
  2016. public function GetType() {return "Table";}
  2017. public function GetTypeDesc() {return "Array with 2 dimensions";}
  2018. public function GetEditClass() {return "Text";}
  2019. protected function GetSQLCol() {return "TEXT";}
  2020. public function GetMaxSize()
  2021. {
  2022. return null;
  2023. }
  2024. // Facilitate things: allow the user to Set the value from a string
  2025. public function MakeRealValue($proposedValue)
  2026. {
  2027. if (!is_array($proposedValue))
  2028. {
  2029. return array(0 => array(0 => $proposedValue));
  2030. }
  2031. return $proposedValue;
  2032. }
  2033. public function FromSQLToValue($aCols, $sPrefix = '')
  2034. {
  2035. try
  2036. {
  2037. $value = @unserialize($aCols[$sPrefix.'']);
  2038. if ($value === false)
  2039. {
  2040. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  2041. }
  2042. }
  2043. catch(Exception $e)
  2044. {
  2045. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  2046. }
  2047. return $value;
  2048. }
  2049. public function GetSQLValues($value)
  2050. {
  2051. $aValues = array();
  2052. $aValues[$this->Get("sql")] = serialize($value);
  2053. return $aValues;
  2054. }
  2055. public function GetAsHTML($value)
  2056. {
  2057. if (!is_array($value))
  2058. {
  2059. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2060. }
  2061. if (count($value) == 0)
  2062. {
  2063. return "";
  2064. }
  2065. $sRes = "<TABLE class=\"listResults\">";
  2066. $sRes .= "<TBODY>";
  2067. foreach($value as $iRow => $aRawData)
  2068. {
  2069. $sRes .= "<TR>";
  2070. foreach ($aRawData as $iCol => $cell)
  2071. {
  2072. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  2073. $sRes .= "<TD>$sCell</TD>";
  2074. }
  2075. $sRes .= "</TR>";
  2076. }
  2077. $sRes .= "</TBODY>";
  2078. $sRes .= "</TABLE>";
  2079. return $sRes;
  2080. }
  2081. }
  2082. // The PHP value is a hash array, it is stored as a TEXT column
  2083. class AttributePropertySet extends AttributeTable
  2084. {
  2085. public function GetType() {return "PropertySet";}
  2086. public function GetTypeDesc() {return "List of properties (name and value)";}
  2087. public function GetEditClass() {return "Text";}
  2088. protected function GetSQLCol() {return "TEXT";}
  2089. // Facilitate things: allow the user to Set the value from a string
  2090. public function MakeRealValue($proposedValue)
  2091. {
  2092. if (!is_array($proposedValue))
  2093. {
  2094. return array('?' => (string)$proposedValue);
  2095. }
  2096. return $proposedValue;
  2097. }
  2098. public function GetAsHTML($value)
  2099. {
  2100. if (!is_array($value))
  2101. {
  2102. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2103. }
  2104. if (count($value) == 0)
  2105. {
  2106. return "";
  2107. }
  2108. $sRes = "<TABLE class=\"listResults\">";
  2109. $sRes .= "<TBODY>";
  2110. foreach($value as $sProperty => $sValue)
  2111. {
  2112. $sRes .= "<TR>";
  2113. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  2114. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  2115. $sRes .= "</TR>";
  2116. }
  2117. $sRes .= "</TBODY>";
  2118. $sRes .= "</TABLE>";
  2119. return $sRes;
  2120. }
  2121. }
  2122. ?>