attributedef.class.inc.php 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590
  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 determined 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. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  926. class AttributeText extends AttributeString
  927. {
  928. public function GetEditClass() {return "Text";}
  929. protected function GetSQLCol() {return "TEXT";}
  930. public function GetMaxSize()
  931. {
  932. // Is there a way to know the current limitation for mysql?
  933. // See mysql_field_len()
  934. return 65535;
  935. }
  936. public function GetAsHTML($sValue)
  937. {
  938. $sValue = parent::GetAsHTML($sValue);
  939. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  940. {
  941. foreach($aAllMatches as $iPos => $aMatches)
  942. {
  943. $sClass = $aMatches[1];
  944. $sName = $aMatches[2];
  945. if (MetaModel::IsValidClass($sClass))
  946. {
  947. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  948. if (is_object($oObj))
  949. {
  950. // Propose a std link to the object
  951. $sValue = str_replace($aMatches[0], $oObj->GetHyperlink(), $sValue);
  952. }
  953. else
  954. {
  955. // Propose a std link to the object
  956. $sClassLabel = MetaModel::GetName($sClass);
  957. $sValue = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sValue);
  958. // Later: propose a link to create a new object
  959. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  960. //$sValue = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="./UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sValue);
  961. }
  962. }
  963. }
  964. }
  965. return str_replace("\n", "<br>\n", $sValue);
  966. }
  967. public function GetEditValue($sValue)
  968. {
  969. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  970. {
  971. foreach($aAllMatches as $iPos => $aMatches)
  972. {
  973. $sClass = $aMatches[1];
  974. $sName = $aMatches[2];
  975. if (MetaModel::IsValidClass($sClass))
  976. {
  977. $sClassLabel = MetaModel::GetName($sClass);
  978. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  979. }
  980. }
  981. }
  982. return $sValue;
  983. }
  984. public function MakeRealValue($proposedValue)
  985. {
  986. $sValue = $proposedValue;
  987. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  988. {
  989. foreach($aAllMatches as $iPos => $aMatches)
  990. {
  991. $sClassLabel = $aMatches[1];
  992. $sName = $aMatches[2];
  993. if (!MetaModel::IsValidClass($sClassLabel))
  994. {
  995. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  996. if ($sClass)
  997. {
  998. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  999. }
  1000. }
  1001. }
  1002. }
  1003. return $sValue;
  1004. }
  1005. public function GetAsXML($value)
  1006. {
  1007. return Str::pure2xml($value);
  1008. }
  1009. }
  1010. /**
  1011. * Map a text column (size > ?), containing HTML code, to an attribute
  1012. *
  1013. * @package iTopORM
  1014. */
  1015. class AttributeHTML extends AttributeText
  1016. {
  1017. public function GetEditClass() {return "HTML";}
  1018. public function GetAsHTML($sValue)
  1019. {
  1020. return $sValue;
  1021. }
  1022. }
  1023. /**
  1024. * Specialization of a string: email
  1025. *
  1026. * @package iTopORM
  1027. */
  1028. class AttributeEmailAddress extends AttributeString
  1029. {
  1030. public function GetValidationPattern()
  1031. {
  1032. // return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  1033. return "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$";
  1034. }
  1035. public function GetAsHTML($sValue)
  1036. {
  1037. if (empty($sValue)) return '';
  1038. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  1039. }
  1040. }
  1041. /**
  1042. * Specialization of a string: IP address
  1043. *
  1044. * @package iTopORM
  1045. */
  1046. class AttributeIPAddress extends AttributeString
  1047. {
  1048. public function GetValidationPattern()
  1049. {
  1050. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  1051. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  1052. }
  1053. }
  1054. /**
  1055. * Specialization of a string: OQL expression
  1056. *
  1057. * @package iTopORM
  1058. */
  1059. class AttributeOQL extends AttributeText
  1060. {
  1061. }
  1062. /**
  1063. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1064. *
  1065. * @package iTopORM
  1066. */
  1067. class AttributeTemplateString extends AttributeString
  1068. {
  1069. }
  1070. /**
  1071. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1072. *
  1073. * @package iTopORM
  1074. */
  1075. class AttributeTemplateText extends AttributeText
  1076. {
  1077. }
  1078. /**
  1079. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1080. *
  1081. * @package iTopORM
  1082. */
  1083. class AttributeTemplateHTML extends AttributeText
  1084. {
  1085. public function GetEditClass() {return "HTML";}
  1086. public function GetAsHTML($sValue)
  1087. {
  1088. return $sValue;
  1089. }
  1090. }
  1091. /**
  1092. * Specialization of a text: wiki formatting
  1093. *
  1094. * @package iTopORM
  1095. */
  1096. class AttributeWikiText extends AttributeText
  1097. {
  1098. public function GetAsHTML($value)
  1099. {
  1100. // [SELECT xxxx.... [label]] => hyperlink to a result list
  1101. // {SELECT xxxx.... [label]} => result list displayed inline
  1102. // [myclass/nnn [label]] => hyperlink to an object
  1103. // {myclass/nnn/attcode} => attribute displayed inline
  1104. // etc.
  1105. return parent::GetAsHTML($value);
  1106. }
  1107. }
  1108. /**
  1109. * Map a enum column to an attribute
  1110. *
  1111. * @package iTopORM
  1112. */
  1113. class AttributeEnum extends AttributeString
  1114. {
  1115. static protected function ListExpectedParams()
  1116. {
  1117. return parent::ListExpectedParams();
  1118. //return array_merge(parent::ListExpectedParams(), array());
  1119. }
  1120. public function GetEditClass() {return "String";}
  1121. protected function GetSQLCol()
  1122. {
  1123. $oValDef = $this->GetValuesDef();
  1124. if ($oValDef)
  1125. {
  1126. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  1127. }
  1128. else
  1129. {
  1130. $aValues = array();
  1131. }
  1132. if (count($aValues) > 0)
  1133. {
  1134. // The syntax used here do matters
  1135. // In particular, I had to remove unnecessary spaces to
  1136. // make sure that this string will match the field type returned by the DB
  1137. // (used to perform a comparison between the current DB format and the data model)
  1138. return "ENUM(".implode(",", $aValues).")";
  1139. }
  1140. else
  1141. {
  1142. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  1143. }
  1144. }
  1145. public function ScalarToSQL($value)
  1146. {
  1147. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  1148. // but that wasn't working for enums, because '' is NOT one of the allowed values
  1149. // that's why a null value must be forced to a real null
  1150. $value = parent::ScalarToSQL($value);
  1151. if ($this->IsNull($value))
  1152. {
  1153. return null;
  1154. }
  1155. else
  1156. {
  1157. return $value;
  1158. }
  1159. }
  1160. public function RequiresIndex()
  1161. {
  1162. return false;
  1163. }
  1164. public function GetBasicFilterOperators()
  1165. {
  1166. return parent::GetBasicFilterOperators();
  1167. }
  1168. public function GetBasicFilterLooseOperator()
  1169. {
  1170. return parent::GetBasicFilterLooseOperator();
  1171. }
  1172. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1173. {
  1174. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1175. }
  1176. public function GetAsHTML($sValue)
  1177. {
  1178. if (is_null($sValue))
  1179. {
  1180. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1181. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  1182. }
  1183. else
  1184. {
  1185. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1186. }
  1187. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', $sValue);
  1188. // later, we could imagine a detailed description in the title
  1189. return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  1190. }
  1191. public function GetEditValue($sValue)
  1192. {
  1193. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1194. return $sLabel;
  1195. }
  1196. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1197. {
  1198. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  1199. if (is_null($aRawValues)) return null;
  1200. $aLocalizedValues = array();
  1201. foreach ($aRawValues as $sKey => $sValue)
  1202. {
  1203. $aLocalizedValues[$sKey] = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sKey, $sKey);
  1204. }
  1205. return $aLocalizedValues;
  1206. }
  1207. /**
  1208. * Processes the input value to align it with the values supported
  1209. * by this type of attribute. In this case: turns empty strings into nulls
  1210. * @param mixed $proposedValue The value to be set for the attribute
  1211. * @return mixed The actual value that will be set
  1212. */
  1213. public function MakeRealValue($proposedValue)
  1214. {
  1215. if ($proposedValue == '') return null;
  1216. return parent::MakeRealValue($proposedValue);
  1217. }
  1218. }
  1219. /**
  1220. * Map a date+time column to an attribute
  1221. *
  1222. * @package iTopORM
  1223. */
  1224. class AttributeDateTime extends AttributeDBField
  1225. {
  1226. //const MYDATETIMEZONE = "UTC";
  1227. const MYDATETIMEZONE = "Europe/Paris";
  1228. static protected $const_TIMEZONE = null; // set once for all upon object construct
  1229. static public function InitStatics()
  1230. {
  1231. // Init static constant once for all (remove when PHP allows real static const)
  1232. self::$const_TIMEZONE = new DateTimeZone(self::MYDATETIMEZONE);
  1233. // #@# Init default timezone -> do not get a notice... to be improved !!!
  1234. // duplicated in the email test page (the mail function does trigger a notice as well)
  1235. date_default_timezone_set(self::MYDATETIMEZONE);
  1236. }
  1237. static protected function GetDateFormat()
  1238. {
  1239. return "Y-m-d H:i:s";
  1240. }
  1241. static protected function ListExpectedParams()
  1242. {
  1243. return parent::ListExpectedParams();
  1244. //return array_merge(parent::ListExpectedParams(), array());
  1245. }
  1246. public function GetEditClass() {return "DateTime";}
  1247. protected function GetSQLCol() {return "TIMESTAMP";}
  1248. public static function GetAsUnixSeconds($value)
  1249. {
  1250. $oDeadlineDateTime = new DateTime($value, self::$const_TIMEZONE);
  1251. $iUnixSeconds = $oDeadlineDateTime->format('U');
  1252. return $iUnixSeconds;
  1253. }
  1254. // #@# THIS HAS TO REVISED
  1255. // Having null not allowed was interpreted by mySQL
  1256. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  1257. // Then, on each update of the record, the field was modified.
  1258. // We will have to specify the default value if we want to restore this option
  1259. // In fact, we could also have more verbs dedicated to the DB:
  1260. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  1261. public function IsNullAllowed() {return true;}
  1262. public function GetDefaultValue()
  1263. {
  1264. $default = parent::GetDefaultValue();
  1265. if (!parent::IsNullAllowed())
  1266. {
  1267. if (empty($default))
  1268. {
  1269. $default = date(self::GetDateFormat());
  1270. }
  1271. }
  1272. return $default;
  1273. }
  1274. // END OF THE WORKAROUND
  1275. ///////////////////////////////////////////////////////////////
  1276. public function GetValidationPattern()
  1277. {
  1278. 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$";
  1279. }
  1280. public function GetBasicFilterOperators()
  1281. {
  1282. return array(
  1283. "="=>"equals",
  1284. "!="=>"differs from",
  1285. "<"=>"before",
  1286. "<="=>"before",
  1287. ">"=>"after (strictly)",
  1288. ">="=>"after",
  1289. "SameDay"=>"same day (strip time)",
  1290. "SameMonth"=>"same year/month",
  1291. "SameYear"=>"same year",
  1292. "Today"=>"today",
  1293. ">|"=>"after today + N days",
  1294. "<|"=>"before today + N days",
  1295. "=|"=>"equals today + N days",
  1296. );
  1297. }
  1298. public function GetBasicFilterLooseOperator()
  1299. {
  1300. // Unless we implement a "same xxx, depending on given precision" !
  1301. return "=";
  1302. }
  1303. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1304. {
  1305. $sQValue = CMDBSource::Quote($value);
  1306. switch ($sOpCode)
  1307. {
  1308. case '=':
  1309. case '!=':
  1310. case '<':
  1311. case '<=':
  1312. case '>':
  1313. case '>=':
  1314. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1315. case 'SameDay':
  1316. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  1317. case 'SameMonth':
  1318. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  1319. case 'SameYear':
  1320. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  1321. case 'Today':
  1322. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  1323. case '>|':
  1324. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1325. case '<|':
  1326. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1327. case '=|':
  1328. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1329. default:
  1330. return $this->GetSQLExpr()." = $sQValue";
  1331. }
  1332. }
  1333. public function MakeRealValue($proposedValue)
  1334. {
  1335. if (is_null($proposedValue))
  1336. {
  1337. return null;
  1338. }
  1339. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  1340. {
  1341. return null;
  1342. }
  1343. if (!is_numeric($proposedValue))
  1344. {
  1345. return $proposedValue;
  1346. }
  1347. return date(self::GetDateFormat(), $proposedValue);
  1348. }
  1349. public function ScalarToSQL($value)
  1350. {
  1351. if (is_null($value))
  1352. {
  1353. return null;
  1354. }
  1355. elseif (empty($value))
  1356. {
  1357. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  1358. return '0000-00-00 00:00:00';
  1359. }
  1360. return $value;
  1361. }
  1362. public function GetAsHTML($value)
  1363. {
  1364. return Str::pure2html($value);
  1365. }
  1366. public function GetAsXML($value)
  1367. {
  1368. return Str::pure2xml($value);
  1369. }
  1370. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1371. {
  1372. $sFrom = array("\r\n", $sTextQualifier);
  1373. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1374. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1375. return '"'.$sEscaped.'"';
  1376. }
  1377. /**
  1378. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  1379. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  1380. * does nothing special, and just calls the default (loose) operator
  1381. * @param string $sSearchText The search string to analyze for smart patterns
  1382. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  1383. * @param Hash $aParams Values of the query parameters
  1384. * @return Expression The search condition to be added (AND) to the current search
  1385. */
  1386. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  1387. {
  1388. // Possible smart patterns
  1389. $aPatterns = array(
  1390. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  1391. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  1392. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  1393. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  1394. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  1395. );
  1396. $sPatternFound = '';
  1397. $aMatches = array();
  1398. foreach($aPatterns as $sPatName => $sPattern)
  1399. {
  1400. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  1401. {
  1402. $sPatternFound = $sPatName;
  1403. break;
  1404. }
  1405. }
  1406. switch($sPatternFound)
  1407. {
  1408. case 'between':
  1409. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  1410. $oRightExpr = new VariableExpression($sParamName1);
  1411. $aParams[$sParamName1] = $aMatches[1];
  1412. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  1413. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  1414. $oRightExpr = new VariableExpression($sParamName2);
  1415. $sOperator = $this->GetBasicFilterLooseOperator();
  1416. $aParams[$sParamName2] = $aMatches[2];
  1417. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  1418. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  1419. break;
  1420. case 'greater than':
  1421. case 'greater than or equal':
  1422. case 'less than':
  1423. case 'less than or equal':
  1424. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  1425. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  1426. $oRightExpr = new VariableExpression($sParamName);
  1427. $aParams[$sParamName] = $aMatches[1];
  1428. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  1429. break;
  1430. default:
  1431. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  1432. }
  1433. return $oNewCondition;
  1434. }
  1435. }
  1436. /**
  1437. * Map a date+time column to an attribute
  1438. *
  1439. * @package iTopORM
  1440. */
  1441. class AttributeDate extends AttributeDateTime
  1442. {
  1443. const MYDATEFORMAT = "Y-m-d";
  1444. static protected function GetDateFormat()
  1445. {
  1446. return "Y-m-d";
  1447. }
  1448. static public function InitStatics()
  1449. {
  1450. // Nothing to do...
  1451. }
  1452. static protected function ListExpectedParams()
  1453. {
  1454. return parent::ListExpectedParams();
  1455. //return array_merge(parent::ListExpectedParams(), array());
  1456. }
  1457. public function GetEditClass() {return "Date";}
  1458. protected function GetSQLCol() {return "DATE";}
  1459. public function GetValidationPattern()
  1460. {
  1461. 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)))$";
  1462. }
  1463. }
  1464. // Init static constant once for all (remove when PHP allows real static const)
  1465. AttributeDate::InitStatics();
  1466. /**
  1467. * A dead line stored as a date & time
  1468. * The only difference with the DateTime attribute is the display:
  1469. * relative to the current time
  1470. */
  1471. class AttributeDeadline extends AttributeDateTime
  1472. {
  1473. public function GetAsHTML($value)
  1474. {
  1475. $sResult = '';
  1476. if ($value !== null)
  1477. {
  1478. $value = AttributeDateTime::GetAsUnixSeconds($value);
  1479. $difference = $value - time();
  1480. if ($difference >= 0)
  1481. {
  1482. $sResult = self::FormatDuration($difference);
  1483. }
  1484. else
  1485. {
  1486. $sResult = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  1487. }
  1488. }
  1489. return $sResult;
  1490. }
  1491. static function FormatDuration($duration)
  1492. {
  1493. $days = floor($duration / 86400);
  1494. $hours = floor(($duration - (86400*$days)) / 3600);
  1495. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  1496. $sResult = '';
  1497. if ($duration < 60)
  1498. {
  1499. // Less than 1 min
  1500. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  1501. }
  1502. else if ($duration < 3600)
  1503. {
  1504. // less than 1 hour, display it in minutes
  1505. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  1506. }
  1507. else if ($duration < 86400)
  1508. {
  1509. // Less that 1 day, display it in hours/minutes
  1510. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  1511. }
  1512. else
  1513. {
  1514. // Less that 1 day, display it in hours/minutes
  1515. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  1516. }
  1517. return $sResult;
  1518. }
  1519. }
  1520. // Init static constant once for all (remove when PHP allows real static const)
  1521. AttributeDateTime::InitStatics();
  1522. /**
  1523. * Map a foreign key to an attribute
  1524. * AttributeExternalKey and AttributeExternalField may be an external key
  1525. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  1526. * where an AttributeExternalField corresponds to a column into another table (class)
  1527. *
  1528. * @package iTopORM
  1529. */
  1530. class AttributeExternalKey extends AttributeDBFieldVoid
  1531. {
  1532. static protected function ListExpectedParams()
  1533. {
  1534. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  1535. }
  1536. public function GetEditClass() {return "ExtKey";}
  1537. protected function GetSQLCol() {return "INT(11)";}
  1538. public function RequiresIndex()
  1539. {
  1540. return true;
  1541. }
  1542. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  1543. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  1544. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  1545. public function GetKeyAttCode() {return $this->GetCode();}
  1546. public function GetDefaultValue() {return 0;}
  1547. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  1548. public function GetBasicFilterOperators()
  1549. {
  1550. return parent::GetBasicFilterOperators();
  1551. }
  1552. public function GetBasicFilterLooseOperator()
  1553. {
  1554. return parent::GetBasicFilterLooseOperator();
  1555. }
  1556. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1557. {
  1558. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1559. }
  1560. // overloaded here so that an ext key always have the answer to
  1561. // "what are your possible values?"
  1562. public function GetValuesDef()
  1563. {
  1564. $oValSetDef = $this->Get("allowed_values");
  1565. if (!$oValSetDef)
  1566. {
  1567. // Let's propose every existing value
  1568. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1569. }
  1570. return $oValSetDef;
  1571. }
  1572. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1573. {
  1574. try
  1575. {
  1576. return parent::GetAllowedValues($aArgs, $sContains);
  1577. }
  1578. catch (MissingQueryArgument $e)
  1579. {
  1580. // Some required arguments could not be found, enlarge to any existing value
  1581. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1582. return $oValSetDef->GetValues($aArgs, $sContains);
  1583. }
  1584. }
  1585. public function GetDeletionPropagationOption()
  1586. {
  1587. return $this->Get("on_target_delete");
  1588. }
  1589. public function GetNullValue()
  1590. {
  1591. return 0;
  1592. }
  1593. public function IsNull($proposedValue)
  1594. {
  1595. return ($proposedValue == 0);
  1596. }
  1597. public function MakeRealValue($proposedValue)
  1598. {
  1599. if (is_null($proposedValue)) return 0;
  1600. if ($proposedValue === '') return 0;
  1601. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  1602. return (int)$proposedValue;
  1603. }
  1604. public function GetMaximumComboLength()
  1605. {
  1606. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  1607. }
  1608. public function GetMinAutoCompleteChars()
  1609. {
  1610. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  1611. }
  1612. public function AllowTargetCreation()
  1613. {
  1614. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  1615. }
  1616. }
  1617. /**
  1618. * An attribute which corresponds to an external key (direct or indirect)
  1619. *
  1620. * @package iTopORM
  1621. */
  1622. class AttributeExternalField extends AttributeDefinition
  1623. {
  1624. static protected function ListExpectedParams()
  1625. {
  1626. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  1627. }
  1628. public function GetEditClass() {return "ExtField";}
  1629. protected function GetSQLCol()
  1630. {
  1631. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  1632. $oExtAttDef = $this->GetExtAttDef();
  1633. return $oExtAttDef->GetSQLCol();
  1634. }
  1635. public function GetSQLExpressions()
  1636. {
  1637. return array('' => $this->GetCode());
  1638. }
  1639. public function GetLabel()
  1640. {
  1641. $oRemoteAtt = $this->GetExtAttDef();
  1642. $sDefault = $oRemoteAtt->GetLabel();
  1643. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $sDefault);
  1644. }
  1645. public function GetDescription()
  1646. {
  1647. $oRemoteAtt = $this->GetExtAttDef();
  1648. $sDefault = $oRemoteAtt->GetDescription();
  1649. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', $sDefault);
  1650. }
  1651. public function GetHelpOnEdition()
  1652. {
  1653. $oRemoteAtt = $this->GetExtAttDef();
  1654. $sDefault = $oRemoteAtt->GetHelpOnEdition();
  1655. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', $sDefault);
  1656. }
  1657. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  1658. {
  1659. switch($iType)
  1660. {
  1661. case EXTKEY_ABSOLUTE:
  1662. // see further
  1663. $oRemoteAtt = $this->GetExtAttDef();
  1664. return $oRemoteAtt->IsExternalKey($iType);
  1665. case EXTKEY_RELATIVE:
  1666. return false;
  1667. default:
  1668. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1669. }
  1670. }
  1671. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  1672. {
  1673. return $this->GetKeyAttDef($iType)->GetTargetClass();
  1674. }
  1675. public function IsExternalField() {return true;}
  1676. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  1677. public function GetExtAttCode() {return $this->Get("target_attcode");}
  1678. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  1679. {
  1680. switch($iType)
  1681. {
  1682. case EXTKEY_ABSOLUTE:
  1683. // see further
  1684. $oRemoteAtt = $this->GetExtAttDef();
  1685. if ($oRemoteAtt->IsExternalField())
  1686. {
  1687. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1688. }
  1689. else if ($oRemoteAtt->IsExternalKey())
  1690. {
  1691. return $oRemoteAtt;
  1692. }
  1693. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  1694. case EXTKEY_RELATIVE:
  1695. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  1696. default:
  1697. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1698. }
  1699. }
  1700. public function GetExtAttDef()
  1701. {
  1702. $oKeyAttDef = $this->GetKeyAttDef();
  1703. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->Get("targetclass"), $this->Get("target_attcode"));
  1704. 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"));
  1705. return $oExtAttDef;
  1706. }
  1707. public function GetSQLExpr()
  1708. {
  1709. $oExtAttDef = $this->GetExtAttDef();
  1710. return $oExtAttDef->GetSQLExpr();
  1711. }
  1712. public function GetDefaultValue()
  1713. {
  1714. $oExtAttDef = $this->GetExtAttDef();
  1715. return $oExtAttDef->GetDefaultValue();
  1716. }
  1717. public function IsNullAllowed()
  1718. {
  1719. $oExtAttDef = $this->GetExtAttDef();
  1720. return $oExtAttDef->IsNullAllowed();
  1721. }
  1722. public function IsScalar()
  1723. {
  1724. $oExtAttDef = $this->GetExtAttDef();
  1725. return $oExtAttDef->IsScalar();
  1726. }
  1727. public function GetFilterDefinitions()
  1728. {
  1729. return array($this->GetCode() => new FilterFromAttribute($this));
  1730. }
  1731. public function GetBasicFilterOperators()
  1732. {
  1733. $oExtAttDef = $this->GetExtAttDef();
  1734. return $oExtAttDef->GetBasicFilterOperators();
  1735. }
  1736. public function GetBasicFilterLooseOperator()
  1737. {
  1738. $oExtAttDef = $this->GetExtAttDef();
  1739. return $oExtAttDef->GetBasicFilterLooseOperator();
  1740. }
  1741. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1742. {
  1743. $oExtAttDef = $this->GetExtAttDef();
  1744. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  1745. }
  1746. public function GetNullValue()
  1747. {
  1748. $oExtAttDef = $this->GetExtAttDef();
  1749. return $oExtAttDef->GetNullValue();
  1750. }
  1751. public function IsNull($proposedValue)
  1752. {
  1753. $oExtAttDef = $this->GetExtAttDef();
  1754. return $oExtAttDef->IsNull($proposedValue);
  1755. }
  1756. public function MakeRealValue($proposedValue)
  1757. {
  1758. $oExtAttDef = $this->GetExtAttDef();
  1759. return $oExtAttDef->MakeRealValue($proposedValue);
  1760. }
  1761. public function ScalarToSQL($value)
  1762. {
  1763. // This one could be used in case of filtering only
  1764. $oExtAttDef = $this->GetExtAttDef();
  1765. return $oExtAttDef->ScalarToSQL($value);
  1766. }
  1767. // Do not overload GetSQLExpression here because this is handled in the joins
  1768. //public function GetSQLExpressions() {return array();}
  1769. // Here, we get the data...
  1770. public function FromSQLToValue($aCols, $sPrefix = '')
  1771. {
  1772. $oExtAttDef = $this->GetExtAttDef();
  1773. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  1774. }
  1775. public function GetAsHTML($value)
  1776. {
  1777. $oExtAttDef = $this->GetExtAttDef();
  1778. return $oExtAttDef->GetAsHTML($value);
  1779. }
  1780. public function GetAsXML($value)
  1781. {
  1782. $oExtAttDef = $this->GetExtAttDef();
  1783. return $oExtAttDef->GetAsXML($value);
  1784. }
  1785. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"')
  1786. {
  1787. $oExtAttDef = $this->GetExtAttDef();
  1788. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  1789. }
  1790. }
  1791. /**
  1792. * Map a varchar column to an URL (formats the ouput in HMTL)
  1793. *
  1794. * @package iTopORM
  1795. */
  1796. class AttributeURL extends AttributeString
  1797. {
  1798. static protected function ListExpectedParams()
  1799. {
  1800. //return parent::ListExpectedParams();
  1801. return array_merge(parent::ListExpectedParams(), array("target"));
  1802. }
  1803. public function GetEditClass() {return "String";}
  1804. public function GetAsHTML($sValue)
  1805. {
  1806. $sTarget = $this->Get("target");
  1807. if (empty($sTarget)) $sTarget = "_blank";
  1808. $sLabel = Str::pure2html($sValue);
  1809. if (strlen($sLabel) > 40)
  1810. {
  1811. // Truncate the length to about 40 characters, by removing the middle
  1812. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  1813. }
  1814. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  1815. }
  1816. public function GetValidationPattern()
  1817. {
  1818. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  1819. }
  1820. }
  1821. /**
  1822. * A blob is an ormDocument, it is stored as several columns in the database
  1823. *
  1824. * @package iTopORM
  1825. */
  1826. class AttributeBlob extends AttributeDefinition
  1827. {
  1828. static protected function ListExpectedParams()
  1829. {
  1830. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  1831. }
  1832. public function GetEditClass() {return "Document";}
  1833. public function IsDirectField() {return true;}
  1834. public function IsScalar() {return true;}
  1835. public function IsWritable() {return true;}
  1836. public function GetDefaultValue() {return "";}
  1837. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  1838. // Facilitate things: allow the user to Set the value from a string
  1839. public function MakeRealValue($proposedValue)
  1840. {
  1841. if (!is_object($proposedValue))
  1842. {
  1843. return new ormDocument($proposedValue, 'text/plain');
  1844. }
  1845. return $proposedValue;
  1846. }
  1847. public function GetSQLExpressions()
  1848. {
  1849. $aColumns = array();
  1850. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1851. $aColumns[''] = $this->GetCode().'_mimetype';
  1852. $aColumns['_data'] = $this->GetCode().'_data';
  1853. $aColumns['_filename'] = $this->GetCode().'_filename';
  1854. return $aColumns;
  1855. }
  1856. public function FromSQLToValue($aCols, $sPrefix = '')
  1857. {
  1858. if (!isset($aCols[$sPrefix]))
  1859. {
  1860. $sAvailable = implode(', ', array_keys($aCols));
  1861. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1862. }
  1863. $sMimeType = $aCols[$sPrefix];
  1864. if (!isset($aCols[$sPrefix.'_data']))
  1865. {
  1866. $sAvailable = implode(', ', array_keys($aCols));
  1867. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  1868. }
  1869. $data = $aCols[$sPrefix.'_data'];
  1870. if (!isset($aCols[$sPrefix.'_filename']))
  1871. {
  1872. $sAvailable = implode(', ', array_keys($aCols));
  1873. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  1874. }
  1875. $sFileName = $aCols[$sPrefix.'_filename'];
  1876. $value = new ormDocument($data, $sMimeType, $sFileName);
  1877. return $value;
  1878. }
  1879. public function GetSQLValues($value)
  1880. {
  1881. // #@# Optimization: do not load blobs anytime
  1882. // As per mySQL doc, selecting blob columns will prevent mySQL from
  1883. // using memory in case a temporary table has to be created
  1884. // (temporary tables created on disk)
  1885. // We will have to remove the blobs from the list of attributes when doing the select
  1886. // then the use of Get() should finalize the load
  1887. if ($value instanceOf ormDocument)
  1888. {
  1889. $aValues = array();
  1890. $aValues[$this->GetCode().'_data'] = $value->GetData();
  1891. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  1892. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  1893. }
  1894. else
  1895. {
  1896. $aValues = array();
  1897. $aValues[$this->GetCode().'_data'] = '';
  1898. $aValues[$this->GetCode().'_mimetype'] = '';
  1899. $aValues[$this->GetCode().'_filename'] = '';
  1900. }
  1901. return $aValues;
  1902. }
  1903. public function GetSQLColumns()
  1904. {
  1905. $aColumns = array();
  1906. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  1907. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  1908. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  1909. return $aColumns;
  1910. }
  1911. public function GetFilterDefinitions()
  1912. {
  1913. return array();
  1914. // still not working... see later...
  1915. return array(
  1916. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  1917. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  1918. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  1919. );
  1920. }
  1921. public function GetBasicFilterOperators()
  1922. {
  1923. return array();
  1924. }
  1925. public function GetBasicFilterLooseOperator()
  1926. {
  1927. return '=';
  1928. }
  1929. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1930. {
  1931. return 'true';
  1932. }
  1933. public function GetAsHTML($value)
  1934. {
  1935. if (is_object($value))
  1936. {
  1937. return $value->GetAsHTML();
  1938. }
  1939. }
  1940. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1941. {
  1942. return ''; // Not exportable in CSV !
  1943. }
  1944. public function GetAsXML($value)
  1945. {
  1946. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  1947. }
  1948. }
  1949. /**
  1950. * One way encrypted (hashed) password
  1951. */
  1952. class AttributeOneWayPassword extends AttributeDefinition
  1953. {
  1954. static protected function ListExpectedParams()
  1955. {
  1956. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  1957. }
  1958. public function GetEditClass() {return "One Way Password";}
  1959. public function IsDirectField() {return true;}
  1960. public function IsScalar() {return true;}
  1961. public function IsWritable() {return true;}
  1962. public function GetDefaultValue() {return "";}
  1963. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  1964. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  1965. public function MakeRealValue($proposedValue)
  1966. {
  1967. $oPassword = $proposedValue;
  1968. if (!is_object($oPassword))
  1969. {
  1970. $oPassword = new ormPassword('', '');
  1971. $oPassword->SetPassword($proposedValue);
  1972. }
  1973. return $oPassword;
  1974. }
  1975. public function GetSQLExpressions()
  1976. {
  1977. $aColumns = array();
  1978. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1979. $aColumns[''] = $this->GetCode().'_hash';
  1980. $aColumns['_salt'] = $this->GetCode().'_salt';
  1981. return $aColumns;
  1982. }
  1983. public function FromSQLToValue($aCols, $sPrefix = '')
  1984. {
  1985. if (!isset($aCols[$sPrefix]))
  1986. {
  1987. $sAvailable = implode(', ', array_keys($aCols));
  1988. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1989. }
  1990. $hashed = $aCols[$sPrefix];
  1991. if (!isset($aCols[$sPrefix.'_salt']))
  1992. {
  1993. $sAvailable = implode(', ', array_keys($aCols));
  1994. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  1995. }
  1996. $sSalt = $aCols[$sPrefix.'_salt'];
  1997. $value = new ormPassword($hashed, $sSalt);
  1998. return $value;
  1999. }
  2000. public function GetSQLValues($value)
  2001. {
  2002. // #@# Optimization: do not load blobs anytime
  2003. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2004. // using memory in case a temporary table has to be created
  2005. // (temporary tables created on disk)
  2006. // We will have to remove the blobs from the list of attributes when doing the select
  2007. // then the use of Get() should finalize the load
  2008. if ($value instanceOf ormPassword)
  2009. {
  2010. $aValues = array();
  2011. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  2012. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  2013. }
  2014. else
  2015. {
  2016. $aValues = array();
  2017. $aValues[$this->GetCode().'_hash'] = '';
  2018. $aValues[$this->GetCode().'_salt'] = '';
  2019. }
  2020. return $aValues;
  2021. }
  2022. public function GetSQLColumns()
  2023. {
  2024. $aColumns = array();
  2025. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  2026. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  2027. return $aColumns;
  2028. }
  2029. public function GetFilterDefinitions()
  2030. {
  2031. return array();
  2032. // still not working... see later...
  2033. }
  2034. public function GetBasicFilterOperators()
  2035. {
  2036. return array();
  2037. }
  2038. public function GetBasicFilterLooseOperator()
  2039. {
  2040. return '=';
  2041. }
  2042. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2043. {
  2044. return 'true';
  2045. }
  2046. public function GetAsHTML($value)
  2047. {
  2048. if (is_object($value))
  2049. {
  2050. return $value->GetAsHTML();
  2051. }
  2052. }
  2053. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  2054. {
  2055. return ''; // Not exportable in CSV
  2056. }
  2057. public function GetAsXML($value)
  2058. {
  2059. return ''; // Not exportable in XML
  2060. }
  2061. }
  2062. // Indexed array having two dimensions
  2063. class AttributeTable extends AttributeText
  2064. {
  2065. public function GetEditClass() {return "Text";}
  2066. protected function GetSQLCol() {return "TEXT";}
  2067. public function GetMaxSize()
  2068. {
  2069. return null;
  2070. }
  2071. // Facilitate things: allow the user to Set the value from a string
  2072. public function MakeRealValue($proposedValue)
  2073. {
  2074. if (!is_array($proposedValue))
  2075. {
  2076. return array(0 => array(0 => $proposedValue));
  2077. }
  2078. return $proposedValue;
  2079. }
  2080. public function FromSQLToValue($aCols, $sPrefix = '')
  2081. {
  2082. try
  2083. {
  2084. $value = @unserialize($aCols[$sPrefix.'']);
  2085. if ($value === false)
  2086. {
  2087. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  2088. }
  2089. }
  2090. catch(Exception $e)
  2091. {
  2092. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  2093. }
  2094. return $value;
  2095. }
  2096. public function GetSQLValues($value)
  2097. {
  2098. $aValues = array();
  2099. $aValues[$this->Get("sql")] = serialize($value);
  2100. return $aValues;
  2101. }
  2102. public function GetAsHTML($value)
  2103. {
  2104. if (!is_array($value))
  2105. {
  2106. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2107. }
  2108. if (count($value) == 0)
  2109. {
  2110. return "";
  2111. }
  2112. $sRes = "<TABLE class=\"listResults\">";
  2113. $sRes .= "<TBODY>";
  2114. foreach($value as $iRow => $aRawData)
  2115. {
  2116. $sRes .= "<TR>";
  2117. foreach ($aRawData as $iCol => $cell)
  2118. {
  2119. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  2120. $sRes .= "<TD>$sCell</TD>";
  2121. }
  2122. $sRes .= "</TR>";
  2123. }
  2124. $sRes .= "</TBODY>";
  2125. $sRes .= "</TABLE>";
  2126. return $sRes;
  2127. }
  2128. }
  2129. // The PHP value is a hash array, it is stored as a TEXT column
  2130. class AttributePropertySet extends AttributeTable
  2131. {
  2132. public function GetEditClass() {return "Text";}
  2133. protected function GetSQLCol() {return "TEXT";}
  2134. // Facilitate things: allow the user to Set the value from a string
  2135. public function MakeRealValue($proposedValue)
  2136. {
  2137. if (!is_array($proposedValue))
  2138. {
  2139. return array('?' => (string)$proposedValue);
  2140. }
  2141. return $proposedValue;
  2142. }
  2143. public function GetAsHTML($value)
  2144. {
  2145. if (!is_array($value))
  2146. {
  2147. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2148. }
  2149. if (count($value) == 0)
  2150. {
  2151. return "";
  2152. }
  2153. $sRes = "<TABLE class=\"listResults\">";
  2154. $sRes .= "<TBODY>";
  2155. foreach($value as $sProperty => $sValue)
  2156. {
  2157. $sRes .= "<TR>";
  2158. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  2159. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  2160. $sRes .= "</TR>";
  2161. }
  2162. $sRes .= "</TBODY>";
  2163. $sRes .= "</TABLE>";
  2164. return $sRes;
  2165. }
  2166. }
  2167. /**
  2168. * The attribute dedicated to the friendly name automatic attribute (not written)
  2169. *
  2170. * @package iTopORM
  2171. */
  2172. class AttributeComputedFieldVoid extends AttributeDefinition
  2173. {
  2174. static protected function ListExpectedParams()
  2175. {
  2176. return array_merge(parent::ListExpectedParams(), array());
  2177. }
  2178. public function GetEditClass() {return "";}
  2179. public function GetValuesDef() {return null;}
  2180. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  2181. public function IsDirectField() {return true;}
  2182. public function IsScalar() {return true;}
  2183. public function IsWritable() {return false;}
  2184. public function GetSQLExpr() {return null;}
  2185. public function GetDefaultValue() {return $this->MakeRealValue("");}
  2186. public function IsNullAllowed() {return false;}
  2187. //
  2188. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  2189. public function GetSQLExpressions()
  2190. {
  2191. return array('' => $this->GetCode());
  2192. }
  2193. public function FromSQLToValue($aCols, $sPrefix = '')
  2194. {
  2195. return null;
  2196. }
  2197. public function GetSQLValues($value)
  2198. {
  2199. return array();
  2200. }
  2201. public function GetSQLColumns()
  2202. {
  2203. return array();
  2204. }
  2205. public function GetFilterDefinitions()
  2206. {
  2207. return array($this->GetCode() => new FilterFromAttribute($this));
  2208. }
  2209. public function GetBasicFilterOperators()
  2210. {
  2211. return array();
  2212. }
  2213. public function GetBasicFilterLooseOperator()
  2214. {
  2215. return "=";
  2216. }
  2217. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2218. {
  2219. $sQValue = CMDBSource::Quote($value);
  2220. switch ($sOpCode)
  2221. {
  2222. case '!=':
  2223. return $this->GetSQLExpr()." != $sQValue";
  2224. break;
  2225. case '=':
  2226. default:
  2227. return $this->GetSQLExpr()." = $sQValue";
  2228. }
  2229. }
  2230. }
  2231. /**
  2232. * The attribute dedicated to the friendly name automatic attribute (not written)
  2233. *
  2234. * @package iTopORM
  2235. */
  2236. class AttributeFriendlyName extends AttributeComputedFieldVoid
  2237. {
  2238. public function __construct($sCode, $sExtKeyAttCode)
  2239. {
  2240. $this->m_sCode = $sCode;
  2241. $aParams = array();
  2242. // $aParams["is_null_allowed"] = false,
  2243. $aParams["default_value"] = '';
  2244. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  2245. parent::__construct($sCode, $aParams);
  2246. $this->m_sValue = $this->Get("default_value");
  2247. }
  2248. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  2249. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  2250. protected function GetSQLCol() {return "";}
  2251. public function FromSQLToValue($aCols, $sPrefix = '')
  2252. {
  2253. $sValue = $aCols[$sPrefix];
  2254. return $sValue;
  2255. }
  2256. /**
  2257. * Encrypt the value before storing it in the database
  2258. */
  2259. public function GetSQLValues($value)
  2260. {
  2261. return array();
  2262. }
  2263. public function IsWritable()
  2264. {
  2265. return false;
  2266. }
  2267. public function SetFixedValue($sValue)
  2268. {
  2269. $this->m_sValue = $sValue;
  2270. }
  2271. public function GetDefaultValue()
  2272. {
  2273. return $this->m_sValue;
  2274. }
  2275. public function GetAsHTML($sValue)
  2276. {
  2277. return Str::pure2html((string)$sValue);
  2278. }
  2279. }
  2280. ?>