attributedef.class.inc.php 82 KB

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