attributedef.class.inc.php 98 KB

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