attributedef.class.inc.php 126 KB

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