attributedef.class.inc.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194
  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. if (empty($sValue)) return '';
  663. return MetaModel::GetName($sValue);
  664. }
  665. public function RequiresIndex()
  666. {
  667. return true;
  668. }
  669. }
  670. /**
  671. * An attibute that matches one of the language codes availables in the dictionnary
  672. *
  673. * @package iTopORM
  674. */
  675. class AttributeApplicationLanguage extends AttributeString
  676. {
  677. static protected function ListExpectedParams()
  678. {
  679. return parent::ListExpectedParams();
  680. }
  681. public function __construct($sCode, $aParams)
  682. {
  683. $this->m_sCode = $sCode;
  684. $aAvailableLanguages = Dict::GetLanguages();
  685. $aLanguageCodes = array();
  686. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  687. {
  688. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  689. }
  690. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  691. parent::__construct($sCode, $aParams);
  692. }
  693. public function RequiresIndex()
  694. {
  695. return true;
  696. }
  697. }
  698. /**
  699. * The attribute dedicated to the finalclass automatic attribute
  700. *
  701. * @package iTopORM
  702. */
  703. class AttributeFinalClass extends AttributeString
  704. {
  705. public function __construct($sCode, $aParams)
  706. {
  707. $this->m_sCode = $sCode;
  708. $aParams["allowed_values"] = null;
  709. parent::__construct($sCode, $aParams);
  710. $this->m_sValue = $this->Get("default_value");
  711. }
  712. public function IsWritable()
  713. {
  714. return false;
  715. }
  716. public function RequiresIndex()
  717. {
  718. return true;
  719. }
  720. public function SetFixedValue($sValue)
  721. {
  722. $this->m_sValue = $sValue;
  723. }
  724. public function GetDefaultValue()
  725. {
  726. return $this->m_sValue;
  727. }
  728. public function GetAsHTML($sValue)
  729. {
  730. if (empty($sValue)) return '';
  731. return MetaModel::GetName($sValue);
  732. }
  733. }
  734. /**
  735. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  736. *
  737. * @package iTopORM
  738. */
  739. class AttributePassword extends AttributeString
  740. {
  741. static protected function ListExpectedParams()
  742. {
  743. return parent::ListExpectedParams();
  744. //return array_merge(parent::ListExpectedParams(), array());
  745. }
  746. public function GetEditClass() {return "Password";}
  747. protected function GetSQLCol() {return "VARCHAR(64)";}
  748. public function GetFilterDefinitions()
  749. {
  750. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  751. // not allowed to search on passwords!
  752. return array();
  753. }
  754. public function GetAsHTML($sValue)
  755. {
  756. if (strlen($sValue) == 0)
  757. {
  758. return '';
  759. }
  760. else
  761. {
  762. return '******';
  763. }
  764. }
  765. }
  766. /**
  767. * Map a text column (size < 255) to an attribute that is encrypted in the database
  768. * The encryption is based on a key set per iTop instance. Thus if you export your
  769. * database (in SQL) to someone else without providing the key at the same time
  770. * the encrypted fields will remain encrypted
  771. *
  772. * @package iTopORM
  773. */
  774. class AttributeEncryptedString extends AttributeString
  775. {
  776. static $sKey = null; // Encryption key used for all encrypted fields
  777. public function __construct($sCode, $aParams)
  778. {
  779. parent::__construct($sCode, $aParams);
  780. if (self::$sKey == null)
  781. {
  782. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  783. }
  784. }
  785. protected function GetSQLCol() {return "TINYBLOB";}
  786. public function GetFilterDefinitions()
  787. {
  788. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  789. // not allowed to search on encrypted fields !
  790. return array();
  791. }
  792. public function MakeRealValue($proposedValue)
  793. {
  794. if (is_null($proposedValue)) return null;
  795. return (string)$proposedValue;
  796. }
  797. /**
  798. * Decrypt the value when reading from the database
  799. */
  800. public function FromSQLToValue($aCols, $sPrefix = '')
  801. {
  802. $oSimpleCrypt = new SimpleCrypt();
  803. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  804. return $sValue;
  805. }
  806. /**
  807. * Encrypt the value before storing it in the database
  808. */
  809. public function GetSQLValues($value)
  810. {
  811. $oSimpleCrypt = new SimpleCrypt();
  812. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  813. $aValues = array();
  814. $aValues[$this->Get("sql")] = $encryptedValue;
  815. return $aValues;
  816. }
  817. }
  818. /**
  819. * Map a text column (size > ?) to an attribute
  820. *
  821. * @package iTopORM
  822. */
  823. class AttributeText extends AttributeString
  824. {
  825. public function GetType() {return "Text";}
  826. public function GetTypeDesc() {return "Multiline character string";}
  827. public function GetEditClass() {return "Text";}
  828. protected function GetSQLCol() {return "TEXT";}
  829. public function GetAsHTML($sValue)
  830. {
  831. return str_replace("\n", "<br>\n", parent::GetAsHTML($sValue));
  832. }
  833. public function GetAsXML($value)
  834. {
  835. return Str::pure2xml($value);
  836. }
  837. }
  838. /**
  839. * Specialization of a string: email
  840. *
  841. * @package iTopORM
  842. */
  843. class AttributeEmailAddress extends AttributeString
  844. {
  845. public function GetTypeDesc() {return "Email address(es)";}
  846. public function GetValidationPattern()
  847. {
  848. return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  849. }
  850. }
  851. /**
  852. * Specialization of a string: IP address
  853. *
  854. * @package iTopORM
  855. */
  856. class AttributeIPAddress extends AttributeString
  857. {
  858. public function GetTypeDesc() {return "IP address";}
  859. public function GetValidationPattern()
  860. {
  861. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  862. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  863. }
  864. }
  865. /**
  866. * Specialization of a string: OQL expression
  867. *
  868. * @package iTopORM
  869. */
  870. class AttributeOQL extends AttributeString
  871. {
  872. public function GetTypeDesc() {return "OQL expression";}
  873. }
  874. /**
  875. * Specialization of a string: template
  876. *
  877. * @package iTopORM
  878. */
  879. class AttributeTemplateString extends AttributeString
  880. {
  881. public function GetTypeDesc() {return "Template string";}
  882. }
  883. /**
  884. * Specialization of a text: template
  885. *
  886. * @package iTopORM
  887. */
  888. class AttributeTemplateText extends AttributeText
  889. {
  890. public function GetTypeDesc() {return "Multiline template string";}
  891. }
  892. /**
  893. * Specialization of a text: wiki formatting
  894. *
  895. * @package iTopORM
  896. */
  897. class AttributeWikiText extends AttributeText
  898. {
  899. public function GetTypeDesc() {return "Multiline string with special formatting such as links to objects";}
  900. public function GetAsHTML($value)
  901. {
  902. // [SELECT xxxx.... [label]] => hyperlink to a result list
  903. // {SELECT xxxx.... [label]} => result list displayed inline
  904. // [myclass/nnn [label]] => hyperlink to an object
  905. // {myclass/nnn/attcode} => attribute displayed inline
  906. // etc.
  907. return parent::GetAsHTML($value);
  908. }
  909. }
  910. /**
  911. * Map a enum column to an attribute
  912. *
  913. * @package iTopORM
  914. */
  915. class AttributeEnum extends AttributeString
  916. {
  917. static protected function ListExpectedParams()
  918. {
  919. return parent::ListExpectedParams();
  920. //return array_merge(parent::ListExpectedParams(), array());
  921. }
  922. public function GetType() {return "Enum";}
  923. public function GetTypeDesc() {return "List of predefined alphanumeric strings";}
  924. public function GetEditClass() {return "String";}
  925. protected function GetSQLCol()
  926. {
  927. $oValDef = $this->GetValuesDef();
  928. if ($oValDef)
  929. {
  930. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  931. }
  932. else
  933. {
  934. $aValues = array();
  935. }
  936. if (count($aValues) > 0)
  937. {
  938. // The syntax used here do matters
  939. // In particular, I had to remove unnecessary spaces to
  940. // make sure that this string will match the field type returned by the DB
  941. // (used to perform a comparison between the current DB format and the data model)
  942. return "ENUM(".implode(",", $aValues).")";
  943. }
  944. else
  945. {
  946. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  947. }
  948. }
  949. public function RequiresIndex()
  950. {
  951. return false;
  952. }
  953. public function GetBasicFilterOperators()
  954. {
  955. return parent::GetBasicFilterOperators();
  956. }
  957. public function GetBasicFilterLooseOperator()
  958. {
  959. return parent::GetBasicFilterLooseOperator();
  960. }
  961. public function GetBasicFilterSQLExpr($sOpCode, $value)
  962. {
  963. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  964. }
  965. public function GetAsHTML($sValue)
  966. {
  967. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  968. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', $sValue);
  969. // later, we could imagine a detailed description in the title
  970. return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  971. }
  972. public function GetEditValue($sValue)
  973. {
  974. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  975. return $sLabel;
  976. }
  977. public function GetAllowedValues($aArgs = array(), $sBeginsWith = '')
  978. {
  979. $aRawValues = parent::GetAllowedValues($aArgs, $sBeginsWith);
  980. if (is_null($aRawValues)) return null;
  981. $aLocalizedValues = array();
  982. foreach ($aRawValues as $sKey => $sValue)
  983. {
  984. $aLocalizedValues[$sKey] = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sKey, $sKey);
  985. }
  986. return $aLocalizedValues;
  987. }
  988. }
  989. /**
  990. * Map a date+time column to an attribute
  991. *
  992. * @package iTopORM
  993. */
  994. class AttributeDateTime extends AttributeDBField
  995. {
  996. //const MYDATETIMEZONE = "UTC";
  997. const MYDATETIMEZONE = "Europe/Paris";
  998. static protected $const_TIMEZONE = null; // set once for all upon object construct
  999. static public function InitStatics()
  1000. {
  1001. // Init static constant once for all (remove when PHP allows real static const)
  1002. self::$const_TIMEZONE = new DateTimeZone(self::MYDATETIMEZONE);
  1003. // #@# Init default timezone -> do not get a notice... to be improved !!!
  1004. // duplicated in the email test page (the mail function does trigger a notice as well)
  1005. date_default_timezone_set(self::MYDATETIMEZONE);
  1006. }
  1007. static protected function GetDateFormat()
  1008. {
  1009. return "Y-m-d H:i:s";
  1010. }
  1011. static protected function ListExpectedParams()
  1012. {
  1013. return parent::ListExpectedParams();
  1014. //return array_merge(parent::ListExpectedParams(), array());
  1015. }
  1016. public function GetType() {return "Date";}
  1017. public function GetTypeDesc() {return "Date and time";}
  1018. public function GetEditClass() {return "DateTime";}
  1019. protected function GetSQLCol() {return "TIMESTAMP";}
  1020. public static function GetAsUnixSeconds($value)
  1021. {
  1022. $oDeadlineDateTime = new DateTime($value, self::$const_TIMEZONE);
  1023. $iUnixSeconds = $oDeadlineDateTime->format('U');
  1024. return $iUnixSeconds;
  1025. }
  1026. // #@# THIS HAS TO REVISED
  1027. // Having null not allowed was interpreted by mySQL
  1028. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  1029. // Then, on each update of the record, the field was modified.
  1030. // We will have to specify the default value if we want to restore this option
  1031. // In fact, we could also have more verbs dedicated to the DB:
  1032. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  1033. public function IsNullAllowed() {return true;}
  1034. public function GetDefaultValue()
  1035. {
  1036. $default = parent::GetDefaultValue();
  1037. if (!parent::IsNullAllowed())
  1038. {
  1039. if (empty($default))
  1040. {
  1041. $default = date(self::GetDateFormat());
  1042. }
  1043. }
  1044. return $default;
  1045. }
  1046. // END OF THE WORKAROUND
  1047. ///////////////////////////////////////////////////////////////
  1048. public function GetValidationPattern()
  1049. {
  1050. 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$";
  1051. }
  1052. public function GetBasicFilterOperators()
  1053. {
  1054. return array(
  1055. "="=>"equals",
  1056. "!="=>"differs from",
  1057. "<"=>"before",
  1058. "<="=>"before",
  1059. ">"=>"after (strictly)",
  1060. ">="=>"after",
  1061. "SameDay"=>"same day (strip time)",
  1062. "SameMonth"=>"same year/month",
  1063. "SameYear"=>"same year",
  1064. "Today"=>"today",
  1065. ">|"=>"after today + N days",
  1066. "<|"=>"before today + N days",
  1067. "=|"=>"equals today + N days",
  1068. );
  1069. }
  1070. public function GetBasicFilterLooseOperator()
  1071. {
  1072. // Unless we implement a "same xxx, depending on given precision" !
  1073. return "=";
  1074. }
  1075. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1076. {
  1077. $sQValue = CMDBSource::Quote($value);
  1078. switch ($sOpCode)
  1079. {
  1080. case '=':
  1081. case '!=':
  1082. case '<':
  1083. case '<=':
  1084. case '>':
  1085. case '>=':
  1086. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1087. case 'SameDay':
  1088. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  1089. case 'SameMonth':
  1090. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  1091. case 'SameYear':
  1092. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  1093. case 'Today':
  1094. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  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. case '=|':
  1100. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1101. default:
  1102. return $this->GetSQLExpr()." = $sQValue";
  1103. }
  1104. }
  1105. public function MakeRealValue($proposedValue)
  1106. {
  1107. if (is_null($proposedValue))
  1108. {
  1109. return null;
  1110. }
  1111. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  1112. {
  1113. return null;
  1114. }
  1115. if (!is_numeric($proposedValue))
  1116. {
  1117. return $proposedValue;
  1118. }
  1119. return date(self::GetDateFormat(), $proposedValue);
  1120. }
  1121. public function ScalarToSQL($value)
  1122. {
  1123. if (is_null($value))
  1124. {
  1125. return null;
  1126. }
  1127. elseif (empty($value))
  1128. {
  1129. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  1130. return '0000-00-00 00:00:00';
  1131. }
  1132. return $value;
  1133. }
  1134. public function GetAsHTML($value)
  1135. {
  1136. return Str::pure2html($value);
  1137. }
  1138. public function GetAsXML($value)
  1139. {
  1140. return Str::pure2xml($value);
  1141. }
  1142. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1143. {
  1144. $sFrom = array("\r\n", $sTextQualifier);
  1145. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1146. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1147. return '"'.$sEscaped.'"';
  1148. }
  1149. /**
  1150. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  1151. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  1152. * does nothing special, and just calls the default (loose) operator
  1153. * @param string $sSearchText The search string to analyze for smart patterns
  1154. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  1155. * @param Hash $aParams Values of the query parameters
  1156. * @return Expression The search condition to be added (AND) to the current search
  1157. */
  1158. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  1159. {
  1160. // Possible smart patterns
  1161. $aPatterns = array(
  1162. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  1163. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  1164. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  1165. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  1166. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  1167. );
  1168. $sPatternFound = '';
  1169. $aMatches = array();
  1170. foreach($aPatterns as $sPatName => $sPattern)
  1171. {
  1172. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  1173. {
  1174. $sPatternFound = $sPatName;
  1175. break;
  1176. }
  1177. }
  1178. switch($sPatternFound)
  1179. {
  1180. case 'between':
  1181. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  1182. $oRightExpr = new VariableExpression($sParamName1);
  1183. $aParams[$sParamName1] = $aMatches[1];
  1184. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  1185. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  1186. $oRightExpr = new VariableExpression($sParamName2);
  1187. $sOperator = $this->GetBasicFilterLooseOperator();
  1188. $aParams[$sParamName2] = $aMatches[2];
  1189. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  1190. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  1191. break;
  1192. case 'greater than':
  1193. case 'greater than or equal':
  1194. case 'less than':
  1195. case 'less than or equal':
  1196. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  1197. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  1198. $oRightExpr = new VariableExpression($sParamName);
  1199. $aParams[$sParamName] = $aMatches[1];
  1200. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  1201. break;
  1202. default:
  1203. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  1204. }
  1205. return $oNewCondition;
  1206. }
  1207. }
  1208. /**
  1209. * Map a date+time column to an attribute
  1210. *
  1211. * @package iTopORM
  1212. */
  1213. class AttributeDate extends AttributeDateTime
  1214. {
  1215. const MYDATEFORMAT = "Y-m-d";
  1216. static protected function GetDateFormat()
  1217. {
  1218. return "Y-m-d";
  1219. }
  1220. static public function InitStatics()
  1221. {
  1222. // Nothing to do...
  1223. }
  1224. static protected function ListExpectedParams()
  1225. {
  1226. return parent::ListExpectedParams();
  1227. //return array_merge(parent::ListExpectedParams(), array());
  1228. }
  1229. public function GetType() {return "Date";}
  1230. public function GetTypeDesc() {return "Date";}
  1231. public function GetEditClass() {return "Date";}
  1232. protected function GetSQLCol() {return "DATE";}
  1233. public function GetValidationPattern()
  1234. {
  1235. 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)))$";
  1236. }
  1237. }
  1238. // Init static constant once for all (remove when PHP allows real static const)
  1239. AttributeDate::InitStatics();
  1240. /**
  1241. * A dead line stored as a date & time
  1242. * The only difference with the DateTime attribute is the display:
  1243. * relative to the current time
  1244. */
  1245. class AttributeDeadline extends AttributeDateTime
  1246. {
  1247. public function GetAsHTML($value)
  1248. {
  1249. $sResult = '';
  1250. if ($value !== null)
  1251. {
  1252. $value = AttributeDateTime::GetAsUnixSeconds($value);
  1253. $difference = $value - time();
  1254. if ($difference >= 0)
  1255. {
  1256. $sResult = self::FormatDuration($difference);
  1257. }
  1258. else
  1259. {
  1260. $sResult = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  1261. }
  1262. }
  1263. return $sResult;
  1264. }
  1265. static function FormatDuration($duration)
  1266. {
  1267. $days = floor($duration / 86400);
  1268. $hours = floor(($duration - (86400*$days)) / 3600);
  1269. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  1270. $sResult = '';
  1271. if ($duration < 60)
  1272. {
  1273. // Less than 1 min
  1274. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  1275. }
  1276. else if ($duration < 3600)
  1277. {
  1278. // less than 1 hour, display it in minutes
  1279. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  1280. }
  1281. else if ($duration < 86400)
  1282. {
  1283. // Less that 1 day, display it in hours/minutes
  1284. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  1285. }
  1286. else
  1287. {
  1288. // Less that 1 day, display it in hours/minutes
  1289. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  1290. }
  1291. return $sResult;
  1292. }
  1293. }
  1294. // Init static constant once for all (remove when PHP allows real static const)
  1295. AttributeDateTime::InitStatics();
  1296. /**
  1297. * Map a foreign key to an attribute
  1298. * AttributeExternalKey and AttributeExternalField may be an external key
  1299. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  1300. * where an AttributeExternalField corresponds to a column into another table (class)
  1301. *
  1302. * @package iTopORM
  1303. */
  1304. class AttributeExternalKey extends AttributeDBFieldVoid
  1305. {
  1306. static protected function ListExpectedParams()
  1307. {
  1308. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  1309. }
  1310. public function GetType() {return "Extkey";}
  1311. public function GetTypeDesc() {return "Link to another object";}
  1312. public function GetEditClass() {return "ExtKey";}
  1313. protected function GetSQLCol() {return "INT(11)";}
  1314. public function RequiresIndex()
  1315. {
  1316. return true;
  1317. }
  1318. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  1319. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  1320. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  1321. public function GetKeyAttCode() {return $this->GetCode();}
  1322. public function GetDefaultValue() {return 0;}
  1323. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  1324. public function GetBasicFilterOperators()
  1325. {
  1326. return parent::GetBasicFilterOperators();
  1327. }
  1328. public function GetBasicFilterLooseOperator()
  1329. {
  1330. return parent::GetBasicFilterLooseOperator();
  1331. }
  1332. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1333. {
  1334. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1335. }
  1336. // overloaded here so that an ext key always have the answer to
  1337. // "what are your possible values?"
  1338. public function GetValuesDef()
  1339. {
  1340. $oValSetDef = $this->Get("allowed_values");
  1341. if (!$oValSetDef)
  1342. {
  1343. // Let's propose every existing value
  1344. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1345. }
  1346. return $oValSetDef;
  1347. }
  1348. public function GetAllowedValues($aArgs = array(), $sBeginsWith = '')
  1349. {
  1350. try
  1351. {
  1352. return parent::GetAllowedValues($aArgs, $sBeginsWith);
  1353. }
  1354. catch (MissingQueryArgument $e)
  1355. {
  1356. // Some required arguments could not be found, enlarge to any existing value
  1357. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1358. return $oValSetDef->GetValues($aArgs, $sBeginsWith);
  1359. }
  1360. }
  1361. public function GetDeletionPropagationOption()
  1362. {
  1363. return $this->Get("on_target_delete");
  1364. }
  1365. public function GetNullValue()
  1366. {
  1367. return 0;
  1368. }
  1369. public function IsNull($proposedValue)
  1370. {
  1371. return ($proposedValue == 0);
  1372. }
  1373. public function MakeRealValue($proposedValue)
  1374. {
  1375. if (is_null($proposedValue)) return 0;
  1376. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  1377. return (int)$proposedValue;
  1378. }
  1379. }
  1380. /**
  1381. * An attribute which corresponds to an external key (direct or indirect)
  1382. *
  1383. * @package iTopORM
  1384. */
  1385. class AttributeExternalField extends AttributeDefinition
  1386. {
  1387. static protected function ListExpectedParams()
  1388. {
  1389. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  1390. }
  1391. public function GetType() {return "ExtkeyField";}
  1392. public function GetTypeDesc() {return "Field of an object pointed to by the current object";}
  1393. public function GetEditClass() {return "ExtField";}
  1394. protected function GetSQLCol()
  1395. {
  1396. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  1397. $oExtAttDef = $this->GetExtAttDef();
  1398. return $oExtAttDef->GetSQLCol();
  1399. }
  1400. public function GetLabel()
  1401. {
  1402. $oRemoteAtt = $this->GetExtAttDef();
  1403. $sDefault = $oRemoteAtt->GetLabel();
  1404. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $sDefault);
  1405. }
  1406. public function GetDescription()
  1407. {
  1408. $oRemoteAtt = $this->GetExtAttDef();
  1409. $sDefault = $oRemoteAtt->GetDescription();
  1410. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', $sDefault);
  1411. }
  1412. public function GetHelpOnEdition()
  1413. {
  1414. $oRemoteAtt = $this->GetExtAttDef();
  1415. $sDefault = $oRemoteAtt->GetHelpOnEdition();
  1416. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', $sDefault);
  1417. }
  1418. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  1419. {
  1420. switch($iType)
  1421. {
  1422. case EXTKEY_ABSOLUTE:
  1423. // see further
  1424. $oRemoteAtt = $this->GetExtAttDef();
  1425. return $oRemoteAtt->IsExternalKey($iType);
  1426. case EXTKEY_RELATIVE:
  1427. return false;
  1428. default:
  1429. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1430. }
  1431. }
  1432. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  1433. {
  1434. return $this->GetKeyAttDef($iType)->GetTargetClass();
  1435. }
  1436. public function IsExternalField() {return true;}
  1437. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  1438. public function GetExtAttCode() {return $this->Get("target_attcode");}
  1439. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  1440. {
  1441. switch($iType)
  1442. {
  1443. case EXTKEY_ABSOLUTE:
  1444. // see further
  1445. $oRemoteAtt = $this->GetExtAttDef();
  1446. if ($oRemoteAtt->IsExternalField())
  1447. {
  1448. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1449. }
  1450. else if ($oRemoteAtt->IsExternalKey())
  1451. {
  1452. return $oRemoteAtt;
  1453. }
  1454. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  1455. case EXTKEY_RELATIVE:
  1456. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  1457. default:
  1458. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1459. }
  1460. }
  1461. public function GetExtAttDef()
  1462. {
  1463. $oKeyAttDef = $this->GetKeyAttDef();
  1464. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->Get("targetclass"), $this->Get("target_attcode"));
  1465. 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"));
  1466. return $oExtAttDef;
  1467. }
  1468. public function GetSQLExpr()
  1469. {
  1470. $oExtAttDef = $this->GetExtAttDef();
  1471. return $oExtAttDef->GetSQLExpr();
  1472. }
  1473. public function GetDefaultValue()
  1474. {
  1475. $oExtAttDef = $this->GetExtAttDef();
  1476. return $oExtAttDef->GetDefaultValue();
  1477. }
  1478. public function IsNullAllowed()
  1479. {
  1480. $oExtAttDef = $this->GetExtAttDef();
  1481. return $oExtAttDef->IsNullAllowed();
  1482. }
  1483. public function IsScalar()
  1484. {
  1485. $oExtAttDef = $this->GetExtAttDef();
  1486. return $oExtAttDef->IsScalar();
  1487. }
  1488. public function GetFilterDefinitions()
  1489. {
  1490. return array($this->GetCode() => new FilterFromAttribute($this));
  1491. }
  1492. public function GetBasicFilterOperators()
  1493. {
  1494. $oExtAttDef = $this->GetExtAttDef();
  1495. return $oExtAttDef->GetBasicFilterOperators();
  1496. }
  1497. public function GetBasicFilterLooseOperator()
  1498. {
  1499. $oExtAttDef = $this->GetExtAttDef();
  1500. return $oExtAttDef->GetBasicFilterLooseOperator();
  1501. }
  1502. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1503. {
  1504. $oExtAttDef = $this->GetExtAttDef();
  1505. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  1506. }
  1507. public function GetNullValue()
  1508. {
  1509. $oExtAttDef = $this->GetExtAttDef();
  1510. return $oExtAttDef->GetNullValue();
  1511. }
  1512. public function IsNull($proposedValue)
  1513. {
  1514. $oExtAttDef = $this->GetExtAttDef();
  1515. return $oExtAttDef->IsNull($proposedValue);
  1516. }
  1517. public function MakeRealValue($proposedValue)
  1518. {
  1519. $oExtAttDef = $this->GetExtAttDef();
  1520. return $oExtAttDef->MakeRealValue($proposedValue);
  1521. }
  1522. public function ScalarToSQL($value)
  1523. {
  1524. // This one could be used in case of filtering only
  1525. $oExtAttDef = $this->GetExtAttDef();
  1526. return $oExtAttDef->ScalarToSQL($value);
  1527. }
  1528. // Do not overload GetSQLExpression here because this is handled in the joins
  1529. //public function GetSQLExpressions() {return array();}
  1530. // Here, we get the data...
  1531. public function FromSQLToValue($aCols, $sPrefix = '')
  1532. {
  1533. $oExtAttDef = $this->GetExtAttDef();
  1534. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  1535. }
  1536. public function GetAsHTML($value)
  1537. {
  1538. $oExtAttDef = $this->GetExtAttDef();
  1539. return $oExtAttDef->GetAsHTML($value);
  1540. }
  1541. public function GetAsXML($value)
  1542. {
  1543. $oExtAttDef = $this->GetExtAttDef();
  1544. return $oExtAttDef->GetAsXML($value);
  1545. }
  1546. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"')
  1547. {
  1548. $oExtAttDef = $this->GetExtAttDef();
  1549. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  1550. }
  1551. }
  1552. /**
  1553. * Map a varchar column to an URL (formats the ouput in HMTL)
  1554. *
  1555. * @package iTopORM
  1556. */
  1557. class AttributeURL extends AttributeString
  1558. {
  1559. static protected function ListExpectedParams()
  1560. {
  1561. //return parent::ListExpectedParams();
  1562. return array_merge(parent::ListExpectedParams(), array("target"));
  1563. }
  1564. public function GetType() {return "Url";}
  1565. public function GetTypeDesc() {return "Absolute or relative URL as a text string";}
  1566. public function GetEditClass() {return "String";}
  1567. public function GetAsHTML($sValue)
  1568. {
  1569. $sTarget = $this->Get("target");
  1570. if (empty($sTarget)) $sTarget = "_blank";
  1571. $sLabel = Str::pure2html($sValue);
  1572. if (strlen($sLabel) > 40)
  1573. {
  1574. // Truncate the length to about 40 characters, by removing the middle
  1575. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  1576. }
  1577. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  1578. }
  1579. public function GetValidationPattern()
  1580. {
  1581. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  1582. }
  1583. }
  1584. /**
  1585. * A blob is an ormDocument, it is stored as several columns in the database
  1586. *
  1587. * @package iTopORM
  1588. */
  1589. class AttributeBlob extends AttributeDefinition
  1590. {
  1591. static protected function ListExpectedParams()
  1592. {
  1593. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  1594. }
  1595. public function GetType() {return "Blob";}
  1596. public function GetTypeDesc() {return "Document";}
  1597. public function GetEditClass() {return "Document";}
  1598. public function IsDirectField() {return true;}
  1599. public function IsScalar() {return true;}
  1600. public function IsWritable() {return true;}
  1601. public function GetDefaultValue() {return "";}
  1602. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  1603. // Facilitate things: allow the user to Set the value from a string
  1604. public function MakeRealValue($proposedValue)
  1605. {
  1606. if (!is_object($proposedValue))
  1607. {
  1608. return new ormDocument($proposedValue, 'text/plain');
  1609. }
  1610. return $proposedValue;
  1611. }
  1612. public function GetSQLExpressions()
  1613. {
  1614. $aColumns = array();
  1615. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1616. $aColumns[''] = $this->GetCode().'_mimetype';
  1617. $aColumns['_data'] = $this->GetCode().'_data';
  1618. $aColumns['_filename'] = $this->GetCode().'_filename';
  1619. return $aColumns;
  1620. }
  1621. public function FromSQLToValue($aCols, $sPrefix = '')
  1622. {
  1623. if (!isset($aCols[$sPrefix]))
  1624. {
  1625. $sAvailable = implode(', ', array_keys($aCols));
  1626. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1627. }
  1628. $sMimeType = $aCols[$sPrefix];
  1629. if (!isset($aCols[$sPrefix.'_data']))
  1630. {
  1631. $sAvailable = implode(', ', array_keys($aCols));
  1632. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  1633. }
  1634. $data = $aCols[$sPrefix.'_data'];
  1635. if (!isset($aCols[$sPrefix.'_filename']))
  1636. {
  1637. $sAvailable = implode(', ', array_keys($aCols));
  1638. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  1639. }
  1640. $sFileName = $aCols[$sPrefix.'_filename'];
  1641. $value = new ormDocument($data, $sMimeType, $sFileName);
  1642. return $value;
  1643. }
  1644. public function GetSQLValues($value)
  1645. {
  1646. // #@# Optimization: do not load blobs anytime
  1647. // As per mySQL doc, selecting blob columns will prevent mySQL from
  1648. // using memory in case a temporary table has to be created
  1649. // (temporary tables created on disk)
  1650. // We will have to remove the blobs from the list of attributes when doing the select
  1651. // then the use of Get() should finalize the load
  1652. if ($value instanceOf ormDocument)
  1653. {
  1654. $aValues = array();
  1655. $aValues[$this->GetCode().'_data'] = $value->GetData();
  1656. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  1657. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  1658. }
  1659. else
  1660. {
  1661. $aValues = array();
  1662. $aValues[$this->GetCode().'_data'] = '';
  1663. $aValues[$this->GetCode().'_mimetype'] = '';
  1664. $aValues[$this->GetCode().'_filename'] = '';
  1665. }
  1666. return $aValues;
  1667. }
  1668. public function GetSQLColumns()
  1669. {
  1670. $aColumns = array();
  1671. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  1672. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  1673. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  1674. return $aColumns;
  1675. }
  1676. public function GetFilterDefinitions()
  1677. {
  1678. return array();
  1679. // still not working... see later...
  1680. return array(
  1681. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  1682. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  1683. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  1684. );
  1685. }
  1686. public function GetBasicFilterOperators()
  1687. {
  1688. return array();
  1689. }
  1690. public function GetBasicFilterLooseOperator()
  1691. {
  1692. return '=';
  1693. }
  1694. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1695. {
  1696. return 'true';
  1697. }
  1698. public function GetAsHTML($value)
  1699. {
  1700. if (is_object($value))
  1701. {
  1702. return $value->GetAsHTML();
  1703. }
  1704. }
  1705. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1706. {
  1707. return ''; // Not exportable in CSV !
  1708. }
  1709. public function GetAsXML($value)
  1710. {
  1711. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  1712. }
  1713. }
  1714. /**
  1715. * One way encrypted (hashed) password
  1716. */
  1717. class AttributeOneWayPassword extends AttributeDefinition
  1718. {
  1719. static protected function ListExpectedParams()
  1720. {
  1721. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  1722. }
  1723. public function GetType() {return "One Way Password";}
  1724. public function GetTypeDesc() {return "One Way Password";}
  1725. public function GetEditClass() {return "One Way Password";}
  1726. public function IsDirectField() {return true;}
  1727. public function IsScalar() {return true;}
  1728. public function IsWritable() {return true;}
  1729. public function GetDefaultValue() {return "";}
  1730. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  1731. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  1732. public function MakeRealValue($proposedValue)
  1733. {
  1734. $oPassword = $proposedValue;
  1735. if (!is_object($oPassword))
  1736. {
  1737. $oPassword = new ormPassword('', '');
  1738. $oPassword->SetPassword($proposedValue);
  1739. }
  1740. return $oPassword;
  1741. }
  1742. public function GetSQLExpressions()
  1743. {
  1744. $aColumns = array();
  1745. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1746. $aColumns[''] = $this->GetCode().'_hash';
  1747. $aColumns['_salt'] = $this->GetCode().'_salt';
  1748. return $aColumns;
  1749. }
  1750. public function FromSQLToValue($aCols, $sPrefix = '')
  1751. {
  1752. if (!isset($aCols[$sPrefix]))
  1753. {
  1754. $sAvailable = implode(', ', array_keys($aCols));
  1755. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1756. }
  1757. $hashed = $aCols[$sPrefix];
  1758. if (!isset($aCols[$sPrefix.'_salt']))
  1759. {
  1760. $sAvailable = implode(', ', array_keys($aCols));
  1761. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  1762. }
  1763. $sSalt = $aCols[$sPrefix.'_salt'];
  1764. $value = new ormPassword($hashed, $sSalt);
  1765. return $value;
  1766. }
  1767. public function GetSQLValues($value)
  1768. {
  1769. // #@# Optimization: do not load blobs anytime
  1770. // As per mySQL doc, selecting blob columns will prevent mySQL from
  1771. // using memory in case a temporary table has to be created
  1772. // (temporary tables created on disk)
  1773. // We will have to remove the blobs from the list of attributes when doing the select
  1774. // then the use of Get() should finalize the load
  1775. if ($value instanceOf ormPassword)
  1776. {
  1777. $aValues = array();
  1778. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  1779. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  1780. }
  1781. else
  1782. {
  1783. $aValues = array();
  1784. $aValues[$this->GetCode().'_hash'] = '';
  1785. $aValues[$this->GetCode().'_salt'] = '';
  1786. }
  1787. return $aValues;
  1788. }
  1789. public function GetSQLColumns()
  1790. {
  1791. $aColumns = array();
  1792. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  1793. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  1794. return $aColumns;
  1795. }
  1796. public function GetFilterDefinitions()
  1797. {
  1798. return array();
  1799. // still not working... see later...
  1800. }
  1801. public function GetBasicFilterOperators()
  1802. {
  1803. return array();
  1804. }
  1805. public function GetBasicFilterLooseOperator()
  1806. {
  1807. return '=';
  1808. }
  1809. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1810. {
  1811. return 'true';
  1812. }
  1813. public function GetAsHTML($value)
  1814. {
  1815. if (is_object($value))
  1816. {
  1817. return $value->GetAsHTML();
  1818. }
  1819. }
  1820. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1821. {
  1822. return ''; // Not exportable in CSV
  1823. }
  1824. public function GetAsXML($value)
  1825. {
  1826. return ''; // Not exportable in XML
  1827. }
  1828. }
  1829. // Indexed array having two dimensions
  1830. class AttributeTable extends AttributeText
  1831. {
  1832. public function GetType() {return "Table";}
  1833. public function GetTypeDesc() {return "Array with 2 dimensions";}
  1834. public function GetEditClass() {return "Text";}
  1835. protected function GetSQLCol() {return "TEXT";}
  1836. // Facilitate things: allow the user to Set the value from a string
  1837. public function MakeRealValue($proposedValue)
  1838. {
  1839. if (!is_array($proposedValue))
  1840. {
  1841. return array(0 => array(0 => $proposedValue));
  1842. }
  1843. return $proposedValue;
  1844. }
  1845. public function FromSQLToValue($aCols, $sPrefix = '')
  1846. {
  1847. try
  1848. {
  1849. $value = @unserialize($aCols[$sPrefix.'']);
  1850. if ($value === false)
  1851. {
  1852. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  1853. }
  1854. }
  1855. catch(Exception $e)
  1856. {
  1857. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  1858. }
  1859. return $value;
  1860. }
  1861. public function GetSQLValues($value)
  1862. {
  1863. $aValues = array();
  1864. $aValues[$this->Get("sql")] = serialize($value);
  1865. return $aValues;
  1866. }
  1867. public function GetAsHTML($value)
  1868. {
  1869. if (!is_array($value))
  1870. {
  1871. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  1872. }
  1873. if (count($value) == 0)
  1874. {
  1875. return "";
  1876. }
  1877. $sRes = "<TABLE class=\"listResults\">";
  1878. $sRes .= "<TBODY>";
  1879. foreach($value as $iRow => $aRawData)
  1880. {
  1881. $sRes .= "<TR>";
  1882. foreach ($aRawData as $iCol => $cell)
  1883. {
  1884. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  1885. $sRes .= "<TD>$sCell</TD>";
  1886. }
  1887. $sRes .= "</TR>";
  1888. }
  1889. $sRes .= "</TBODY>";
  1890. $sRes .= "</TABLE>";
  1891. return $sRes;
  1892. }
  1893. }
  1894. // The PHP value is a hash array, it is stored as a TEXT column
  1895. class AttributePropertySet extends AttributeTable
  1896. {
  1897. public function GetType() {return "PropertySet";}
  1898. public function GetTypeDesc() {return "List of properties (name and value)";}
  1899. public function GetEditClass() {return "Text";}
  1900. protected function GetSQLCol() {return "TEXT";}
  1901. // Facilitate things: allow the user to Set the value from a string
  1902. public function MakeRealValue($proposedValue)
  1903. {
  1904. if (!is_array($proposedValue))
  1905. {
  1906. return array('?' => (string)$proposedValue);
  1907. }
  1908. return $proposedValue;
  1909. }
  1910. public function GetAsHTML($value)
  1911. {
  1912. if (!is_array($value))
  1913. {
  1914. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  1915. }
  1916. if (count($value) == 0)
  1917. {
  1918. return "";
  1919. }
  1920. $sRes = "<TABLE class=\"listResults\">";
  1921. $sRes .= "<TBODY>";
  1922. foreach($value as $sProperty => $sValue)
  1923. {
  1924. $sRes .= "<TR>";
  1925. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  1926. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  1927. $sRes .= "</TR>";
  1928. }
  1929. $sRes .= "</TBODY>";
  1930. $sRes .= "</TABLE>";
  1931. return $sRes;
  1932. }
  1933. }
  1934. ?>