attributedef.class.inc.php 93 KB

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