attributedef.class.inc.php 127 KB

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