attributedef.class.inc.php 108 KB

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