attributedef.class.inc.php 60 KB

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