attributedef.class.inc.php 86 KB

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