attributedef.class.inc.php 96 KB

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