attributedef.class.inc.php 125 KB

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