attributedef.class.inc.php 125 KB

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