attributedef.class.inc.php 96 KB

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