attributedef.class.inc.php 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139
  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. require_once('ormcaselog.class.inc.php');
  28. /**
  29. * MissingColumnException - sent if an attribute is being created but the column is missing in the row
  30. *
  31. * @package iTopORM
  32. */
  33. class MissingColumnException extends Exception
  34. {}
  35. /**
  36. * add some description here...
  37. *
  38. * @package iTopORM
  39. */
  40. define('EXTKEY_RELATIVE', 1);
  41. /**
  42. * add some description here...
  43. *
  44. * @package iTopORM
  45. */
  46. define('EXTKEY_ABSOLUTE', 2);
  47. /**
  48. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  49. *
  50. * @package iTopORM
  51. */
  52. define('DEL_MANUAL', 1);
  53. /**
  54. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  55. *
  56. * @package iTopORM
  57. */
  58. define('DEL_AUTO', 2);
  59. define('DEL_SILENT', 2);
  60. /**
  61. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  62. *
  63. * @package iTopORM
  64. */
  65. abstract class AttributeDefinition
  66. {
  67. public function GetType()
  68. {
  69. return Dict::S('Core:'.get_class($this));
  70. }
  71. public function GetTypeDesc()
  72. {
  73. return Dict::S('Core:'.get_class($this).'+');
  74. }
  75. abstract public function GetEditClass();
  76. protected $m_sCode;
  77. private $m_aParams = array();
  78. protected $m_sHostClass = '!undefined!';
  79. protected function Get($sParamName) {return $this->m_aParams[$sParamName];}
  80. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  81. protected function GetOptional($sParamName, $default)
  82. {
  83. if (array_key_exists($sParamName, $this->m_aParams))
  84. {
  85. return $this->m_aParams[$sParamName];
  86. }
  87. else
  88. {
  89. return $default;
  90. }
  91. }
  92. public function __construct($sCode, $aParams)
  93. {
  94. $this->m_sCode = $sCode;
  95. $this->m_aParams = $aParams;
  96. $this->ConsistencyCheck();
  97. }
  98. public function OverloadParams($aParams)
  99. {
  100. foreach ($aParams as $sParam => $value)
  101. {
  102. if (!array_key_exists($sParam, $this->m_aParams))
  103. {
  104. throw new CoreException("Unknown attribute definition parameter '$sParam', please select a value in {".implode(", ", array_keys($this->m_aParams))."}");
  105. }
  106. else
  107. {
  108. $this->m_aParams[$sParam] = $value;
  109. }
  110. }
  111. }
  112. public function SetHostClass($sHostClass)
  113. {
  114. $this->m_sHostClass = $sHostClass;
  115. }
  116. public function GetHostClass()
  117. {
  118. return $this->m_sHostClass;
  119. }
  120. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  121. // to be overloaded
  122. static protected function ListExpectedParams()
  123. {
  124. return array();
  125. }
  126. private function ConsistencyCheck()
  127. {
  128. // Check that any mandatory param has been specified
  129. //
  130. $aExpectedParams = $this->ListExpectedParams();
  131. foreach($aExpectedParams as $sParamName)
  132. {
  133. if (!array_key_exists($sParamName, $this->m_aParams))
  134. {
  135. $aBacktrace = debug_backtrace();
  136. $sTargetClass = $aBacktrace[2]["class"];
  137. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  138. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  139. }
  140. }
  141. }
  142. // table, key field, name field
  143. public function ListDBJoins()
  144. {
  145. return "";
  146. // e.g: return array("Site", "infrid", "name");
  147. }
  148. public function IsDirectField() {return false;}
  149. public function IsScalar() {return false;}
  150. public function IsLinkSet() {return false;}
  151. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  152. public function IsExternalField() {return false;}
  153. public function IsWritable() {return false;}
  154. public function IsNullAllowed() {return true;}
  155. public function GetCode() {return $this->m_sCode;}
  156. public function GetLabel() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $this->m_sCode);}
  157. public function GetLabel_Obsolete()
  158. {
  159. // Written for compatibility with a data model written prior to version 0.9.1
  160. if (array_key_exists('label', $this->m_aParams))
  161. {
  162. return $this->m_aParams['label'];
  163. }
  164. else
  165. {
  166. return $this->GetLabel();
  167. }
  168. }
  169. public function GetDescription() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', '');}
  170. public function GetHelpOnEdition() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', '');}
  171. public function GetDescription_Obsolete()
  172. {
  173. // Written for compatibility with a data model written prior to version 0.9.1
  174. if (array_key_exists('description', $this->m_aParams))
  175. {
  176. return $this->m_aParams['description'];
  177. }
  178. else
  179. {
  180. return $this->GetDescription();
  181. }
  182. }
  183. public function GetValuesDef() {return null;}
  184. public function GetPrerequisiteAttributes() {return array();}
  185. public function GetNullValue() {return null;}
  186. public function IsNull($proposedValue) {return is_null($proposedValue);}
  187. public function MakeRealValue($proposedValue, $oHostObj) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  188. public function Equals($val1, $val2) {return ($val1 == $val2);}
  189. public function GetSQLExpressions($sPrefix = '') {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  190. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  191. public function GetSQLColumns() {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  192. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  193. public function RequiresIndex() {return false;}
  194. // Import - differs slightly from SQL input, but identical in most cases
  195. //
  196. public function GetImportColumns() {return $this->GetSQLColumns();}
  197. public function FromImportToValue($aCols, $sPrefix = '')
  198. {
  199. $aValues = array();
  200. foreach ($this->GetSQLExpressions($sPrefix) as $sAlias => $sExpr)
  201. {
  202. // This is working, based on the assumption that importable fields
  203. // are not computed fields => the expression is the name of a column
  204. $aValues[$sPrefix.$sAlias] = $aCols[$sExpr];
  205. }
  206. return $this->FromSQLToValue($aValues, $sPrefix);
  207. }
  208. public function GetValidationPattern()
  209. {
  210. return '';
  211. }
  212. public function CheckFormat($value)
  213. {
  214. return true;
  215. }
  216. public function GetMaxSize()
  217. {
  218. return null;
  219. }
  220. public function MakeValue()
  221. {
  222. $sComputeFunc = $this->Get("compute_func");
  223. if (empty($sComputeFunc)) return null;
  224. return call_user_func($sComputeFunc);
  225. }
  226. abstract public function GetDefaultValue();
  227. //
  228. // To be overloaded in subclasses
  229. //
  230. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  231. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  232. //abstract protected GetBasicFilterHTMLInput();
  233. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  234. public function GetFilterDefinitions()
  235. {
  236. return array();
  237. }
  238. public function GetEditValue($sValue)
  239. {
  240. return (string)$sValue;
  241. }
  242. public function GetAsHTML($sValue, $oHostObject = null)
  243. {
  244. return Str::pure2html((string)$sValue);
  245. }
  246. public function GetAsXML($sValue, $oHostObject = null)
  247. {
  248. return Str::pure2xml((string)$sValue);
  249. }
  250. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  251. {
  252. return (string)$sValue;
  253. }
  254. public function GetAllowedValues($aArgs = array(), $sContains = '')
  255. {
  256. $oValSetDef = $this->GetValuesDef();
  257. if (!$oValSetDef) return null;
  258. return $oValSetDef->GetValues($aArgs, $sContains);
  259. }
  260. /**
  261. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  262. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  263. * does nothing special, and just calls the default (loose) operator
  264. * @param string $sSearchText The search string to analyze for smart patterns
  265. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  266. * @param Hash $aParams Values of the query parameters
  267. * @return Expression The search condition to be added (AND) to the current search
  268. */
  269. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  270. {
  271. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  272. $oRightExpr = new VariableExpression($sParamName);
  273. $sOperator = $this->GetBasicFilterLooseOperator();
  274. switch ($sOperator)
  275. {
  276. case 'Contains':
  277. $aParams[$sParamName] = "%$sSearchText%";
  278. $sSQLOperator = 'LIKE';
  279. break;
  280. default:
  281. $sSQLOperator = $sOperator;
  282. $aParams[$sParamName] = $sSearchText;
  283. }
  284. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  285. return $oNewCondition;
  286. }
  287. }
  288. /**
  289. * Set of objects directly linked to an object, and being part of its definition
  290. *
  291. * @package iTopORM
  292. */
  293. class AttributeLinkedSet extends AttributeDefinition
  294. {
  295. static protected function ListExpectedParams()
  296. {
  297. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  298. }
  299. public function GetEditClass() {return "List";}
  300. public function IsWritable() {return true;}
  301. public function IsLinkSet() {return true;}
  302. public function IsIndirect() {return false;}
  303. public function GetValuesDef() {return $this->Get("allowed_values");}
  304. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  305. public function GetDefaultValue($aArgs = array())
  306. {
  307. // Note: so far, this feature is a prototype,
  308. // later, the argument 'this' should always be present in the arguments
  309. //
  310. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  311. {
  312. $aValues = $this->Get('default_value')->GetValues($aArgs);
  313. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  314. return $oSet;
  315. }
  316. else
  317. {
  318. return DBObjectSet::FromScratch($this->Get('linked_class'));
  319. }
  320. }
  321. public function GetLinkedClass() {return $this->Get('linked_class');}
  322. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  323. public function GetBasicFilterOperators() {return array();}
  324. public function GetBasicFilterLooseOperator() {return '';}
  325. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  326. public function GetAsHTML($sValue, $oHostObject = null)
  327. {
  328. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  329. {
  330. $sValue->Rewind();
  331. $aItems = array();
  332. while ($oObj = $sValue->Fetch())
  333. {
  334. // Show only relevant information (hide the external key to the current object)
  335. $aAttributes = array();
  336. foreach(MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef)
  337. {
  338. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  339. if ($oAttDef->IsExternalField()) continue;
  340. $sAttValue = $oObj->GetAsHTML($sAttCode);
  341. if (strlen($sAttValue) > 0)
  342. {
  343. $aAttributes[] = $sAttValue;
  344. }
  345. }
  346. $sAttributes = implode(', ', $aAttributes);
  347. $aItems[] = $sAttributes;
  348. }
  349. return implode('<br/>', $aItems);
  350. }
  351. return null;
  352. }
  353. public function GetAsXML($sValue, $oHostObject = null)
  354. {
  355. return "Sorry, no yet implemented";
  356. }
  357. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  358. {
  359. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  360. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  361. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  362. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  363. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  364. {
  365. $sValue->Rewind();
  366. $aItems = array();
  367. while ($oObj = $sValue->Fetch())
  368. {
  369. $sObjClass = get_class($oObj);
  370. // Show only relevant information (hide the external key to the current object)
  371. $aAttributes = array();
  372. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  373. {
  374. if ($sAttCode == 'finalclass')
  375. {
  376. if ($sObjClass == $this->GetLinkedClass())
  377. {
  378. // Simplify the output if the exact class could be determined implicitely
  379. continue;
  380. }
  381. }
  382. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  383. if ($oAttDef->IsExternalField()) continue;
  384. if (!$oAttDef->IsDirectField()) continue;
  385. if (!$oAttDef->IsScalar()) continue;
  386. $sAttValue = $oObj->GetAsCSV($sAttCode, $sSepValue, '');
  387. if (strlen($sAttValue) > 0)
  388. {
  389. $sAttributeData = str_replace($sAttributeQualifier, $sAttributeQualifier.$sAttributeQualifier, $sAttCode.$sSepValue.$sAttValue);
  390. $aAttributes[] = $sAttributeQualifier.$sAttributeData.$sAttributeQualifier;
  391. }
  392. }
  393. $sAttributes = implode($sSepAttribute, $aAttributes);
  394. $aItems[] = $sAttributes;
  395. }
  396. $sRes = implode($sSepItem, $aItems);
  397. }
  398. else
  399. {
  400. $sRes = '';
  401. }
  402. $sRes = str_replace($sTextQualifier, $sTextQualifier.$sTextQualifier, $sRes);
  403. $sRes = $sTextQualifier.$sRes.$sTextQualifier;
  404. return $sRes;
  405. }
  406. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  407. // Specific to this kind of attribute : transform a string into a value
  408. public function MakeValueFromString($sProposedValue, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  409. {
  410. if (is_null($sSepItem))
  411. {
  412. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  413. }
  414. if (is_null($sSepAttribute))
  415. {
  416. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  417. }
  418. if (is_null($sSepValue))
  419. {
  420. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  421. }
  422. if (is_null($sAttributeQualifier))
  423. {
  424. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  425. }
  426. $sTargetClass = $this->Get('linked_class');
  427. $sInput = str_replace($sSepItem, "\n", $sProposedValue);
  428. $oCSVParser = new CSVParser($sInput, $sSepAttribute, $sAttributeQualifier);
  429. $aInput = $oCSVParser->ToArray(0 /* do not skip lines */);
  430. $aLinks = array();
  431. foreach($aInput as $aRow)
  432. {
  433. // 1st - get the values, split the extkey->searchkey specs, and eventually get the finalclass value
  434. $aExtKeys = array();
  435. $aValues = array();
  436. foreach($aRow as $sCell)
  437. {
  438. $iSepPos = strpos($sCell, $sSepValue);
  439. if ($iSepPos === false)
  440. {
  441. // Houston...
  442. throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell));
  443. }
  444. $sAttCode = trim(substr($sCell, 0, $iSepPos));
  445. $sValue = substr($sCell, $iSepPos + strlen($sSepValue));
  446. if (preg_match('/^(.+)->(.+)$/', $sAttCode, $aMatches))
  447. {
  448. $sKeyAttCode = $aMatches[1];
  449. $sRemoteAttCode = $aMatches[2];
  450. $aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue;
  451. if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode))
  452. {
  453. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sKeyAttCode));
  454. }
  455. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  456. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  457. if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode))
  458. {
  459. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode));
  460. }
  461. }
  462. else
  463. {
  464. if(!MetaModel::IsValidAttCode($sTargetClass, $sAttCode))
  465. {
  466. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sAttCode));
  467. }
  468. $aValues[$sAttCode] = $sValue;
  469. }
  470. }
  471. // 2nd - Instanciate the object and set the value
  472. if (isset($aValues['finalclass']))
  473. {
  474. $sLinkClass = $aValues['finalclass'];
  475. if (!is_subclass_of($sLinkClass, $sTargetClass))
  476. {
  477. throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
  478. }
  479. }
  480. elseif (MetaModel::IsAbstract($sTargetClass))
  481. {
  482. throw new CoreException('Missing finalclass for link attribute specification');
  483. }
  484. else
  485. {
  486. $sLinkClass = $sTargetClass;
  487. }
  488. $oLink = MetaModel::NewObject($sLinkClass);
  489. foreach ($aValues as $sAttCode => $sValue)
  490. {
  491. $oLink->Set($sAttCode, $sValue);
  492. }
  493. // 3rd - Set external keys from search conditions
  494. foreach ($aExtKeys as $sKeyAttCode => $aReconciliation)
  495. {
  496. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  497. $sKeyClass = $oKeyAttDef->GetTargetClass();
  498. $oExtKeyFilter = new CMDBSearchFilter($sKeyClass);
  499. $aReconciliationDesc = array();
  500. foreach($aReconciliation as $sRemoteAttCode => $sValue)
  501. {
  502. $oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '=');
  503. $aReconciliationDesc[] = "$sRemoteAttCode=$sValue";
  504. }
  505. $oExtKeySet = new CMDBObjectSet($oExtKeyFilter);
  506. switch($oExtKeySet->Count())
  507. {
  508. case 0:
  509. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  510. throw new CoreException("Found no match", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  511. break;
  512. case 1:
  513. $oRemoteObj = $oExtKeySet->Fetch();
  514. $oLink->Set($sKeyAttCode, $oRemoteObj->GetKey());
  515. break;
  516. default:
  517. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  518. throw new CoreException("Found several matches", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  519. // Found several matches, ambiguous
  520. }
  521. }
  522. $aLinks[] = $oLink;
  523. }
  524. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  525. return $oSet;
  526. }
  527. public function Equals($val1, $val2)
  528. {
  529. if ($val1 === $val2) return true;
  530. if (is_object($val1) != is_object($val2))
  531. {
  532. return false;
  533. }
  534. if (!is_object($val1))
  535. {
  536. // string ?
  537. // todo = implement this case ?
  538. return false;
  539. }
  540. // Both values are Object sets
  541. return $val1->HasSameContents($val2);
  542. }
  543. }
  544. /**
  545. * Set of objects linked to an object (n-n), and being part of its definition
  546. *
  547. * @package iTopORM
  548. */
  549. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  550. {
  551. static protected function ListExpectedParams()
  552. {
  553. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  554. }
  555. public function IsIndirect() {return true;}
  556. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  557. public function GetEditClass() {return "LinkedSet";}
  558. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  559. }
  560. /**
  561. * Abstract class implementing default filters for a DB column
  562. *
  563. * @package iTopORM
  564. */
  565. class AttributeDBFieldVoid extends AttributeDefinition
  566. {
  567. static protected function ListExpectedParams()
  568. {
  569. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  570. }
  571. // To be overriden, used in GetSQLColumns
  572. protected function GetSQLCol() {return "VARCHAR(255)";}
  573. public function GetEditClass() {return "String";}
  574. public function GetValuesDef() {return $this->Get("allowed_values");}
  575. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  576. public function IsDirectField() {return true;}
  577. public function IsScalar() {return true;}
  578. public function IsWritable() {return true;}
  579. public function GetSQLExpr() {return $this->Get("sql");}
  580. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  581. public function IsNullAllowed() {return false;}
  582. //
  583. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  584. public function GetSQLExpressions($sPrefix = '')
  585. {
  586. $aColumns = array();
  587. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  588. $aColumns[''] = $this->Get("sql");
  589. return $aColumns;
  590. }
  591. public function FromSQLToValue($aCols, $sPrefix = '')
  592. {
  593. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  594. return $value;
  595. }
  596. public function GetSQLValues($value)
  597. {
  598. $aValues = array();
  599. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  600. return $aValues;
  601. }
  602. public function GetSQLColumns()
  603. {
  604. $aColumns = array();
  605. $aColumns[$this->Get("sql")] = $this->GetSQLCol();
  606. return $aColumns;
  607. }
  608. public function GetFilterDefinitions()
  609. {
  610. return array($this->GetCode() => new FilterFromAttribute($this));
  611. }
  612. public function GetBasicFilterOperators()
  613. {
  614. return array("="=>"equals", "!="=>"differs from");
  615. }
  616. public function GetBasicFilterLooseOperator()
  617. {
  618. return "=";
  619. }
  620. public function GetBasicFilterSQLExpr($sOpCode, $value)
  621. {
  622. $sQValue = CMDBSource::Quote($value);
  623. switch ($sOpCode)
  624. {
  625. case '!=':
  626. return $this->GetSQLExpr()." != $sQValue";
  627. break;
  628. case '=':
  629. default:
  630. return $this->GetSQLExpr()." = $sQValue";
  631. }
  632. }
  633. }
  634. /**
  635. * Base class for all kind of DB attributes, with the exception of external keys
  636. *
  637. * @package iTopORM
  638. */
  639. class AttributeDBField extends AttributeDBFieldVoid
  640. {
  641. static protected function ListExpectedParams()
  642. {
  643. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  644. }
  645. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"), null);}
  646. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  647. }
  648. /**
  649. * Map an integer column to an attribute
  650. *
  651. * @package iTopORM
  652. */
  653. class AttributeInteger extends AttributeDBField
  654. {
  655. static protected function ListExpectedParams()
  656. {
  657. return parent::ListExpectedParams();
  658. //return array_merge(parent::ListExpectedParams(), array());
  659. }
  660. public function GetEditClass() {return "String";}
  661. protected function GetSQLCol() {return "INT(11)";}
  662. public function GetValidationPattern()
  663. {
  664. return "^[0-9]+$";
  665. }
  666. public function GetBasicFilterOperators()
  667. {
  668. return array(
  669. "!="=>"differs from",
  670. "="=>"equals",
  671. ">"=>"greater (strict) than",
  672. ">="=>"greater than",
  673. "<"=>"less (strict) than",
  674. "<="=>"less than",
  675. "in"=>"in"
  676. );
  677. }
  678. public function GetBasicFilterLooseOperator()
  679. {
  680. // Unless we implement an "equals approximately..." or "same order of magnitude"
  681. return "=";
  682. }
  683. public function GetBasicFilterSQLExpr($sOpCode, $value)
  684. {
  685. $sQValue = CMDBSource::Quote($value);
  686. switch ($sOpCode)
  687. {
  688. case '!=':
  689. return $this->GetSQLExpr()." != $sQValue";
  690. break;
  691. case '>':
  692. return $this->GetSQLExpr()." > $sQValue";
  693. break;
  694. case '>=':
  695. return $this->GetSQLExpr()." >= $sQValue";
  696. break;
  697. case '<':
  698. return $this->GetSQLExpr()." < $sQValue";
  699. break;
  700. case '<=':
  701. return $this->GetSQLExpr()." <= $sQValue";
  702. break;
  703. case 'in':
  704. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  705. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  706. break;
  707. case '=':
  708. default:
  709. return $this->GetSQLExpr()." = \"$value\"";
  710. }
  711. }
  712. public function GetNullValue()
  713. {
  714. return null;
  715. }
  716. public function IsNull($proposedValue)
  717. {
  718. return is_null($proposedValue);
  719. }
  720. public function MakeRealValue($proposedValue, $oHostObj)
  721. {
  722. if (is_null($proposedValue)) return null;
  723. if ($proposedValue === '') return null; // 0 is transformed into '' !
  724. return (int)$proposedValue;
  725. }
  726. public function ScalarToSQL($value)
  727. {
  728. assert(is_numeric($value) || is_null($value));
  729. return $value; // supposed to be an int
  730. }
  731. }
  732. /**
  733. * Map a decimal value column (suitable for financial computations) to an attribute
  734. * internally in PHP such numbers are represented as string. Should you want to perform
  735. * a calculation on them, it is recommended to use the BC Math functions in order to
  736. * retain the precision
  737. *
  738. * @package iTopORM
  739. */
  740. class AttributeDecimal extends AttributeDBField
  741. {
  742. static protected function ListExpectedParams()
  743. {
  744. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  745. }
  746. public function GetEditClass() {return "String";}
  747. protected function GetSQLCol() {return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")";}
  748. public function GetValidationPattern()
  749. {
  750. $iNbDigits = $this->Get('digits');
  751. $iPrecision = $this->Get('decimals');
  752. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  753. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  754. }
  755. public function GetBasicFilterOperators()
  756. {
  757. return array(
  758. "!="=>"differs from",
  759. "="=>"equals",
  760. ">"=>"greater (strict) than",
  761. ">="=>"greater than",
  762. "<"=>"less (strict) than",
  763. "<="=>"less than",
  764. "in"=>"in"
  765. );
  766. }
  767. public function GetBasicFilterLooseOperator()
  768. {
  769. // Unless we implement an "equals approximately..." or "same order of magnitude"
  770. return "=";
  771. }
  772. public function GetBasicFilterSQLExpr($sOpCode, $value)
  773. {
  774. $sQValue = CMDBSource::Quote($value);
  775. switch ($sOpCode)
  776. {
  777. case '!=':
  778. return $this->GetSQLExpr()." != $sQValue";
  779. break;
  780. case '>':
  781. return $this->GetSQLExpr()." > $sQValue";
  782. break;
  783. case '>=':
  784. return $this->GetSQLExpr()." >= $sQValue";
  785. break;
  786. case '<':
  787. return $this->GetSQLExpr()." < $sQValue";
  788. break;
  789. case '<=':
  790. return $this->GetSQLExpr()." <= $sQValue";
  791. break;
  792. case 'in':
  793. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  794. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  795. break;
  796. case '=':
  797. default:
  798. return $this->GetSQLExpr()." = \"$value\"";
  799. }
  800. }
  801. public function GetNullValue()
  802. {
  803. return null;
  804. }
  805. public function IsNull($proposedValue)
  806. {
  807. return is_null($proposedValue);
  808. }
  809. public function MakeRealValue($proposedValue, $oHostObj)
  810. {
  811. if (is_null($proposedValue)) return null;
  812. if ($proposedValue == '') return null;
  813. return (string)$proposedValue;
  814. }
  815. public function ScalarToSQL($value)
  816. {
  817. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  818. return (string)$value; // treated as a string
  819. }
  820. }
  821. /**
  822. * Map a boolean column to an attribute
  823. *
  824. * @package iTopORM
  825. */
  826. class AttributeBoolean extends AttributeInteger
  827. {
  828. static protected function ListExpectedParams()
  829. {
  830. return parent::ListExpectedParams();
  831. //return array_merge(parent::ListExpectedParams(), array());
  832. }
  833. public function GetEditClass() {return "Integer";}
  834. protected function GetSQLCol() {return "TINYINT(1)";}
  835. public function MakeRealValue($proposedValue, $oHostObj)
  836. {
  837. if (is_null($proposedValue)) return null;
  838. if ($proposedValue === '') return null;
  839. if ((int)$proposedValue) return true;
  840. return false;
  841. }
  842. public function ScalarToSQL($value)
  843. {
  844. if ($value) return 1;
  845. return 0;
  846. }
  847. }
  848. /**
  849. * Map a varchar column (size < ?) to an attribute
  850. *
  851. * @package iTopORM
  852. */
  853. class AttributeString extends AttributeDBField
  854. {
  855. static protected function ListExpectedParams()
  856. {
  857. return parent::ListExpectedParams();
  858. //return array_merge(parent::ListExpectedParams(), array());
  859. }
  860. public function GetEditClass() {return "String";}
  861. protected function GetSQLCol() {return "VARCHAR(255)";}
  862. public function GetValidationPattern()
  863. {
  864. $sPattern = $this->GetOptional('validation_pattern', '');
  865. if (empty($sPattern))
  866. {
  867. return parent::GetValidationPattern();
  868. }
  869. else
  870. {
  871. return $sPattern;
  872. }
  873. }
  874. public function CheckFormat($value)
  875. {
  876. $sRegExp = $this->GetValidationPattern();
  877. if (empty($sRegExp))
  878. {
  879. return true;
  880. }
  881. else
  882. {
  883. $sRegExp = str_replace('/', '\\/', $sRegExp);
  884. return preg_match("/$sRegExp/", $value);
  885. }
  886. }
  887. public function GetMaxSize()
  888. {
  889. return 255;
  890. }
  891. public function GetBasicFilterOperators()
  892. {
  893. return array(
  894. "="=>"equals",
  895. "!="=>"differs from",
  896. "Like"=>"equals (no case)",
  897. "NotLike"=>"differs from (no case)",
  898. "Contains"=>"contains",
  899. "Begins with"=>"begins with",
  900. "Finishes with"=>"finishes with"
  901. );
  902. }
  903. public function GetBasicFilterLooseOperator()
  904. {
  905. return "Contains";
  906. }
  907. public function GetBasicFilterSQLExpr($sOpCode, $value)
  908. {
  909. $sQValue = CMDBSource::Quote($value);
  910. switch ($sOpCode)
  911. {
  912. case '=':
  913. case '!=':
  914. return $this->GetSQLExpr()." $sOpCode $sQValue";
  915. case 'Begins with':
  916. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  917. case 'Finishes with':
  918. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  919. case 'Contains':
  920. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  921. case 'NotLike':
  922. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  923. case 'Like':
  924. default:
  925. return $this->GetSQLExpr()." LIKE $sQValue";
  926. }
  927. }
  928. public function GetNullValue()
  929. {
  930. return '';
  931. }
  932. public function IsNull($proposedValue)
  933. {
  934. return ($proposedValue == '');
  935. }
  936. public function MakeRealValue($proposedValue, $oHostObj)
  937. {
  938. if (is_null($proposedValue)) return '';
  939. return (string)$proposedValue;
  940. }
  941. public function ScalarToSQL($value)
  942. {
  943. if (!is_string($value) && !is_null($value))
  944. {
  945. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  946. }
  947. return $value;
  948. }
  949. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  950. {
  951. $sFrom = array("\r\n", $sTextQualifier);
  952. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  953. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  954. return $sTextQualifier.$sEscaped.$sTextQualifier;
  955. }
  956. }
  957. /**
  958. * An attibute that matches an object class
  959. *
  960. * @package iTopORM
  961. */
  962. class AttributeClass extends AttributeString
  963. {
  964. static protected function ListExpectedParams()
  965. {
  966. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  967. }
  968. public function __construct($sCode, $aParams)
  969. {
  970. $this->m_sCode = $sCode;
  971. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  972. parent::__construct($sCode, $aParams);
  973. }
  974. public function GetDefaultValue()
  975. {
  976. $sDefault = parent::GetDefaultValue();
  977. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  978. {
  979. // For this kind of attribute specifying null as default value
  980. // is authorized even if null is not allowed
  981. // Pick the first one...
  982. $aClasses = $this->GetAllowedValues();
  983. $sDefault = key($aClasses);
  984. }
  985. return $sDefault;
  986. }
  987. public function GetAsHTML($sValue, $oHostObject = null)
  988. {
  989. if (empty($sValue)) return '';
  990. return MetaModel::GetName($sValue);
  991. }
  992. public function RequiresIndex()
  993. {
  994. return true;
  995. }
  996. public function GetBasicFilterLooseOperator()
  997. {
  998. return '=';
  999. }
  1000. }
  1001. /**
  1002. * An attibute that matches one of the language codes availables in the dictionnary
  1003. *
  1004. * @package iTopORM
  1005. */
  1006. class AttributeApplicationLanguage extends AttributeString
  1007. {
  1008. static protected function ListExpectedParams()
  1009. {
  1010. return parent::ListExpectedParams();
  1011. }
  1012. public function __construct($sCode, $aParams)
  1013. {
  1014. $this->m_sCode = $sCode;
  1015. $aAvailableLanguages = Dict::GetLanguages();
  1016. $aLanguageCodes = array();
  1017. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  1018. {
  1019. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  1020. }
  1021. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  1022. parent::__construct($sCode, $aParams);
  1023. }
  1024. public function RequiresIndex()
  1025. {
  1026. return true;
  1027. }
  1028. public function GetBasicFilterLooseOperator()
  1029. {
  1030. return '=';
  1031. }
  1032. }
  1033. /**
  1034. * The attribute dedicated to the finalclass automatic attribute
  1035. *
  1036. * @package iTopORM
  1037. */
  1038. class AttributeFinalClass extends AttributeString
  1039. {
  1040. public function __construct($sCode, $aParams)
  1041. {
  1042. $this->m_sCode = $sCode;
  1043. $aParams["allowed_values"] = null;
  1044. parent::__construct($sCode, $aParams);
  1045. $this->m_sValue = $this->Get("default_value");
  1046. }
  1047. public function IsWritable()
  1048. {
  1049. return false;
  1050. }
  1051. public function RequiresIndex()
  1052. {
  1053. return true;
  1054. }
  1055. public function SetFixedValue($sValue)
  1056. {
  1057. $this->m_sValue = $sValue;
  1058. }
  1059. public function GetDefaultValue()
  1060. {
  1061. return $this->m_sValue;
  1062. }
  1063. public function GetAsHTML($sValue, $oHostObject = null)
  1064. {
  1065. if (empty($sValue)) return '';
  1066. return MetaModel::GetName($sValue);
  1067. }
  1068. public function GetBasicFilterLooseOperator()
  1069. {
  1070. return '=';
  1071. }
  1072. }
  1073. /**
  1074. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  1075. *
  1076. * @package iTopORM
  1077. */
  1078. class AttributePassword extends AttributeString
  1079. {
  1080. static protected function ListExpectedParams()
  1081. {
  1082. return parent::ListExpectedParams();
  1083. //return array_merge(parent::ListExpectedParams(), array());
  1084. }
  1085. public function GetEditClass() {return "Password";}
  1086. protected function GetSQLCol() {return "VARCHAR(64)";}
  1087. public function GetMaxSize()
  1088. {
  1089. return 64;
  1090. }
  1091. public function GetFilterDefinitions()
  1092. {
  1093. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  1094. // not allowed to search on passwords!
  1095. return array();
  1096. }
  1097. public function GetAsHTML($sValue, $oHostObject = null)
  1098. {
  1099. if (strlen($sValue) == 0)
  1100. {
  1101. return '';
  1102. }
  1103. else
  1104. {
  1105. return '******';
  1106. }
  1107. }
  1108. }
  1109. /**
  1110. * Map a text column (size < 255) to an attribute that is encrypted in the database
  1111. * The encryption is based on a key set per iTop instance. Thus if you export your
  1112. * database (in SQL) to someone else without providing the key at the same time
  1113. * the encrypted fields will remain encrypted
  1114. *
  1115. * @package iTopORM
  1116. */
  1117. class AttributeEncryptedString extends AttributeString
  1118. {
  1119. static $sKey = null; // Encryption key used for all encrypted fields
  1120. public function __construct($sCode, $aParams)
  1121. {
  1122. parent::__construct($sCode, $aParams);
  1123. if (self::$sKey == null)
  1124. {
  1125. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1126. }
  1127. }
  1128. protected function GetSQLCol() {return "TINYBLOB";}
  1129. public function GetMaxSize()
  1130. {
  1131. return 255;
  1132. }
  1133. public function GetFilterDefinitions()
  1134. {
  1135. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  1136. // not allowed to search on encrypted fields !
  1137. return array();
  1138. }
  1139. public function MakeRealValue($proposedValue, $oHostObj)
  1140. {
  1141. if (is_null($proposedValue)) return null;
  1142. return (string)$proposedValue;
  1143. }
  1144. /**
  1145. * Decrypt the value when reading from the database
  1146. */
  1147. public function FromSQLToValue($aCols, $sPrefix = '')
  1148. {
  1149. $oSimpleCrypt = new SimpleCrypt();
  1150. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  1151. return $sValue;
  1152. }
  1153. /**
  1154. * Encrypt the value before storing it in the database
  1155. */
  1156. public function GetSQLValues($value)
  1157. {
  1158. $oSimpleCrypt = new SimpleCrypt();
  1159. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  1160. $aValues = array();
  1161. $aValues[$this->Get("sql")] = $encryptedValue;
  1162. return $aValues;
  1163. }
  1164. }
  1165. /**
  1166. * Map a text column (size > ?) to an attribute
  1167. *
  1168. * @package iTopORM
  1169. */
  1170. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  1171. class AttributeText extends AttributeString
  1172. {
  1173. public function GetEditClass() {return "Text";}
  1174. protected function GetSQLCol() {return "TEXT";}
  1175. public function GetMaxSize()
  1176. {
  1177. // Is there a way to know the current limitation for mysql?
  1178. // See mysql_field_len()
  1179. return 65535;
  1180. }
  1181. static public function RenderWikiHtml($sText)
  1182. {
  1183. if (preg_match_all(WIKI_OBJECT_REGEXP, $sText, $aAllMatches, PREG_SET_ORDER))
  1184. {
  1185. foreach($aAllMatches as $iPos => $aMatches)
  1186. {
  1187. $sClass = $aMatches[1];
  1188. $sName = $aMatches[2];
  1189. if (MetaModel::IsValidClass($sClass))
  1190. {
  1191. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  1192. if (is_object($oObj))
  1193. {
  1194. // Propose a std link to the object
  1195. $sText = str_replace($aMatches[0], $oObj->GetHyperlink(), $sText);
  1196. }
  1197. else
  1198. {
  1199. // Propose a std link to the object
  1200. $sClassLabel = MetaModel::GetName($sClass);
  1201. $sText = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sText);
  1202. // Later: propose a link to create a new object
  1203. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  1204. //$sText = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="./UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sText);
  1205. }
  1206. }
  1207. }
  1208. }
  1209. return $sText;
  1210. }
  1211. public function GetAsHTML($sValue, $oHostObject = null)
  1212. {
  1213. $sValue = parent::GetAsHTML($sValue);
  1214. $sValue = self::RenderWikiHtml($sValue);
  1215. return str_replace("\n", "<br>\n", $sValue);
  1216. }
  1217. public function GetEditValue($sValue)
  1218. {
  1219. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1220. {
  1221. foreach($aAllMatches as $iPos => $aMatches)
  1222. {
  1223. $sClass = $aMatches[1];
  1224. $sName = $aMatches[2];
  1225. if (MetaModel::IsValidClass($sClass))
  1226. {
  1227. $sClassLabel = MetaModel::GetName($sClass);
  1228. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  1229. }
  1230. }
  1231. }
  1232. return $sValue;
  1233. }
  1234. public function MakeRealValue($proposedValue, $oHostObj)
  1235. {
  1236. $sValue = $proposedValue;
  1237. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1238. {
  1239. foreach($aAllMatches as $iPos => $aMatches)
  1240. {
  1241. $sClassLabel = $aMatches[1];
  1242. $sName = $aMatches[2];
  1243. if (!MetaModel::IsValidClass($sClassLabel))
  1244. {
  1245. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  1246. if ($sClass)
  1247. {
  1248. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  1249. }
  1250. }
  1251. }
  1252. }
  1253. return $sValue;
  1254. }
  1255. public function GetAsXML($value, $oHostObject = null)
  1256. {
  1257. return Str::pure2xml($value);
  1258. }
  1259. public function GetWidth()
  1260. {
  1261. return $this->GetOptional('width', '');
  1262. }
  1263. public function GetHeight()
  1264. {
  1265. return $this->GetOptional('height', '');
  1266. }
  1267. }
  1268. /**
  1269. * Map a log to an attribute
  1270. *
  1271. * @package iTopORM
  1272. */
  1273. class AttributeLongText extends AttributeText
  1274. {
  1275. protected function GetSQLCol() {return "LONGTEXT";}
  1276. public function GetMaxSize()
  1277. {
  1278. // Is there a way to know the current limitation for mysql?
  1279. // See mysql_field_len()
  1280. return 65535*1024; // Limited... still 64 Mb!
  1281. }
  1282. }
  1283. /**
  1284. * An attibute that stores a case log (i.e journal)
  1285. *
  1286. * @package iTopORM
  1287. */
  1288. class AttributeCaseLog extends AttributeText
  1289. {
  1290. public function GetNullValue()
  1291. {
  1292. return '';
  1293. }
  1294. public function IsNull($proposedValue)
  1295. {
  1296. if (!($proposedValue instanceof ormCaseLog))
  1297. {
  1298. return ($proposedValue == '');
  1299. }
  1300. return ($proposedValue->GetText() == '');
  1301. }
  1302. public function ScalarToSQL($value)
  1303. {
  1304. if (!is_string($value) && !is_null($value))
  1305. {
  1306. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  1307. }
  1308. return $value;
  1309. }
  1310. public function GetEditClass() {return "CaseLog";}
  1311. public function GetEditValue($sValue) { return ''; } // New 'edit' value is always blank since it will be appended to the existing log
  1312. public function GetDefaultValue() {return new ormCaseLog();}
  1313. public function Equals($val1, $val2) {return ($val1->GetText() == $val2->GetText());}
  1314. // Facilitate things: allow the user to Set the value from a string
  1315. public function MakeRealValue($proposedValue, $oHostObj)
  1316. {
  1317. if (!($proposedValue instanceof ormCaseLog))
  1318. {
  1319. // Append the new value if an instance of the object is supplied
  1320. //
  1321. $oPreviousLog = null;
  1322. if ($oHostObj != null)
  1323. {
  1324. $oPreviousLog = $oHostObj->Get($this->GetCode());
  1325. if (!is_object($oPreviousLog))
  1326. {
  1327. $oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
  1328. }
  1329. }
  1330. if (is_object($oPreviousLog))
  1331. {
  1332. $oCaseLog = clone($oPreviousLog);
  1333. }
  1334. else
  1335. {
  1336. $oCaseLog = new ormCaseLog();
  1337. }
  1338. if (strlen($proposedValue) > 0)
  1339. {
  1340. $oCaseLog->AddLogEntry(parent::MakeRealValue($proposedValue, $oHostObj));
  1341. }
  1342. return $oCaseLog;
  1343. }
  1344. return $proposedValue;
  1345. }
  1346. public function GetSQLExpressions($sPrefix = '')
  1347. {
  1348. if ($sPrefix == '')
  1349. {
  1350. $sPrefix = $this->GetCode();
  1351. }
  1352. $aColumns = array();
  1353. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1354. $aColumns[''] = $sPrefix;
  1355. $aColumns['_index'] = $sPrefix.'_index';
  1356. return $aColumns;
  1357. }
  1358. public function FromSQLToValue($aCols, $sPrefix = '')
  1359. {
  1360. if (!isset($aCols[$sPrefix]))
  1361. {
  1362. $sAvailable = implode(', ', array_keys($aCols));
  1363. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1364. }
  1365. $sLog = $aCols[$sPrefix];
  1366. if (isset($aCols[$sPrefix.'_index']))
  1367. {
  1368. $sIndex = $aCols[$sPrefix.'_index'];
  1369. }
  1370. else
  1371. {
  1372. // For backward compatibility, allow the current state to be: 1 log, no index
  1373. $sIndex = '';
  1374. }
  1375. if (strlen($sIndex) > 0)
  1376. {
  1377. $aIndex = unserialize($sIndex);
  1378. $value = new ormCaseLog($sLog, $aIndex);
  1379. }
  1380. else
  1381. {
  1382. $value = new ormCaseLog($sLog);
  1383. }
  1384. return $value;
  1385. }
  1386. public function GetSQLValues($value)
  1387. {
  1388. if (!($value instanceOf ormCaseLog))
  1389. {
  1390. $value = new ormCaseLog('');
  1391. }
  1392. $aValues = array();
  1393. $aValues[$this->GetCode()] = $value->GetText();
  1394. $aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
  1395. return $aValues;
  1396. }
  1397. public function GetSQLColumns()
  1398. {
  1399. $aColumns = array();
  1400. $aColumns[$this->GetCode()] = 'LONGTEXT'; // 2^32 (4 Gb)
  1401. $aColumns[$this->GetCode().'_index'] = 'BLOB';
  1402. return $aColumns;
  1403. }
  1404. public function GetAsHTML($value, $oHostObject = null)
  1405. {
  1406. if ($value instanceOf ormCaseLog)
  1407. {
  1408. return $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
  1409. }
  1410. else
  1411. {
  1412. return '';
  1413. }
  1414. }
  1415. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1416. {
  1417. if ($value instanceOf ormCaseLog)
  1418. {
  1419. return parent::GetAsCSV($value->GetText(), $sSeparator, $sTextQualifier, $oHostObject);
  1420. }
  1421. else
  1422. {
  1423. return '';
  1424. }
  1425. }
  1426. public function GetAsXML($value, $oHostObject = null)
  1427. {
  1428. if ($value instanceOf ormCaseLog)
  1429. {
  1430. return parent::GetAsXML($value->GetText(), $oHostObject);
  1431. }
  1432. else
  1433. {
  1434. return '';
  1435. }
  1436. }
  1437. }
  1438. /**
  1439. * Map a text column (size > ?), containing HTML code, to an attribute
  1440. *
  1441. * @package iTopORM
  1442. */
  1443. class AttributeHTML extends AttributeText
  1444. {
  1445. public function GetEditClass() {return "HTML";}
  1446. public function GetAsHTML($sValue, $oHostObject = null)
  1447. {
  1448. return $sValue;
  1449. }
  1450. }
  1451. /**
  1452. * Specialization of a string: email
  1453. *
  1454. * @package iTopORM
  1455. */
  1456. class AttributeEmailAddress extends AttributeString
  1457. {
  1458. public function GetValidationPattern()
  1459. {
  1460. // return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  1461. return "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$";
  1462. }
  1463. public function GetAsHTML($sValue, $oHostObject = null)
  1464. {
  1465. if (empty($sValue)) return '';
  1466. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  1467. }
  1468. }
  1469. /**
  1470. * Specialization of a string: IP address
  1471. *
  1472. * @package iTopORM
  1473. */
  1474. class AttributeIPAddress extends AttributeString
  1475. {
  1476. public function GetValidationPattern()
  1477. {
  1478. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  1479. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  1480. }
  1481. }
  1482. /**
  1483. * Specialization of a string: OQL expression
  1484. *
  1485. * @package iTopORM
  1486. */
  1487. class AttributeOQL extends AttributeText
  1488. {
  1489. }
  1490. /**
  1491. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1492. *
  1493. * @package iTopORM
  1494. */
  1495. class AttributeTemplateString extends AttributeString
  1496. {
  1497. }
  1498. /**
  1499. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1500. *
  1501. * @package iTopORM
  1502. */
  1503. class AttributeTemplateText extends AttributeText
  1504. {
  1505. }
  1506. /**
  1507. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1508. *
  1509. * @package iTopORM
  1510. */
  1511. class AttributeTemplateHTML extends AttributeText
  1512. {
  1513. public function GetEditClass() {return "HTML";}
  1514. public function GetAsHTML($sValue, $oHostObject = null)
  1515. {
  1516. return $sValue;
  1517. }
  1518. }
  1519. /**
  1520. * Map a enum column to an attribute
  1521. *
  1522. * @package iTopORM
  1523. */
  1524. class AttributeEnum extends AttributeString
  1525. {
  1526. static protected function ListExpectedParams()
  1527. {
  1528. return parent::ListExpectedParams();
  1529. //return array_merge(parent::ListExpectedParams(), array());
  1530. }
  1531. public function GetEditClass() {return "String";}
  1532. protected function GetSQLCol()
  1533. {
  1534. $oValDef = $this->GetValuesDef();
  1535. if ($oValDef)
  1536. {
  1537. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  1538. }
  1539. else
  1540. {
  1541. $aValues = array();
  1542. }
  1543. if (count($aValues) > 0)
  1544. {
  1545. // The syntax used here do matters
  1546. // In particular, I had to remove unnecessary spaces to
  1547. // make sure that this string will match the field type returned by the DB
  1548. // (used to perform a comparison between the current DB format and the data model)
  1549. return "ENUM(".implode(",", $aValues).")";
  1550. }
  1551. else
  1552. {
  1553. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  1554. }
  1555. }
  1556. public function ScalarToSQL($value)
  1557. {
  1558. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  1559. // but that wasn't working for enums, because '' is NOT one of the allowed values
  1560. // that's why a null value must be forced to a real null
  1561. $value = parent::ScalarToSQL($value);
  1562. if ($this->IsNull($value))
  1563. {
  1564. return null;
  1565. }
  1566. else
  1567. {
  1568. return $value;
  1569. }
  1570. }
  1571. public function RequiresIndex()
  1572. {
  1573. return false;
  1574. }
  1575. public function GetBasicFilterOperators()
  1576. {
  1577. return parent::GetBasicFilterOperators();
  1578. }
  1579. public function GetBasicFilterLooseOperator()
  1580. {
  1581. return '=';
  1582. }
  1583. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1584. {
  1585. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1586. }
  1587. public function GetAsHTML($sValue, $oHostObject = null)
  1588. {
  1589. if (is_null($sValue))
  1590. {
  1591. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1592. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  1593. }
  1594. else
  1595. {
  1596. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1597. }
  1598. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', $sValue);
  1599. // later, we could imagine a detailed description in the title
  1600. return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  1601. }
  1602. public function GetEditValue($sValue)
  1603. {
  1604. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1605. return $sLabel;
  1606. }
  1607. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1608. {
  1609. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  1610. if (is_null($aRawValues)) return null;
  1611. $aLocalizedValues = array();
  1612. foreach ($aRawValues as $sKey => $sValue)
  1613. {
  1614. $aLocalizedValues[$sKey] = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sKey, $sKey);
  1615. }
  1616. return $aLocalizedValues;
  1617. }
  1618. /**
  1619. * Processes the input value to align it with the values supported
  1620. * by this type of attribute. In this case: turns empty strings into nulls
  1621. * @param mixed $proposedValue The value to be set for the attribute
  1622. * @return mixed The actual value that will be set
  1623. */
  1624. public function MakeRealValue($proposedValue, $oHostObj)
  1625. {
  1626. if ($proposedValue == '') return null;
  1627. return parent::MakeRealValue($proposedValue, $oHostObj);
  1628. }
  1629. }
  1630. /**
  1631. * Map a date+time column to an attribute
  1632. *
  1633. * @package iTopORM
  1634. */
  1635. class AttributeDateTime extends AttributeDBField
  1636. {
  1637. static protected function GetDateFormat()
  1638. {
  1639. return "Y-m-d H:i:s";
  1640. }
  1641. static protected function ListExpectedParams()
  1642. {
  1643. return parent::ListExpectedParams();
  1644. //return array_merge(parent::ListExpectedParams(), array());
  1645. }
  1646. public function GetEditClass() {return "DateTime";}
  1647. protected function GetSQLCol() {return "TIMESTAMP";}
  1648. public static function GetAsUnixSeconds($value)
  1649. {
  1650. $oDeadlineDateTime = new DateTime($value);
  1651. $iUnixSeconds = $oDeadlineDateTime->format('U');
  1652. return $iUnixSeconds;
  1653. }
  1654. // #@# THIS HAS TO REVISED
  1655. // Having null not allowed was interpreted by mySQL
  1656. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  1657. // Then, on each update of the record, the field was modified.
  1658. // We will have to specify the default value if we want to restore this option
  1659. // In fact, we could also have more verbs dedicated to the DB:
  1660. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  1661. public function IsNullAllowed() {return true;}
  1662. public function GetDefaultValue()
  1663. {
  1664. $default = parent::GetDefaultValue();
  1665. if (!parent::IsNullAllowed())
  1666. {
  1667. if (empty($default))
  1668. {
  1669. $default = date(self::GetDateFormat());
  1670. }
  1671. }
  1672. return $default;
  1673. }
  1674. // END OF THE WORKAROUND
  1675. ///////////////////////////////////////////////////////////////
  1676. public function GetValidationPattern()
  1677. {
  1678. 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$";
  1679. }
  1680. public function GetBasicFilterOperators()
  1681. {
  1682. return array(
  1683. "="=>"equals",
  1684. "!="=>"differs from",
  1685. "<"=>"before",
  1686. "<="=>"before",
  1687. ">"=>"after (strictly)",
  1688. ">="=>"after",
  1689. "SameDay"=>"same day (strip time)",
  1690. "SameMonth"=>"same year/month",
  1691. "SameYear"=>"same year",
  1692. "Today"=>"today",
  1693. ">|"=>"after today + N days",
  1694. "<|"=>"before today + N days",
  1695. "=|"=>"equals today + N days",
  1696. );
  1697. }
  1698. public function GetBasicFilterLooseOperator()
  1699. {
  1700. // Unless we implement a "same xxx, depending on given precision" !
  1701. return "=";
  1702. }
  1703. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1704. {
  1705. $sQValue = CMDBSource::Quote($value);
  1706. switch ($sOpCode)
  1707. {
  1708. case '=':
  1709. case '!=':
  1710. case '<':
  1711. case '<=':
  1712. case '>':
  1713. case '>=':
  1714. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1715. case 'SameDay':
  1716. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  1717. case 'SameMonth':
  1718. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  1719. case 'SameYear':
  1720. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  1721. case 'Today':
  1722. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  1723. case '>|':
  1724. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1725. case '<|':
  1726. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1727. case '=|':
  1728. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1729. default:
  1730. return $this->GetSQLExpr()." = $sQValue";
  1731. }
  1732. }
  1733. public function MakeRealValue($proposedValue, $oHostObj)
  1734. {
  1735. if (is_null($proposedValue))
  1736. {
  1737. return null;
  1738. }
  1739. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  1740. {
  1741. return null;
  1742. }
  1743. if (!is_numeric($proposedValue))
  1744. {
  1745. return $proposedValue;
  1746. }
  1747. return date(self::GetDateFormat(), $proposedValue);
  1748. }
  1749. public function ScalarToSQL($value)
  1750. {
  1751. if (is_null($value))
  1752. {
  1753. return null;
  1754. }
  1755. elseif (empty($value))
  1756. {
  1757. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  1758. return '0000-00-00 00:00:00';
  1759. }
  1760. return $value;
  1761. }
  1762. public function GetAsHTML($value, $oHostObject = null)
  1763. {
  1764. return Str::pure2html($value);
  1765. }
  1766. public function GetAsXML($value, $oHostObject = null)
  1767. {
  1768. return Str::pure2xml($value);
  1769. }
  1770. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1771. {
  1772. $sFrom = array("\r\n", $sTextQualifier);
  1773. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1774. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1775. return '"'.$sEscaped.'"';
  1776. }
  1777. /**
  1778. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  1779. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  1780. * does nothing special, and just calls the default (loose) operator
  1781. * @param string $sSearchText The search string to analyze for smart patterns
  1782. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  1783. * @param Hash $aParams Values of the query parameters
  1784. * @return Expression The search condition to be added (AND) to the current search
  1785. */
  1786. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  1787. {
  1788. // Possible smart patterns
  1789. $aPatterns = array(
  1790. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  1791. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  1792. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  1793. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  1794. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  1795. );
  1796. $sPatternFound = '';
  1797. $aMatches = array();
  1798. foreach($aPatterns as $sPatName => $sPattern)
  1799. {
  1800. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  1801. {
  1802. $sPatternFound = $sPatName;
  1803. break;
  1804. }
  1805. }
  1806. switch($sPatternFound)
  1807. {
  1808. case 'between':
  1809. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  1810. $oRightExpr = new VariableExpression($sParamName1);
  1811. $aParams[$sParamName1] = $aMatches[1];
  1812. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  1813. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  1814. $oRightExpr = new VariableExpression($sParamName2);
  1815. $sOperator = $this->GetBasicFilterLooseOperator();
  1816. $aParams[$sParamName2] = $aMatches[2];
  1817. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  1818. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  1819. break;
  1820. case 'greater than':
  1821. case 'greater than or equal':
  1822. case 'less than':
  1823. case 'less than or equal':
  1824. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  1825. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  1826. $oRightExpr = new VariableExpression($sParamName);
  1827. $aParams[$sParamName] = $aMatches[1];
  1828. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  1829. break;
  1830. default:
  1831. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  1832. }
  1833. return $oNewCondition;
  1834. }
  1835. }
  1836. /**
  1837. * Store a duration as a number of seconds
  1838. *
  1839. * @package iTopORM
  1840. */
  1841. class AttributeDuration extends AttributeInteger
  1842. {
  1843. public function GetEditClass() {return "Duration";}
  1844. protected function GetSQLCol() {return "INT(11) UNSIGNED";}
  1845. public function GetNullValue() {return '0';}
  1846. public function GetDefaultValue()
  1847. {
  1848. return 0;
  1849. }
  1850. public function MakeRealValue($proposedValue, $oHostObj)
  1851. {
  1852. if (is_null($proposedValue)) return null;
  1853. if (!is_numeric($proposedValue)) return null;
  1854. if ( ((int)$proposedValue) < 0) return null;
  1855. return (int)$proposedValue;
  1856. }
  1857. public function ScalarToSQL($value)
  1858. {
  1859. if (is_null($value))
  1860. {
  1861. return null;
  1862. }
  1863. return $value;
  1864. }
  1865. public function GetAsHTML($value, $oHostObject = null)
  1866. {
  1867. return Str::pure2html(self::FormatDuration($value));
  1868. }
  1869. static function FormatDuration($duration)
  1870. {
  1871. $aDuration = self::SplitDuration($duration);
  1872. $sResult = '';
  1873. if ($duration < 60)
  1874. {
  1875. // Less than 1 min
  1876. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  1877. }
  1878. else if ($duration < 3600)
  1879. {
  1880. // less than 1 hour, display it in minutes/seconds
  1881. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  1882. }
  1883. else if ($duration < 86400)
  1884. {
  1885. // Less than 1 day, display it in hours/minutes/seconds
  1886. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  1887. }
  1888. else
  1889. {
  1890. // more than 1 day, display it in days/hours/minutes/seconds
  1891. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  1892. }
  1893. return $sResult;
  1894. }
  1895. static function SplitDuration($duration)
  1896. {
  1897. $days = floor($duration / 86400);
  1898. $hours = floor(($duration - (86400*$days)) / 3600);
  1899. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  1900. $seconds = ($duration % 60); // modulo
  1901. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  1902. }
  1903. }
  1904. /**
  1905. * Map a date+time column to an attribute
  1906. *
  1907. * @package iTopORM
  1908. */
  1909. class AttributeDate extends AttributeDateTime
  1910. {
  1911. const MYDATEFORMAT = "Y-m-d";
  1912. static protected function GetDateFormat()
  1913. {
  1914. return "Y-m-d";
  1915. }
  1916. static protected function ListExpectedParams()
  1917. {
  1918. return parent::ListExpectedParams();
  1919. //return array_merge(parent::ListExpectedParams(), array());
  1920. }
  1921. public function GetEditClass() {return "Date";}
  1922. protected function GetSQLCol() {return "DATE";}
  1923. public function GetValidationPattern()
  1924. {
  1925. 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)))$";
  1926. }
  1927. }
  1928. /**
  1929. * A dead line stored as a date & time
  1930. * The only difference with the DateTime attribute is the display:
  1931. * relative to the current time
  1932. */
  1933. class AttributeDeadline extends AttributeDateTime
  1934. {
  1935. public function GetAsHTML($value, $oHostObject = null)
  1936. {
  1937. $sResult = '';
  1938. if ($value !== null)
  1939. {
  1940. $value = AttributeDateTime::GetAsUnixSeconds($value);
  1941. $difference = $value - time();
  1942. if ($difference >= 0)
  1943. {
  1944. $sResult = self::FormatDuration($difference);
  1945. }
  1946. else
  1947. {
  1948. $sResult = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  1949. }
  1950. }
  1951. return $sResult;
  1952. }
  1953. static function FormatDuration($duration)
  1954. {
  1955. $days = floor($duration / 86400);
  1956. $hours = floor(($duration - (86400*$days)) / 3600);
  1957. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  1958. $sResult = '';
  1959. if ($duration < 60)
  1960. {
  1961. // Less than 1 min
  1962. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  1963. }
  1964. else if ($duration < 3600)
  1965. {
  1966. // less than 1 hour, display it in minutes
  1967. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  1968. }
  1969. else if ($duration < 86400)
  1970. {
  1971. // Less that 1 day, display it in hours/minutes
  1972. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  1973. }
  1974. else
  1975. {
  1976. // Less that 1 day, display it in hours/minutes
  1977. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  1978. }
  1979. return $sResult;
  1980. }
  1981. }
  1982. /**
  1983. * Map a foreign key to an attribute
  1984. * AttributeExternalKey and AttributeExternalField may be an external key
  1985. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  1986. * where an AttributeExternalField corresponds to a column into another table (class)
  1987. *
  1988. * @package iTopORM
  1989. */
  1990. class AttributeExternalKey extends AttributeDBFieldVoid
  1991. {
  1992. static protected function ListExpectedParams()
  1993. {
  1994. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  1995. }
  1996. public function GetEditClass() {return "ExtKey";}
  1997. protected function GetSQLCol() {return "INT(11)";}
  1998. public function RequiresIndex()
  1999. {
  2000. return true;
  2001. }
  2002. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  2003. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  2004. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2005. public function GetKeyAttCode() {return $this->GetCode();}
  2006. public function GetDefaultValue() {return 0;}
  2007. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  2008. public function GetBasicFilterOperators()
  2009. {
  2010. return parent::GetBasicFilterOperators();
  2011. }
  2012. public function GetBasicFilterLooseOperator()
  2013. {
  2014. return parent::GetBasicFilterLooseOperator();
  2015. }
  2016. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2017. {
  2018. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2019. }
  2020. // overloaded here so that an ext key always have the answer to
  2021. // "what are your possible values?"
  2022. public function GetValuesDef()
  2023. {
  2024. $oValSetDef = $this->Get("allowed_values");
  2025. if (!$oValSetDef)
  2026. {
  2027. // Let's propose every existing value
  2028. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2029. }
  2030. return $oValSetDef;
  2031. }
  2032. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2033. {
  2034. try
  2035. {
  2036. return parent::GetAllowedValues($aArgs, $sContains);
  2037. }
  2038. catch (MissingQueryArgument $e)
  2039. {
  2040. // Some required arguments could not be found, enlarge to any existing value
  2041. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2042. return $oValSetDef->GetValues($aArgs, $sContains);
  2043. }
  2044. }
  2045. public function GetDeletionPropagationOption()
  2046. {
  2047. return $this->Get("on_target_delete");
  2048. }
  2049. public function GetNullValue()
  2050. {
  2051. return 0;
  2052. }
  2053. public function IsNull($proposedValue)
  2054. {
  2055. return ($proposedValue == 0);
  2056. }
  2057. public function MakeRealValue($proposedValue, $oHostObj)
  2058. {
  2059. if (is_null($proposedValue)) return 0;
  2060. if ($proposedValue === '') return 0;
  2061. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  2062. return (int)$proposedValue;
  2063. }
  2064. public function GetMaximumComboLength()
  2065. {
  2066. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  2067. }
  2068. public function GetMinAutoCompleteChars()
  2069. {
  2070. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  2071. }
  2072. public function AllowTargetCreation()
  2073. {
  2074. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  2075. }
  2076. }
  2077. /**
  2078. * An attribute which corresponds to an external key (direct or indirect)
  2079. *
  2080. * @package iTopORM
  2081. */
  2082. class AttributeExternalField extends AttributeDefinition
  2083. {
  2084. static protected function ListExpectedParams()
  2085. {
  2086. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  2087. }
  2088. public function GetEditClass() {return "ExtField";}
  2089. protected function GetSQLCol()
  2090. {
  2091. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  2092. $oExtAttDef = $this->GetExtAttDef();
  2093. return $oExtAttDef->GetSQLCol();
  2094. }
  2095. public function GetSQLExpressions($sPrefix = '')
  2096. {
  2097. if ($sPrefix == '')
  2098. {
  2099. return array('' => $this->GetCode());
  2100. }
  2101. else
  2102. {
  2103. return $sPrefix;
  2104. }
  2105. }
  2106. public function GetLabel()
  2107. {
  2108. $oRemoteAtt = $this->GetExtAttDef();
  2109. $sDefault = $oRemoteAtt->GetLabel();
  2110. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $sDefault);
  2111. }
  2112. public function GetDescription()
  2113. {
  2114. $oRemoteAtt = $this->GetExtAttDef();
  2115. $sDefault = $oRemoteAtt->GetDescription();
  2116. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', $sDefault);
  2117. }
  2118. public function GetHelpOnEdition()
  2119. {
  2120. $oRemoteAtt = $this->GetExtAttDef();
  2121. $sDefault = $oRemoteAtt->GetHelpOnEdition();
  2122. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', $sDefault);
  2123. }
  2124. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  2125. {
  2126. switch($iType)
  2127. {
  2128. case EXTKEY_ABSOLUTE:
  2129. // see further
  2130. $oRemoteAtt = $this->GetExtAttDef();
  2131. return $oRemoteAtt->IsExternalKey($iType);
  2132. case EXTKEY_RELATIVE:
  2133. return false;
  2134. default:
  2135. throw new CoreException("Unexpected value for argument iType: '$iType'");
  2136. }
  2137. }
  2138. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  2139. {
  2140. return $this->GetKeyAttDef($iType)->GetTargetClass();
  2141. }
  2142. public function IsExternalField() {return true;}
  2143. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  2144. public function GetExtAttCode() {return $this->Get("target_attcode");}
  2145. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  2146. {
  2147. switch($iType)
  2148. {
  2149. case EXTKEY_ABSOLUTE:
  2150. // see further
  2151. $oRemoteAtt = $this->GetExtAttDef();
  2152. if ($oRemoteAtt->IsExternalField())
  2153. {
  2154. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  2155. }
  2156. else if ($oRemoteAtt->IsExternalKey())
  2157. {
  2158. return $oRemoteAtt;
  2159. }
  2160. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  2161. case EXTKEY_RELATIVE:
  2162. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  2163. default:
  2164. throw new CoreException("Unexpected value for argument iType: '$iType'");
  2165. }
  2166. }
  2167. public function GetExtAttDef()
  2168. {
  2169. $oKeyAttDef = $this->GetKeyAttDef();
  2170. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->Get("targetclass"), $this->Get("target_attcode"));
  2171. 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"));
  2172. return $oExtAttDef;
  2173. }
  2174. public function GetSQLExpr()
  2175. {
  2176. $oExtAttDef = $this->GetExtAttDef();
  2177. return $oExtAttDef->GetSQLExpr();
  2178. }
  2179. public function GetDefaultValue()
  2180. {
  2181. $oExtAttDef = $this->GetExtAttDef();
  2182. return $oExtAttDef->GetDefaultValue();
  2183. }
  2184. public function IsNullAllowed()
  2185. {
  2186. $oExtAttDef = $this->GetExtAttDef();
  2187. return $oExtAttDef->IsNullAllowed();
  2188. }
  2189. public function IsScalar()
  2190. {
  2191. $oExtAttDef = $this->GetExtAttDef();
  2192. return $oExtAttDef->IsScalar();
  2193. }
  2194. public function GetFilterDefinitions()
  2195. {
  2196. return array($this->GetCode() => new FilterFromAttribute($this));
  2197. }
  2198. public function GetBasicFilterOperators()
  2199. {
  2200. $oExtAttDef = $this->GetExtAttDef();
  2201. return $oExtAttDef->GetBasicFilterOperators();
  2202. }
  2203. public function GetBasicFilterLooseOperator()
  2204. {
  2205. $oExtAttDef = $this->GetExtAttDef();
  2206. return $oExtAttDef->GetBasicFilterLooseOperator();
  2207. }
  2208. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2209. {
  2210. $oExtAttDef = $this->GetExtAttDef();
  2211. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  2212. }
  2213. public function GetNullValue()
  2214. {
  2215. $oExtAttDef = $this->GetExtAttDef();
  2216. return $oExtAttDef->GetNullValue();
  2217. }
  2218. public function IsNull($proposedValue)
  2219. {
  2220. $oExtAttDef = $this->GetExtAttDef();
  2221. return $oExtAttDef->IsNull($proposedValue);
  2222. }
  2223. public function MakeRealValue($proposedValue, $oHostObj)
  2224. {
  2225. $oExtAttDef = $this->GetExtAttDef();
  2226. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  2227. }
  2228. public function ScalarToSQL($value)
  2229. {
  2230. // This one could be used in case of filtering only
  2231. $oExtAttDef = $this->GetExtAttDef();
  2232. return $oExtAttDef->ScalarToSQL($value);
  2233. }
  2234. // Do not overload GetSQLExpression here because this is handled in the joins
  2235. //public function GetSQLExpressions($sPrefix = '') {return array();}
  2236. // Here, we get the data...
  2237. public function FromSQLToValue($aCols, $sPrefix = '')
  2238. {
  2239. $oExtAttDef = $this->GetExtAttDef();
  2240. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  2241. }
  2242. public function GetAsHTML($value, $oHostObject = null)
  2243. {
  2244. $oExtAttDef = $this->GetExtAttDef();
  2245. return $oExtAttDef->GetAsHTML($value);
  2246. }
  2247. public function GetAsXML($value, $oHostObject = null)
  2248. {
  2249. $oExtAttDef = $this->GetExtAttDef();
  2250. return $oExtAttDef->GetAsXML($value);
  2251. }
  2252. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null)
  2253. {
  2254. $oExtAttDef = $this->GetExtAttDef();
  2255. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  2256. }
  2257. }
  2258. /**
  2259. * Map a varchar column to an URL (formats the ouput in HMTL)
  2260. *
  2261. * @package iTopORM
  2262. */
  2263. class AttributeURL extends AttributeString
  2264. {
  2265. static protected function ListExpectedParams()
  2266. {
  2267. //return parent::ListExpectedParams();
  2268. return array_merge(parent::ListExpectedParams(), array("target"));
  2269. }
  2270. public function GetEditClass() {return "String";}
  2271. public function GetAsHTML($sValue, $oHostObject = null)
  2272. {
  2273. $sTarget = $this->Get("target");
  2274. if (empty($sTarget)) $sTarget = "_blank";
  2275. $sLabel = Str::pure2html($sValue);
  2276. if (strlen($sLabel) > 40)
  2277. {
  2278. // Truncate the length to about 40 characters, by removing the middle
  2279. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  2280. }
  2281. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  2282. }
  2283. public function GetValidationPattern()
  2284. {
  2285. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  2286. }
  2287. }
  2288. /**
  2289. * A blob is an ormDocument, it is stored as several columns in the database
  2290. *
  2291. * @package iTopORM
  2292. */
  2293. class AttributeBlob extends AttributeDefinition
  2294. {
  2295. static protected function ListExpectedParams()
  2296. {
  2297. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  2298. }
  2299. public function GetEditClass() {return "Document";}
  2300. public function IsDirectField() {return true;}
  2301. public function IsScalar() {return true;}
  2302. public function IsWritable() {return true;}
  2303. public function GetDefaultValue() {return "";}
  2304. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2305. // Facilitate things: allow the user to Set the value from a string
  2306. public function MakeRealValue($proposedValue, $oHostObj)
  2307. {
  2308. if (!is_object($proposedValue))
  2309. {
  2310. return new ormDocument($proposedValue, 'text/plain');
  2311. }
  2312. return $proposedValue;
  2313. }
  2314. public function GetSQLExpressions($sPrefix = '')
  2315. {
  2316. if ($sPrefix == '')
  2317. {
  2318. $sPrefix = $this->GetCode();
  2319. }
  2320. $aColumns = array();
  2321. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2322. $aColumns[''] = $sPrefix.'_mimetype';
  2323. $aColumns['_data'] = $sPrefix.'_data';
  2324. $aColumns['_filename'] = $sPrefix.'_filename';
  2325. return $aColumns;
  2326. }
  2327. public function FromSQLToValue($aCols, $sPrefix = '')
  2328. {
  2329. if (!isset($aCols[$sPrefix]))
  2330. {
  2331. $sAvailable = implode(', ', array_keys($aCols));
  2332. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2333. }
  2334. $sMimeType = $aCols[$sPrefix];
  2335. if (!isset($aCols[$sPrefix.'_data']))
  2336. {
  2337. $sAvailable = implode(', ', array_keys($aCols));
  2338. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  2339. }
  2340. $data = $aCols[$sPrefix.'_data'];
  2341. if (!isset($aCols[$sPrefix.'_filename']))
  2342. {
  2343. $sAvailable = implode(', ', array_keys($aCols));
  2344. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  2345. }
  2346. $sFileName = $aCols[$sPrefix.'_filename'];
  2347. $value = new ormDocument($data, $sMimeType, $sFileName);
  2348. return $value;
  2349. }
  2350. public function GetSQLValues($value)
  2351. {
  2352. // #@# Optimization: do not load blobs anytime
  2353. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2354. // using memory in case a temporary table has to be created
  2355. // (temporary tables created on disk)
  2356. // We will have to remove the blobs from the list of attributes when doing the select
  2357. // then the use of Get() should finalize the load
  2358. if ($value instanceOf ormDocument)
  2359. {
  2360. $aValues = array();
  2361. $aValues[$this->GetCode().'_data'] = $value->GetData();
  2362. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  2363. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  2364. }
  2365. else
  2366. {
  2367. $aValues = array();
  2368. $aValues[$this->GetCode().'_data'] = '';
  2369. $aValues[$this->GetCode().'_mimetype'] = '';
  2370. $aValues[$this->GetCode().'_filename'] = '';
  2371. }
  2372. return $aValues;
  2373. }
  2374. public function GetSQLColumns()
  2375. {
  2376. $aColumns = array();
  2377. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  2378. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  2379. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  2380. return $aColumns;
  2381. }
  2382. public function GetFilterDefinitions()
  2383. {
  2384. return array();
  2385. // still not working... see later...
  2386. return array(
  2387. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  2388. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  2389. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  2390. );
  2391. }
  2392. public function GetBasicFilterOperators()
  2393. {
  2394. return array();
  2395. }
  2396. public function GetBasicFilterLooseOperator()
  2397. {
  2398. return '=';
  2399. }
  2400. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2401. {
  2402. return 'true';
  2403. }
  2404. public function GetAsHTML($value, $oHostObject = null)
  2405. {
  2406. if (is_object($value))
  2407. {
  2408. return $value->GetAsHTML();
  2409. }
  2410. }
  2411. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2412. {
  2413. return ''; // Not exportable in CSV !
  2414. }
  2415. public function GetAsXML($value, $oHostObject = null)
  2416. {
  2417. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  2418. }
  2419. }
  2420. /**
  2421. * One way encrypted (hashed) password
  2422. */
  2423. class AttributeOneWayPassword extends AttributeDefinition
  2424. {
  2425. static protected function ListExpectedParams()
  2426. {
  2427. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  2428. }
  2429. public function GetEditClass() {return "One Way Password";}
  2430. public function IsDirectField() {return true;}
  2431. public function IsScalar() {return true;}
  2432. public function IsWritable() {return true;}
  2433. public function GetDefaultValue() {return "";}
  2434. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2435. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  2436. public function MakeRealValue($proposedValue, $oHostObj)
  2437. {
  2438. $oPassword = $proposedValue;
  2439. if (!is_object($oPassword))
  2440. {
  2441. $oPassword = new ormPassword('', '');
  2442. $oPassword->SetPassword($proposedValue);
  2443. }
  2444. return $oPassword;
  2445. }
  2446. public function GetSQLExpressions($sPrefix = '')
  2447. {
  2448. if ($sPrefix == '')
  2449. {
  2450. $sPrefix = $this->GetCode();
  2451. }
  2452. $aColumns = array();
  2453. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2454. $aColumns[''] = $sPrefix.'_hash';
  2455. $aColumns['_salt'] = $sPrefix.'_salt';
  2456. return $aColumns;
  2457. }
  2458. public function FromSQLToValue($aCols, $sPrefix = '')
  2459. {
  2460. if (!isset($aCols[$sPrefix]))
  2461. {
  2462. $sAvailable = implode(', ', array_keys($aCols));
  2463. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2464. }
  2465. $hashed = $aCols[$sPrefix];
  2466. if (!isset($aCols[$sPrefix.'_salt']))
  2467. {
  2468. $sAvailable = implode(', ', array_keys($aCols));
  2469. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  2470. }
  2471. $sSalt = $aCols[$sPrefix.'_salt'];
  2472. $value = new ormPassword($hashed, $sSalt);
  2473. return $value;
  2474. }
  2475. public function GetSQLValues($value)
  2476. {
  2477. // #@# Optimization: do not load blobs anytime
  2478. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2479. // using memory in case a temporary table has to be created
  2480. // (temporary tables created on disk)
  2481. // We will have to remove the blobs from the list of attributes when doing the select
  2482. // then the use of Get() should finalize the load
  2483. if ($value instanceOf ormPassword)
  2484. {
  2485. $aValues = array();
  2486. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  2487. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  2488. }
  2489. else
  2490. {
  2491. $aValues = array();
  2492. $aValues[$this->GetCode().'_hash'] = '';
  2493. $aValues[$this->GetCode().'_salt'] = '';
  2494. }
  2495. return $aValues;
  2496. }
  2497. public function GetSQLColumns()
  2498. {
  2499. $aColumns = array();
  2500. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  2501. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  2502. return $aColumns;
  2503. }
  2504. public function GetImportColumns()
  2505. {
  2506. $aColumns = array();
  2507. $aColumns[$this->GetCode()] = 'TINYTEXT';
  2508. return $aColumns;
  2509. }
  2510. public function FromImportToValue($aCols, $sPrefix = '')
  2511. {
  2512. if (!isset($aCols[$sPrefix]))
  2513. {
  2514. $sAvailable = implode(', ', array_keys($aCols));
  2515. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2516. }
  2517. $sClearPwd = $aCols[$sPrefix];
  2518. $oPassword = new ormPassword('', '');
  2519. $oPassword->SetPassword($sClearPwd);
  2520. return $oPassword;
  2521. }
  2522. public function GetFilterDefinitions()
  2523. {
  2524. return array();
  2525. // still not working... see later...
  2526. }
  2527. public function GetBasicFilterOperators()
  2528. {
  2529. return array();
  2530. }
  2531. public function GetBasicFilterLooseOperator()
  2532. {
  2533. return '=';
  2534. }
  2535. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2536. {
  2537. return 'true';
  2538. }
  2539. public function GetAsHTML($value, $oHostObject = null)
  2540. {
  2541. if (is_object($value))
  2542. {
  2543. return $value->GetAsHTML();
  2544. }
  2545. }
  2546. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2547. {
  2548. return ''; // Not exportable in CSV
  2549. }
  2550. public function GetAsXML($value, $oHostObject = null)
  2551. {
  2552. return ''; // Not exportable in XML
  2553. }
  2554. }
  2555. // Indexed array having two dimensions
  2556. class AttributeTable extends AttributeText
  2557. {
  2558. public function GetEditClass() {return "Text";}
  2559. protected function GetSQLCol() {return "TEXT";}
  2560. public function GetMaxSize()
  2561. {
  2562. return null;
  2563. }
  2564. // Facilitate things: allow the user to Set the value from a string
  2565. public function MakeRealValue($proposedValue, $oHostObj)
  2566. {
  2567. if (!is_array($proposedValue))
  2568. {
  2569. return array(0 => array(0 => $proposedValue));
  2570. }
  2571. return $proposedValue;
  2572. }
  2573. public function FromSQLToValue($aCols, $sPrefix = '')
  2574. {
  2575. try
  2576. {
  2577. $value = @unserialize($aCols[$sPrefix.'']);
  2578. if ($value === false)
  2579. {
  2580. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  2581. }
  2582. }
  2583. catch(Exception $e)
  2584. {
  2585. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  2586. }
  2587. return $value;
  2588. }
  2589. public function GetSQLValues($value)
  2590. {
  2591. $aValues = array();
  2592. $aValues[$this->Get("sql")] = serialize($value);
  2593. return $aValues;
  2594. }
  2595. public function GetAsHTML($value, $oHostObject = null)
  2596. {
  2597. if (!is_array($value))
  2598. {
  2599. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2600. }
  2601. if (count($value) == 0)
  2602. {
  2603. return "";
  2604. }
  2605. $sRes = "<TABLE class=\"listResults\">";
  2606. $sRes .= "<TBODY>";
  2607. foreach($value as $iRow => $aRawData)
  2608. {
  2609. $sRes .= "<TR>";
  2610. foreach ($aRawData as $iCol => $cell)
  2611. {
  2612. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  2613. $sRes .= "<TD>$sCell</TD>";
  2614. }
  2615. $sRes .= "</TR>";
  2616. }
  2617. $sRes .= "</TBODY>";
  2618. $sRes .= "</TABLE>";
  2619. return $sRes;
  2620. }
  2621. }
  2622. // The PHP value is a hash array, it is stored as a TEXT column
  2623. class AttributePropertySet extends AttributeTable
  2624. {
  2625. public function GetEditClass() {return "Text";}
  2626. protected function GetSQLCol() {return "TEXT";}
  2627. // Facilitate things: allow the user to Set the value from a string
  2628. public function MakeRealValue($proposedValue, $oHostObj)
  2629. {
  2630. if (!is_array($proposedValue))
  2631. {
  2632. return array('?' => (string)$proposedValue);
  2633. }
  2634. return $proposedValue;
  2635. }
  2636. public function GetAsHTML($value, $oHostObject = null)
  2637. {
  2638. if (!is_array($value))
  2639. {
  2640. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2641. }
  2642. if (count($value) == 0)
  2643. {
  2644. return "";
  2645. }
  2646. $sRes = "<TABLE class=\"listResults\">";
  2647. $sRes .= "<TBODY>";
  2648. foreach($value as $sProperty => $sValue)
  2649. {
  2650. $sRes .= "<TR>";
  2651. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  2652. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  2653. $sRes .= "</TR>";
  2654. }
  2655. $sRes .= "</TBODY>";
  2656. $sRes .= "</TABLE>";
  2657. return $sRes;
  2658. }
  2659. }
  2660. /**
  2661. * The attribute dedicated to the friendly name automatic attribute (not written)
  2662. *
  2663. * @package iTopORM
  2664. */
  2665. class AttributeComputedFieldVoid extends AttributeDefinition
  2666. {
  2667. static protected function ListExpectedParams()
  2668. {
  2669. return array_merge(parent::ListExpectedParams(), array());
  2670. }
  2671. public function GetEditClass() {return "";}
  2672. public function GetValuesDef() {return null;}
  2673. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  2674. public function IsDirectField() {return true;}
  2675. public function IsScalar() {return true;}
  2676. public function IsWritable() {return false;}
  2677. public function GetSQLExpr() {return null;}
  2678. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  2679. public function IsNullAllowed() {return false;}
  2680. //
  2681. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  2682. public function GetSQLExpressions($sPrefix = '')
  2683. {
  2684. if ($sPrefix == '')
  2685. {
  2686. $sPrefix = $this->GetCode();
  2687. }
  2688. return array('' => $sPrefix);
  2689. }
  2690. public function FromSQLToValue($aCols, $sPrefix = '')
  2691. {
  2692. return null;
  2693. }
  2694. public function GetSQLValues($value)
  2695. {
  2696. return array();
  2697. }
  2698. public function GetSQLColumns()
  2699. {
  2700. return array();
  2701. }
  2702. public function GetFilterDefinitions()
  2703. {
  2704. return array($this->GetCode() => new FilterFromAttribute($this));
  2705. }
  2706. public function GetBasicFilterOperators()
  2707. {
  2708. return array();
  2709. }
  2710. public function GetBasicFilterLooseOperator()
  2711. {
  2712. return "=";
  2713. }
  2714. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2715. {
  2716. $sQValue = CMDBSource::Quote($value);
  2717. switch ($sOpCode)
  2718. {
  2719. case '!=':
  2720. return $this->GetSQLExpr()." != $sQValue";
  2721. break;
  2722. case '=':
  2723. default:
  2724. return $this->GetSQLExpr()." = $sQValue";
  2725. }
  2726. }
  2727. }
  2728. /**
  2729. * The attribute dedicated to the friendly name automatic attribute (not written)
  2730. *
  2731. * @package iTopORM
  2732. */
  2733. class AttributeFriendlyName extends AttributeComputedFieldVoid
  2734. {
  2735. public function __construct($sCode, $sExtKeyAttCode)
  2736. {
  2737. $this->m_sCode = $sCode;
  2738. $aParams = array();
  2739. // $aParams["is_null_allowed"] = false,
  2740. $aParams["default_value"] = '';
  2741. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  2742. parent::__construct($sCode, $aParams);
  2743. $this->m_sValue = $this->Get("default_value");
  2744. }
  2745. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  2746. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  2747. protected function GetSQLCol() {return "";}
  2748. public function FromSQLToValue($aCols, $sPrefix = '')
  2749. {
  2750. $sValue = $aCols[$sPrefix];
  2751. return $sValue;
  2752. }
  2753. /**
  2754. * Encrypt the value before storing it in the database
  2755. */
  2756. public function GetSQLValues($value)
  2757. {
  2758. return array();
  2759. }
  2760. public function IsWritable()
  2761. {
  2762. return false;
  2763. }
  2764. public function IsDirectField()
  2765. {
  2766. return false;
  2767. }
  2768. public function SetFixedValue($sValue)
  2769. {
  2770. $this->m_sValue = $sValue;
  2771. }
  2772. public function GetDefaultValue()
  2773. {
  2774. return $this->m_sValue;
  2775. }
  2776. public function GetAsHTML($sValue, $oHostObject = null)
  2777. {
  2778. return Str::pure2html((string)$sValue);
  2779. }
  2780. }
  2781. ?>