attributedef.class.inc.php 95 KB

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