attributedef.class.inc.php 82 KB

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