attributedef.class.inc.php 131 KB

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