attributedef.class.inc.php 64 KB

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