attributedef.class.inc.php 65 KB

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