attributedef.class.inc.php 61 KB

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