attributedef.class.inc.php 87 KB

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