attributedef.class.inc.php 108 KB

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