attributedef.class.inc.php 96 KB

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