attributedef.class.inc.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  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. /**
  59. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  60. *
  61. * @package iTopORM
  62. */
  63. abstract class AttributeDefinition
  64. {
  65. public function GetType()
  66. {
  67. return Dict::S('Core:'.get_class($this));
  68. }
  69. public function GetTypeDesc()
  70. {
  71. return Dict::S('Core:'.get_class($this).'+');
  72. }
  73. abstract public function GetEditClass();
  74. protected $m_sCode;
  75. private $m_aParams = array();
  76. protected $m_sHostClass = '!undefined!';
  77. protected function Get($sParamName) {return $this->m_aParams[$sParamName];}
  78. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  79. protected function GetOptional($sParamName, $default)
  80. {
  81. if (array_key_exists($sParamName, $this->m_aParams))
  82. {
  83. return $this->m_aParams[$sParamName];
  84. }
  85. else
  86. {
  87. return $default;
  88. }
  89. }
  90. public function __construct($sCode, $aParams)
  91. {
  92. $this->m_sCode = $sCode;
  93. $this->m_aParams = $aParams;
  94. $this->ConsistencyCheck();
  95. }
  96. public function OverloadParams($aParams)
  97. {
  98. foreach ($aParams as $sParam => $value)
  99. {
  100. if (!array_key_exists($sParam, $this->m_aParams))
  101. {
  102. throw new CoreException("Unknown attribute definition parameter '$sParam', please select a value in {".implode(", ", array_keys($this->m_aParams))."}");
  103. }
  104. else
  105. {
  106. $this->m_aParams[$sParam] = $value;
  107. }
  108. }
  109. }
  110. public function SetHostClass($sHostClass)
  111. {
  112. $this->m_sHostClass = $sHostClass;
  113. }
  114. public function GetHostClass()
  115. {
  116. return $this->m_sHostClass;
  117. }
  118. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  119. // to be overloaded
  120. static protected function ListExpectedParams()
  121. {
  122. return array();
  123. }
  124. private function ConsistencyCheck()
  125. {
  126. // Check that any mandatory param has been specified
  127. //
  128. $aExpectedParams = $this->ListExpectedParams();
  129. foreach($aExpectedParams as $sParamName)
  130. {
  131. if (!array_key_exists($sParamName, $this->m_aParams))
  132. {
  133. $aBacktrace = debug_backtrace();
  134. $sTargetClass = $aBacktrace[2]["class"];
  135. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  136. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  137. }
  138. }
  139. }
  140. // table, key field, name field
  141. public function ListDBJoins()
  142. {
  143. return "";
  144. // e.g: return array("Site", "infrid", "name");
  145. }
  146. public function IsDirectField() {return false;}
  147. public function IsScalar() {return false;}
  148. public function IsLinkSet() {return false;}
  149. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  150. public function IsExternalField() {return false;}
  151. public function IsWritable() {return false;}
  152. public function IsNullAllowed() {return true;}
  153. public function GetCode() {return $this->m_sCode;}
  154. public function GetLabel() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $this->m_sCode);}
  155. public function GetLabel_Obsolete()
  156. {
  157. // Written for compatibility with a data model written prior to version 0.9.1
  158. if (array_key_exists('label', $this->m_aParams))
  159. {
  160. return $this->m_aParams['label'];
  161. }
  162. else
  163. {
  164. return $this->GetLabel();
  165. }
  166. }
  167. public function GetDescription() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', '');}
  168. public function GetHelpOnEdition() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', '');}
  169. public function GetDescription_Obsolete()
  170. {
  171. // Written for compatibility with a data model written prior to version 0.9.1
  172. if (array_key_exists('description', $this->m_aParams))
  173. {
  174. return $this->m_aParams['description'];
  175. }
  176. else
  177. {
  178. return $this->GetDescription();
  179. }
  180. }
  181. public function GetValuesDef() {return null;}
  182. public function GetPrerequisiteAttributes() {return array();}
  183. public function GetNullValue() {return null;}
  184. public function IsNull($proposedValue) {return is_null($proposedValue);}
  185. public function MakeRealValue($proposedValue) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  186. public function GetSQLExpressions() {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  187. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  188. public function GetSQLColumns() {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  189. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  190. public function RequiresIndex() {return false;}
  191. public function GetValidationPattern()
  192. {
  193. return '';
  194. }
  195. public function CheckFormat($value)
  196. {
  197. return true;
  198. }
  199. public function GetMaxSize()
  200. {
  201. return null;
  202. }
  203. public function MakeValue()
  204. {
  205. $sComputeFunc = $this->Get("compute_func");
  206. if (empty($sComputeFunc)) return null;
  207. return call_user_func($sComputeFunc);
  208. }
  209. abstract public function GetDefaultValue();
  210. //
  211. // To be overloaded in subclasses
  212. //
  213. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  214. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  215. //abstract protected GetBasicFilterHTMLInput();
  216. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  217. public function GetFilterDefinitions()
  218. {
  219. return array();
  220. }
  221. public function GetEditValue($sValue)
  222. {
  223. return (string)$sValue;
  224. }
  225. public function GetAsHTML($sValue)
  226. {
  227. return Str::pure2html((string)$sValue);
  228. }
  229. public function GetAsXML($sValue)
  230. {
  231. return Str::pure2xml((string)$sValue);
  232. }
  233. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  234. {
  235. return (string)$sValue;
  236. }
  237. public function GetAllowedValues($aArgs = array(), $sContains = '')
  238. {
  239. $oValSetDef = $this->GetValuesDef();
  240. if (!$oValSetDef) return null;
  241. return $oValSetDef->GetValues($aArgs, $sContains);
  242. }
  243. /**
  244. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  245. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  246. * does nothing special, and just calls the default (loose) operator
  247. * @param string $sSearchText The search string to analyze for smart patterns
  248. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  249. * @param Hash $aParams Values of the query parameters
  250. * @return Expression The search condition to be added (AND) to the current search
  251. */
  252. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  253. {
  254. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  255. $oRightExpr = new VariableExpression($sParamName);
  256. $sOperator = $this->GetBasicFilterLooseOperator();
  257. switch ($sOperator)
  258. {
  259. case 'Contains':
  260. $aParams[$sParamName] = "%$sSearchText%";
  261. $sSQLOperator = 'LIKE';
  262. break;
  263. default:
  264. $sSQLOperator = $sOperator;
  265. $aParams[$sParamName] = $sSearchText;
  266. }
  267. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  268. return $oNewCondition;
  269. }
  270. }
  271. /**
  272. * Set of objects directly linked to an object, and being part of its definition
  273. *
  274. * @package iTopORM
  275. */
  276. class AttributeLinkedSet extends AttributeDefinition
  277. {
  278. static protected function ListExpectedParams()
  279. {
  280. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  281. }
  282. public function GetEditClass() {return "List";}
  283. public function IsWritable() {return true;}
  284. public function IsLinkSet() {return true;}
  285. public function IsIndirect() {return false;}
  286. public function GetValuesDef() {return $this->Get("allowed_values");}
  287. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  288. public function GetDefaultValue($aArgs = array())
  289. {
  290. // Note: so far, this feature is a prototype,
  291. // later, the argument 'this' should always be present in the arguments
  292. //
  293. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  294. {
  295. $aValues = $this->Get('default_value')->GetValues($aArgs);
  296. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  297. return $oSet;
  298. }
  299. else
  300. {
  301. return DBObjectSet::FromScratch($this->Get('linked_class'));
  302. }
  303. }
  304. public function GetLinkedClass() {return $this->Get('linked_class');}
  305. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  306. public function GetBasicFilterOperators() {return array();}
  307. public function GetBasicFilterLooseOperator() {return '';}
  308. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  309. public function GetAsHTML($sValue)
  310. {
  311. return "ERROR: LIST OF OBJECTS";
  312. }
  313. public function GetAsXML($sValue)
  314. {
  315. return "ERROR: LIST OF OBJECTS";
  316. }
  317. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  318. {
  319. return "ERROR: LIST OF OBJECTS";
  320. }
  321. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  322. }
  323. /**
  324. * Set of objects linked to an object (n-n), and being part of its definition
  325. *
  326. * @package iTopORM
  327. */
  328. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  329. {
  330. static protected function ListExpectedParams()
  331. {
  332. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  333. }
  334. public function IsIndirect() {return true;}
  335. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  336. public function GetEditClass() {return "LinkedSet";}
  337. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  338. }
  339. /**
  340. * Abstract class implementing default filters for a DB column
  341. *
  342. * @package iTopORM
  343. */
  344. class AttributeDBFieldVoid extends AttributeDefinition
  345. {
  346. static protected function ListExpectedParams()
  347. {
  348. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  349. }
  350. // To be overriden, used in GetSQLColumns
  351. protected function GetSQLCol() {return "VARCHAR(255)";}
  352. public function GetEditClass() {return "String";}
  353. public function GetValuesDef() {return $this->Get("allowed_values");}
  354. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  355. public function IsDirectField() {return true;}
  356. public function IsScalar() {return true;}
  357. public function IsWritable() {return true;}
  358. public function GetSQLExpr() {return $this->Get("sql");}
  359. public function GetDefaultValue() {return $this->MakeRealValue("");}
  360. public function IsNullAllowed() {return false;}
  361. //
  362. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  363. public function GetSQLExpressions()
  364. {
  365. $aColumns = array();
  366. // Note: to optimize things, the existence of the attribute is determine by the existence of one column with an empty suffix
  367. $aColumns[''] = $this->Get("sql");
  368. return $aColumns;
  369. }
  370. public function FromSQLToValue($aCols, $sPrefix = '')
  371. {
  372. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  373. return $value;
  374. }
  375. public function GetSQLValues($value)
  376. {
  377. $aValues = array();
  378. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  379. return $aValues;
  380. }
  381. public function GetSQLColumns()
  382. {
  383. $aColumns = array();
  384. $aColumns[$this->Get("sql")] = $this->GetSQLCol();
  385. return $aColumns;
  386. }
  387. public function GetFilterDefinitions()
  388. {
  389. return array($this->GetCode() => new FilterFromAttribute($this));
  390. }
  391. public function GetBasicFilterOperators()
  392. {
  393. return array("="=>"equals", "!="=>"differs from");
  394. }
  395. public function GetBasicFilterLooseOperator()
  396. {
  397. return "=";
  398. }
  399. public function GetBasicFilterSQLExpr($sOpCode, $value)
  400. {
  401. $sQValue = CMDBSource::Quote($value);
  402. switch ($sOpCode)
  403. {
  404. case '!=':
  405. return $this->GetSQLExpr()." != $sQValue";
  406. break;
  407. case '=':
  408. default:
  409. return $this->GetSQLExpr()." = $sQValue";
  410. }
  411. }
  412. }
  413. /**
  414. * Base class for all kind of DB attributes, with the exception of external keys
  415. *
  416. * @package iTopORM
  417. */
  418. class AttributeDBField extends AttributeDBFieldVoid
  419. {
  420. static protected function ListExpectedParams()
  421. {
  422. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  423. }
  424. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"));}
  425. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  426. }
  427. /**
  428. * Map an integer column to an attribute
  429. *
  430. * @package iTopORM
  431. */
  432. class AttributeInteger extends AttributeDBField
  433. {
  434. static protected function ListExpectedParams()
  435. {
  436. return parent::ListExpectedParams();
  437. //return array_merge(parent::ListExpectedParams(), array());
  438. }
  439. public function GetEditClass() {return "String";}
  440. protected function GetSQLCol() {return "INT(11)";}
  441. public function GetValidationPattern()
  442. {
  443. return "^[0-9]+$";
  444. }
  445. public function GetBasicFilterOperators()
  446. {
  447. return array(
  448. "!="=>"differs from",
  449. "="=>"equals",
  450. ">"=>"greater (strict) than",
  451. ">="=>"greater than",
  452. "<"=>"less (strict) than",
  453. "<="=>"less than",
  454. "in"=>"in"
  455. );
  456. }
  457. public function GetBasicFilterLooseOperator()
  458. {
  459. // Unless we implement an "equals approximately..." or "same order of magnitude"
  460. return "=";
  461. }
  462. public function GetBasicFilterSQLExpr($sOpCode, $value)
  463. {
  464. $sQValue = CMDBSource::Quote($value);
  465. switch ($sOpCode)
  466. {
  467. case '!=':
  468. return $this->GetSQLExpr()." != $sQValue";
  469. break;
  470. case '>':
  471. return $this->GetSQLExpr()." > $sQValue";
  472. break;
  473. case '>=':
  474. return $this->GetSQLExpr()." >= $sQValue";
  475. break;
  476. case '<':
  477. return $this->GetSQLExpr()." < $sQValue";
  478. break;
  479. case '<=':
  480. return $this->GetSQLExpr()." <= $sQValue";
  481. break;
  482. case 'in':
  483. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  484. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  485. break;
  486. case '=':
  487. default:
  488. return $this->GetSQLExpr()." = \"$value\"";
  489. }
  490. }
  491. public function GetNullValue()
  492. {
  493. return null;
  494. }
  495. public function IsNull($proposedValue)
  496. {
  497. return is_null($proposedValue);
  498. }
  499. public function MakeRealValue($proposedValue)
  500. {
  501. if (is_null($proposedValue)) return null;
  502. if ($proposedValue == '') return null;
  503. return (int)$proposedValue;
  504. }
  505. public function ScalarToSQL($value)
  506. {
  507. assert(is_numeric($value) || is_null($value));
  508. return $value; // supposed to be an int
  509. }
  510. }
  511. /**
  512. * Map a decimal value column (suitable for financial computations) to an attribute
  513. * internally in PHP such numbers are represented as string. Should you want to perform
  514. * a calculation on them, it is recommended to use the BC Math functions in order to
  515. * retain the precision
  516. *
  517. * @package iTopORM
  518. */
  519. class AttributeDecimal extends AttributeDBField
  520. {
  521. static protected function ListExpectedParams()
  522. {
  523. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  524. }
  525. public function GetEditClass() {return "String";}
  526. protected function GetSQLCol() {return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")";}
  527. public function GetValidationPattern()
  528. {
  529. $iNbDigits = $this->Get('digits');
  530. $iPrecision = $this->Get('decimals');
  531. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  532. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  533. }
  534. public function GetBasicFilterOperators()
  535. {
  536. return array(
  537. "!="=>"differs from",
  538. "="=>"equals",
  539. ">"=>"greater (strict) than",
  540. ">="=>"greater than",
  541. "<"=>"less (strict) than",
  542. "<="=>"less than",
  543. "in"=>"in"
  544. );
  545. }
  546. public function GetBasicFilterLooseOperator()
  547. {
  548. // Unless we implement an "equals approximately..." or "same order of magnitude"
  549. return "=";
  550. }
  551. public function GetBasicFilterSQLExpr($sOpCode, $value)
  552. {
  553. $sQValue = CMDBSource::Quote($value);
  554. switch ($sOpCode)
  555. {
  556. case '!=':
  557. return $this->GetSQLExpr()." != $sQValue";
  558. break;
  559. case '>':
  560. return $this->GetSQLExpr()." > $sQValue";
  561. break;
  562. case '>=':
  563. return $this->GetSQLExpr()." >= $sQValue";
  564. break;
  565. case '<':
  566. return $this->GetSQLExpr()." < $sQValue";
  567. break;
  568. case '<=':
  569. return $this->GetSQLExpr()." <= $sQValue";
  570. break;
  571. case 'in':
  572. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  573. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  574. break;
  575. case '=':
  576. default:
  577. return $this->GetSQLExpr()." = \"$value\"";
  578. }
  579. }
  580. public function GetNullValue()
  581. {
  582. return null;
  583. }
  584. public function IsNull($proposedValue)
  585. {
  586. return is_null($proposedValue);
  587. }
  588. public function MakeRealValue($proposedValue)
  589. {
  590. if (is_null($proposedValue)) return null;
  591. if ($proposedValue == '') return null;
  592. return (string)$proposedValue;
  593. }
  594. public function ScalarToSQL($value)
  595. {
  596. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  597. return (string)$value; // treated as a string
  598. }
  599. }
  600. /**
  601. * Map a boolean column to an attribute
  602. *
  603. * @package iTopORM
  604. */
  605. class AttributeBoolean extends AttributeInteger
  606. {
  607. static protected function ListExpectedParams()
  608. {
  609. return parent::ListExpectedParams();
  610. //return array_merge(parent::ListExpectedParams(), array());
  611. }
  612. public function GetEditClass() {return "Integer";}
  613. protected function GetSQLCol() {return "TINYINT(1)";}
  614. public function MakeRealValue($proposedValue)
  615. {
  616. if (is_null($proposedValue)) return null;
  617. if ($proposedValue == '') return null;
  618. if ((int)$proposedValue) return true;
  619. return false;
  620. }
  621. public function ScalarToSQL($value)
  622. {
  623. if ($value) return 1;
  624. return 0;
  625. }
  626. }
  627. /**
  628. * Map a varchar column (size < ?) to an attribute
  629. *
  630. * @package iTopORM
  631. */
  632. class AttributeString extends AttributeDBField
  633. {
  634. static protected function ListExpectedParams()
  635. {
  636. return parent::ListExpectedParams();
  637. //return array_merge(parent::ListExpectedParams(), array());
  638. }
  639. public function GetEditClass() {return "String";}
  640. protected function GetSQLCol() {return "VARCHAR(255)";}
  641. public function CheckFormat($value)
  642. {
  643. $sRegExp = $this->GetValidationPattern();
  644. if (empty($sRegExp))
  645. {
  646. return true;
  647. }
  648. else
  649. {
  650. $sRegExp = str_replace('/', '\\/', $sRegExp);
  651. return preg_match("/$sRegExp/", $value);
  652. }
  653. }
  654. public function GetMaxSize()
  655. {
  656. return 255;
  657. }
  658. public function GetBasicFilterOperators()
  659. {
  660. return array(
  661. "="=>"equals",
  662. "!="=>"differs from",
  663. "Like"=>"equals (no case)",
  664. "NotLike"=>"differs from (no case)",
  665. "Contains"=>"contains",
  666. "Begins with"=>"begins with",
  667. "Finishes with"=>"finishes with"
  668. );
  669. }
  670. public function GetBasicFilterLooseOperator()
  671. {
  672. return "Contains";
  673. }
  674. public function GetBasicFilterSQLExpr($sOpCode, $value)
  675. {
  676. $sQValue = CMDBSource::Quote($value);
  677. switch ($sOpCode)
  678. {
  679. case '=':
  680. case '!=':
  681. return $this->GetSQLExpr()." $sOpCode $sQValue";
  682. case 'Begins with':
  683. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  684. case 'Finishes with':
  685. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  686. case 'Contains':
  687. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  688. case 'NotLike':
  689. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  690. case 'Like':
  691. default:
  692. return $this->GetSQLExpr()." LIKE $sQValue";
  693. }
  694. }
  695. public function GetNullValue()
  696. {
  697. return '';
  698. }
  699. public function IsNull($proposedValue)
  700. {
  701. return ($proposedValue == '');
  702. }
  703. public function MakeRealValue($proposedValue)
  704. {
  705. if (is_null($proposedValue)) return '';
  706. return (string)$proposedValue;
  707. }
  708. public function ScalarToSQL($value)
  709. {
  710. if (!is_string($value) && !is_null($value))
  711. {
  712. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  713. }
  714. return $value;
  715. }
  716. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  717. {
  718. $sFrom = array("\r\n", $sTextQualifier);
  719. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  720. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  721. return '"'.$sEscaped.'"';
  722. }
  723. }
  724. /**
  725. * An attibute that matches an object class
  726. *
  727. * @package iTopORM
  728. */
  729. class AttributeClass extends AttributeString
  730. {
  731. static protected function ListExpectedParams()
  732. {
  733. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  734. }
  735. public function __construct($sCode, $aParams)
  736. {
  737. $this->m_sCode = $sCode;
  738. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  739. parent::__construct($sCode, $aParams);
  740. }
  741. public function GetDefaultValue()
  742. {
  743. $sDefault = parent::GetDefaultValue();
  744. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  745. {
  746. // For this kind of attribute specifying null as default value
  747. // is authorized even if null is not allowed
  748. // Pick the first one...
  749. $aClasses = $this->GetAllowedValues();
  750. $sDefault = key($aClasses);
  751. }
  752. return $sDefault;
  753. }
  754. public function GetAsHTML($sValue)
  755. {
  756. if (empty($sValue)) return '';
  757. return MetaModel::GetName($sValue);
  758. }
  759. public function RequiresIndex()
  760. {
  761. return true;
  762. }
  763. }
  764. /**
  765. * An attibute that matches one of the language codes availables in the dictionnary
  766. *
  767. * @package iTopORM
  768. */
  769. class AttributeApplicationLanguage extends AttributeString
  770. {
  771. static protected function ListExpectedParams()
  772. {
  773. return parent::ListExpectedParams();
  774. }
  775. public function __construct($sCode, $aParams)
  776. {
  777. $this->m_sCode = $sCode;
  778. $aAvailableLanguages = Dict::GetLanguages();
  779. $aLanguageCodes = array();
  780. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  781. {
  782. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  783. }
  784. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  785. parent::__construct($sCode, $aParams);
  786. }
  787. public function RequiresIndex()
  788. {
  789. return true;
  790. }
  791. }
  792. /**
  793. * The attribute dedicated to the finalclass automatic attribute
  794. *
  795. * @package iTopORM
  796. */
  797. class AttributeFinalClass extends AttributeString
  798. {
  799. public function __construct($sCode, $aParams)
  800. {
  801. $this->m_sCode = $sCode;
  802. $aParams["allowed_values"] = null;
  803. parent::__construct($sCode, $aParams);
  804. $this->m_sValue = $this->Get("default_value");
  805. }
  806. public function IsWritable()
  807. {
  808. return false;
  809. }
  810. public function RequiresIndex()
  811. {
  812. return true;
  813. }
  814. public function SetFixedValue($sValue)
  815. {
  816. $this->m_sValue = $sValue;
  817. }
  818. public function GetDefaultValue()
  819. {
  820. return $this->m_sValue;
  821. }
  822. public function GetAsHTML($sValue)
  823. {
  824. if (empty($sValue)) return '';
  825. return MetaModel::GetName($sValue);
  826. }
  827. }
  828. /**
  829. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  830. *
  831. * @package iTopORM
  832. */
  833. class AttributePassword extends AttributeString
  834. {
  835. static protected function ListExpectedParams()
  836. {
  837. return parent::ListExpectedParams();
  838. //return array_merge(parent::ListExpectedParams(), array());
  839. }
  840. public function GetEditClass() {return "Password";}
  841. protected function GetSQLCol() {return "VARCHAR(64)";}
  842. public function GetMaxSize()
  843. {
  844. return 64;
  845. }
  846. public function GetFilterDefinitions()
  847. {
  848. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  849. // not allowed to search on passwords!
  850. return array();
  851. }
  852. public function GetAsHTML($sValue)
  853. {
  854. if (strlen($sValue) == 0)
  855. {
  856. return '';
  857. }
  858. else
  859. {
  860. return '******';
  861. }
  862. }
  863. }
  864. /**
  865. * Map a text column (size < 255) to an attribute that is encrypted in the database
  866. * The encryption is based on a key set per iTop instance. Thus if you export your
  867. * database (in SQL) to someone else without providing the key at the same time
  868. * the encrypted fields will remain encrypted
  869. *
  870. * @package iTopORM
  871. */
  872. class AttributeEncryptedString extends AttributeString
  873. {
  874. static $sKey = null; // Encryption key used for all encrypted fields
  875. public function __construct($sCode, $aParams)
  876. {
  877. parent::__construct($sCode, $aParams);
  878. if (self::$sKey == null)
  879. {
  880. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  881. }
  882. }
  883. protected function GetSQLCol() {return "TINYBLOB";}
  884. public function GetMaxSize()
  885. {
  886. return 255;
  887. }
  888. public function GetFilterDefinitions()
  889. {
  890. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  891. // not allowed to search on encrypted fields !
  892. return array();
  893. }
  894. public function MakeRealValue($proposedValue)
  895. {
  896. if (is_null($proposedValue)) return null;
  897. return (string)$proposedValue;
  898. }
  899. /**
  900. * Decrypt the value when reading from the database
  901. */
  902. public function FromSQLToValue($aCols, $sPrefix = '')
  903. {
  904. $oSimpleCrypt = new SimpleCrypt();
  905. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  906. return $sValue;
  907. }
  908. /**
  909. * Encrypt the value before storing it in the database
  910. */
  911. public function GetSQLValues($value)
  912. {
  913. $oSimpleCrypt = new SimpleCrypt();
  914. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  915. $aValues = array();
  916. $aValues[$this->Get("sql")] = $encryptedValue;
  917. return $aValues;
  918. }
  919. }
  920. /**
  921. * Map a text column (size > ?) to an attribute
  922. *
  923. * @package iTopORM
  924. */
  925. class AttributeText extends AttributeString
  926. {
  927. public function GetEditClass() {return "Text";}
  928. protected function GetSQLCol() {return "TEXT";}
  929. public function GetMaxSize()
  930. {
  931. // Is there a way to know the current limitation for mysql?
  932. // See mysql_field_len()
  933. return 65535;
  934. }
  935. public function GetAsHTML($sValue)
  936. {
  937. return str_replace("\n", "<br>\n", parent::GetAsHTML($sValue));
  938. }
  939. public function GetAsXML($value)
  940. {
  941. return Str::pure2xml($value);
  942. }
  943. }
  944. /**
  945. * Map a text column (size > ?), containing HTML code, to an attribute
  946. *
  947. * @package iTopORM
  948. */
  949. class AttributeHTML extends AttributeText
  950. {
  951. public function GetEditClass() {return "HTML";}
  952. public function GetAsHTML($sValue)
  953. {
  954. return $sValue;
  955. }
  956. }
  957. /**
  958. * Specialization of a string: email
  959. *
  960. * @package iTopORM
  961. */
  962. class AttributeEmailAddress extends AttributeString
  963. {
  964. public function GetValidationPattern()
  965. {
  966. return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  967. }
  968. public function GetAsHTML($sValue)
  969. {
  970. if (empty($sValue)) return '';
  971. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  972. }
  973. }
  974. /**
  975. * Specialization of a string: IP address
  976. *
  977. * @package iTopORM
  978. */
  979. class AttributeIPAddress extends AttributeString
  980. {
  981. public function GetValidationPattern()
  982. {
  983. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  984. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  985. }
  986. }
  987. /**
  988. * Specialization of a string: OQL expression
  989. *
  990. * @package iTopORM
  991. */
  992. class AttributeOQL extends AttributeText
  993. {
  994. }
  995. /**
  996. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  997. *
  998. * @package iTopORM
  999. */
  1000. class AttributeTemplateString extends AttributeString
  1001. {
  1002. }
  1003. /**
  1004. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1005. *
  1006. * @package iTopORM
  1007. */
  1008. class AttributeTemplateText extends AttributeText
  1009. {
  1010. }
  1011. /**
  1012. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1013. *
  1014. * @package iTopORM
  1015. */
  1016. class AttributeTemplateHTML extends AttributeText
  1017. {
  1018. public function GetEditClass() {return "HTML";}
  1019. public function GetAsHTML($sValue)
  1020. {
  1021. return $sValue;
  1022. }
  1023. }
  1024. /**
  1025. * Specialization of a text: wiki formatting
  1026. *
  1027. * @package iTopORM
  1028. */
  1029. class AttributeWikiText extends AttributeText
  1030. {
  1031. public function GetAsHTML($value)
  1032. {
  1033. // [SELECT xxxx.... [label]] => hyperlink to a result list
  1034. // {SELECT xxxx.... [label]} => result list displayed inline
  1035. // [myclass/nnn [label]] => hyperlink to an object
  1036. // {myclass/nnn/attcode} => attribute displayed inline
  1037. // etc.
  1038. return parent::GetAsHTML($value);
  1039. }
  1040. }
  1041. /**
  1042. * Map a enum column to an attribute
  1043. *
  1044. * @package iTopORM
  1045. */
  1046. class AttributeEnum extends AttributeString
  1047. {
  1048. static protected function ListExpectedParams()
  1049. {
  1050. return parent::ListExpectedParams();
  1051. //return array_merge(parent::ListExpectedParams(), array());
  1052. }
  1053. public function GetEditClass() {return "String";}
  1054. protected function GetSQLCol()
  1055. {
  1056. $oValDef = $this->GetValuesDef();
  1057. if ($oValDef)
  1058. {
  1059. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  1060. }
  1061. else
  1062. {
  1063. $aValues = array();
  1064. }
  1065. if (count($aValues) > 0)
  1066. {
  1067. // The syntax used here do matters
  1068. // In particular, I had to remove unnecessary spaces to
  1069. // make sure that this string will match the field type returned by the DB
  1070. // (used to perform a comparison between the current DB format and the data model)
  1071. return "ENUM(".implode(",", $aValues).")";
  1072. }
  1073. else
  1074. {
  1075. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  1076. }
  1077. }
  1078. public function ScalarToSQL($value)
  1079. {
  1080. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  1081. // but that wasn't working for enums, because '' is NOT one of the allowed values
  1082. // that's why a null value must be forced to a real null
  1083. $value = parent::ScalarToSQL($value);
  1084. if ($this->IsNull($value))
  1085. {
  1086. return null;
  1087. }
  1088. else
  1089. {
  1090. return $value;
  1091. }
  1092. }
  1093. public function RequiresIndex()
  1094. {
  1095. return false;
  1096. }
  1097. public function GetBasicFilterOperators()
  1098. {
  1099. return parent::GetBasicFilterOperators();
  1100. }
  1101. public function GetBasicFilterLooseOperator()
  1102. {
  1103. return parent::GetBasicFilterLooseOperator();
  1104. }
  1105. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1106. {
  1107. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1108. }
  1109. public function GetAsHTML($sValue)
  1110. {
  1111. if (is_null($sValue))
  1112. {
  1113. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1114. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  1115. }
  1116. else
  1117. {
  1118. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1119. }
  1120. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', $sValue);
  1121. // later, we could imagine a detailed description in the title
  1122. return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  1123. }
  1124. public function GetEditValue($sValue)
  1125. {
  1126. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1127. return $sLabel;
  1128. }
  1129. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1130. {
  1131. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  1132. if (is_null($aRawValues)) return null;
  1133. $aLocalizedValues = array();
  1134. foreach ($aRawValues as $sKey => $sValue)
  1135. {
  1136. $aLocalizedValues[$sKey] = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sKey, $sKey);
  1137. }
  1138. return $aLocalizedValues;
  1139. }
  1140. /**
  1141. * Processes the input value to align it with the values supported
  1142. * by this type of attribute. In this case: turns empty strings into nulls
  1143. * @param mixed $proposedValue The value to be set for the attribute
  1144. * @return mixed The actual value that will be set
  1145. */
  1146. public function MakeRealValue($proposedValue)
  1147. {
  1148. if ($proposedValue == '') return null;
  1149. return parent::MakeRealValue($proposedValue);
  1150. }
  1151. }
  1152. /**
  1153. * Map a date+time column to an attribute
  1154. *
  1155. * @package iTopORM
  1156. */
  1157. class AttributeDateTime extends AttributeDBField
  1158. {
  1159. //const MYDATETIMEZONE = "UTC";
  1160. const MYDATETIMEZONE = "Europe/Paris";
  1161. static protected $const_TIMEZONE = null; // set once for all upon object construct
  1162. static public function InitStatics()
  1163. {
  1164. // Init static constant once for all (remove when PHP allows real static const)
  1165. self::$const_TIMEZONE = new DateTimeZone(self::MYDATETIMEZONE);
  1166. // #@# Init default timezone -> do not get a notice... to be improved !!!
  1167. // duplicated in the email test page (the mail function does trigger a notice as well)
  1168. date_default_timezone_set(self::MYDATETIMEZONE);
  1169. }
  1170. static protected function GetDateFormat()
  1171. {
  1172. return "Y-m-d H:i:s";
  1173. }
  1174. static protected function ListExpectedParams()
  1175. {
  1176. return parent::ListExpectedParams();
  1177. //return array_merge(parent::ListExpectedParams(), array());
  1178. }
  1179. public function GetEditClass() {return "DateTime";}
  1180. protected function GetSQLCol() {return "TIMESTAMP";}
  1181. public static function GetAsUnixSeconds($value)
  1182. {
  1183. $oDeadlineDateTime = new DateTime($value, self::$const_TIMEZONE);
  1184. $iUnixSeconds = $oDeadlineDateTime->format('U');
  1185. return $iUnixSeconds;
  1186. }
  1187. // #@# THIS HAS TO REVISED
  1188. // Having null not allowed was interpreted by mySQL
  1189. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  1190. // Then, on each update of the record, the field was modified.
  1191. // We will have to specify the default value if we want to restore this option
  1192. // In fact, we could also have more verbs dedicated to the DB:
  1193. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  1194. public function IsNullAllowed() {return true;}
  1195. public function GetDefaultValue()
  1196. {
  1197. $default = parent::GetDefaultValue();
  1198. if (!parent::IsNullAllowed())
  1199. {
  1200. if (empty($default))
  1201. {
  1202. $default = date(self::GetDateFormat());
  1203. }
  1204. }
  1205. return $default;
  1206. }
  1207. // END OF THE WORKAROUND
  1208. ///////////////////////////////////////////////////////////////
  1209. public function GetValidationPattern()
  1210. {
  1211. 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$";
  1212. }
  1213. public function GetBasicFilterOperators()
  1214. {
  1215. return array(
  1216. "="=>"equals",
  1217. "!="=>"differs from",
  1218. "<"=>"before",
  1219. "<="=>"before",
  1220. ">"=>"after (strictly)",
  1221. ">="=>"after",
  1222. "SameDay"=>"same day (strip time)",
  1223. "SameMonth"=>"same year/month",
  1224. "SameYear"=>"same year",
  1225. "Today"=>"today",
  1226. ">|"=>"after today + N days",
  1227. "<|"=>"before today + N days",
  1228. "=|"=>"equals today + N days",
  1229. );
  1230. }
  1231. public function GetBasicFilterLooseOperator()
  1232. {
  1233. // Unless we implement a "same xxx, depending on given precision" !
  1234. return "=";
  1235. }
  1236. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1237. {
  1238. $sQValue = CMDBSource::Quote($value);
  1239. switch ($sOpCode)
  1240. {
  1241. case '=':
  1242. case '!=':
  1243. case '<':
  1244. case '<=':
  1245. case '>':
  1246. case '>=':
  1247. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1248. case 'SameDay':
  1249. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  1250. case 'SameMonth':
  1251. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  1252. case 'SameYear':
  1253. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  1254. case 'Today':
  1255. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  1256. case '>|':
  1257. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1258. case '<|':
  1259. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1260. case '=|':
  1261. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1262. default:
  1263. return $this->GetSQLExpr()." = $sQValue";
  1264. }
  1265. }
  1266. public function MakeRealValue($proposedValue)
  1267. {
  1268. if (is_null($proposedValue))
  1269. {
  1270. return null;
  1271. }
  1272. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  1273. {
  1274. return null;
  1275. }
  1276. if (!is_numeric($proposedValue))
  1277. {
  1278. return $proposedValue;
  1279. }
  1280. return date(self::GetDateFormat(), $proposedValue);
  1281. }
  1282. public function ScalarToSQL($value)
  1283. {
  1284. if (is_null($value))
  1285. {
  1286. return null;
  1287. }
  1288. elseif (empty($value))
  1289. {
  1290. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  1291. return '0000-00-00 00:00:00';
  1292. }
  1293. return $value;
  1294. }
  1295. public function GetAsHTML($value)
  1296. {
  1297. return Str::pure2html($value);
  1298. }
  1299. public function GetAsXML($value)
  1300. {
  1301. return Str::pure2xml($value);
  1302. }
  1303. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1304. {
  1305. $sFrom = array("\r\n", $sTextQualifier);
  1306. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1307. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1308. return '"'.$sEscaped.'"';
  1309. }
  1310. /**
  1311. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  1312. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  1313. * does nothing special, and just calls the default (loose) operator
  1314. * @param string $sSearchText The search string to analyze for smart patterns
  1315. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  1316. * @param Hash $aParams Values of the query parameters
  1317. * @return Expression The search condition to be added (AND) to the current search
  1318. */
  1319. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  1320. {
  1321. // Possible smart patterns
  1322. $aPatterns = array(
  1323. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  1324. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  1325. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  1326. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  1327. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  1328. );
  1329. $sPatternFound = '';
  1330. $aMatches = array();
  1331. foreach($aPatterns as $sPatName => $sPattern)
  1332. {
  1333. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  1334. {
  1335. $sPatternFound = $sPatName;
  1336. break;
  1337. }
  1338. }
  1339. switch($sPatternFound)
  1340. {
  1341. case 'between':
  1342. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  1343. $oRightExpr = new VariableExpression($sParamName1);
  1344. $aParams[$sParamName1] = $aMatches[1];
  1345. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  1346. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  1347. $oRightExpr = new VariableExpression($sParamName2);
  1348. $sOperator = $this->GetBasicFilterLooseOperator();
  1349. $aParams[$sParamName2] = $aMatches[2];
  1350. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  1351. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  1352. break;
  1353. case 'greater than':
  1354. case 'greater than or equal':
  1355. case 'less than':
  1356. case 'less than or equal':
  1357. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  1358. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  1359. $oRightExpr = new VariableExpression($sParamName);
  1360. $aParams[$sParamName] = $aMatches[1];
  1361. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  1362. break;
  1363. default:
  1364. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  1365. }
  1366. return $oNewCondition;
  1367. }
  1368. }
  1369. /**
  1370. * Map a date+time column to an attribute
  1371. *
  1372. * @package iTopORM
  1373. */
  1374. class AttributeDate extends AttributeDateTime
  1375. {
  1376. const MYDATEFORMAT = "Y-m-d";
  1377. static protected function GetDateFormat()
  1378. {
  1379. return "Y-m-d";
  1380. }
  1381. static public function InitStatics()
  1382. {
  1383. // Nothing to do...
  1384. }
  1385. static protected function ListExpectedParams()
  1386. {
  1387. return parent::ListExpectedParams();
  1388. //return array_merge(parent::ListExpectedParams(), array());
  1389. }
  1390. public function GetEditClass() {return "Date";}
  1391. protected function GetSQLCol() {return "DATE";}
  1392. public function GetValidationPattern()
  1393. {
  1394. 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)))$";
  1395. }
  1396. }
  1397. // Init static constant once for all (remove when PHP allows real static const)
  1398. AttributeDate::InitStatics();
  1399. /**
  1400. * A dead line stored as a date & time
  1401. * The only difference with the DateTime attribute is the display:
  1402. * relative to the current time
  1403. */
  1404. class AttributeDeadline extends AttributeDateTime
  1405. {
  1406. public function GetAsHTML($value)
  1407. {
  1408. $sResult = '';
  1409. if ($value !== null)
  1410. {
  1411. $value = AttributeDateTime::GetAsUnixSeconds($value);
  1412. $difference = $value - time();
  1413. if ($difference >= 0)
  1414. {
  1415. $sResult = self::FormatDuration($difference);
  1416. }
  1417. else
  1418. {
  1419. $sResult = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  1420. }
  1421. }
  1422. return $sResult;
  1423. }
  1424. static function FormatDuration($duration)
  1425. {
  1426. $days = floor($duration / 86400);
  1427. $hours = floor(($duration - (86400*$days)) / 3600);
  1428. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  1429. $sResult = '';
  1430. if ($duration < 60)
  1431. {
  1432. // Less than 1 min
  1433. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  1434. }
  1435. else if ($duration < 3600)
  1436. {
  1437. // less than 1 hour, display it in minutes
  1438. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  1439. }
  1440. else if ($duration < 86400)
  1441. {
  1442. // Less that 1 day, display it in hours/minutes
  1443. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  1444. }
  1445. else
  1446. {
  1447. // Less that 1 day, display it in hours/minutes
  1448. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  1449. }
  1450. return $sResult;
  1451. }
  1452. }
  1453. // Init static constant once for all (remove when PHP allows real static const)
  1454. AttributeDateTime::InitStatics();
  1455. /**
  1456. * Map a foreign key to an attribute
  1457. * AttributeExternalKey and AttributeExternalField may be an external key
  1458. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  1459. * where an AttributeExternalField corresponds to a column into another table (class)
  1460. *
  1461. * @package iTopORM
  1462. */
  1463. class AttributeExternalKey extends AttributeDBFieldVoid
  1464. {
  1465. static protected function ListExpectedParams()
  1466. {
  1467. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  1468. }
  1469. public function GetEditClass() {return "ExtKey";}
  1470. protected function GetSQLCol() {return "INT(11)";}
  1471. public function RequiresIndex()
  1472. {
  1473. return true;
  1474. }
  1475. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  1476. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  1477. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  1478. public function GetKeyAttCode() {return $this->GetCode();}
  1479. public function GetDefaultValue() {return 0;}
  1480. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  1481. public function GetBasicFilterOperators()
  1482. {
  1483. return parent::GetBasicFilterOperators();
  1484. }
  1485. public function GetBasicFilterLooseOperator()
  1486. {
  1487. return parent::GetBasicFilterLooseOperator();
  1488. }
  1489. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1490. {
  1491. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1492. }
  1493. // overloaded here so that an ext key always have the answer to
  1494. // "what are your possible values?"
  1495. public function GetValuesDef()
  1496. {
  1497. $oValSetDef = $this->Get("allowed_values");
  1498. if (!$oValSetDef)
  1499. {
  1500. // Let's propose every existing value
  1501. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1502. }
  1503. return $oValSetDef;
  1504. }
  1505. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1506. {
  1507. try
  1508. {
  1509. return parent::GetAllowedValues($aArgs, $sContains);
  1510. }
  1511. catch (MissingQueryArgument $e)
  1512. {
  1513. // Some required arguments could not be found, enlarge to any existing value
  1514. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1515. return $oValSetDef->GetValues($aArgs, $sContains);
  1516. }
  1517. }
  1518. public function GetDeletionPropagationOption()
  1519. {
  1520. return $this->Get("on_target_delete");
  1521. }
  1522. public function GetNullValue()
  1523. {
  1524. return 0;
  1525. }
  1526. public function IsNull($proposedValue)
  1527. {
  1528. return ($proposedValue == 0);
  1529. }
  1530. public function MakeRealValue($proposedValue)
  1531. {
  1532. if (is_null($proposedValue)) return 0;
  1533. if ($proposedValue === '') return 0;
  1534. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  1535. return (int)$proposedValue;
  1536. }
  1537. public function GetMaximumComboLength()
  1538. {
  1539. return $this->GetOptional('max_combo_length', utils::GetConfig()->Get('max_combo_length'));
  1540. }
  1541. public function GetMinAutoCompleteChars()
  1542. {
  1543. return $this->GetOptional('min_autocomplete_chars', utils::GetConfig()->Get('min_autocomplete_chars'));
  1544. }
  1545. public function AllowTargetCreation()
  1546. {
  1547. return $this->GetOptional('allow_target_creation', utils::GetConfig()->Get('allow_target_creation'));
  1548. }
  1549. }
  1550. /**
  1551. * An attribute which corresponds to an external key (direct or indirect)
  1552. *
  1553. * @package iTopORM
  1554. */
  1555. class AttributeExternalField extends AttributeDefinition
  1556. {
  1557. static protected function ListExpectedParams()
  1558. {
  1559. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  1560. }
  1561. public function GetEditClass() {return "ExtField";}
  1562. protected function GetSQLCol()
  1563. {
  1564. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  1565. $oExtAttDef = $this->GetExtAttDef();
  1566. return $oExtAttDef->GetSQLCol();
  1567. }
  1568. public function GetLabel()
  1569. {
  1570. $oRemoteAtt = $this->GetExtAttDef();
  1571. $sDefault = $oRemoteAtt->GetLabel();
  1572. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $sDefault);
  1573. }
  1574. public function GetDescription()
  1575. {
  1576. $oRemoteAtt = $this->GetExtAttDef();
  1577. $sDefault = $oRemoteAtt->GetDescription();
  1578. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', $sDefault);
  1579. }
  1580. public function GetHelpOnEdition()
  1581. {
  1582. $oRemoteAtt = $this->GetExtAttDef();
  1583. $sDefault = $oRemoteAtt->GetHelpOnEdition();
  1584. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', $sDefault);
  1585. }
  1586. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  1587. {
  1588. switch($iType)
  1589. {
  1590. case EXTKEY_ABSOLUTE:
  1591. // see further
  1592. $oRemoteAtt = $this->GetExtAttDef();
  1593. return $oRemoteAtt->IsExternalKey($iType);
  1594. case EXTKEY_RELATIVE:
  1595. return false;
  1596. default:
  1597. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1598. }
  1599. }
  1600. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  1601. {
  1602. return $this->GetKeyAttDef($iType)->GetTargetClass();
  1603. }
  1604. public function IsExternalField() {return true;}
  1605. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  1606. public function GetExtAttCode() {return $this->Get("target_attcode");}
  1607. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  1608. {
  1609. switch($iType)
  1610. {
  1611. case EXTKEY_ABSOLUTE:
  1612. // see further
  1613. $oRemoteAtt = $this->GetExtAttDef();
  1614. if ($oRemoteAtt->IsExternalField())
  1615. {
  1616. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1617. }
  1618. else if ($oRemoteAtt->IsExternalKey())
  1619. {
  1620. return $oRemoteAtt;
  1621. }
  1622. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  1623. case EXTKEY_RELATIVE:
  1624. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  1625. default:
  1626. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1627. }
  1628. }
  1629. public function GetExtAttDef()
  1630. {
  1631. $oKeyAttDef = $this->GetKeyAttDef();
  1632. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->Get("targetclass"), $this->Get("target_attcode"));
  1633. 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"));
  1634. return $oExtAttDef;
  1635. }
  1636. public function GetSQLExpr()
  1637. {
  1638. $oExtAttDef = $this->GetExtAttDef();
  1639. return $oExtAttDef->GetSQLExpr();
  1640. }
  1641. public function GetDefaultValue()
  1642. {
  1643. $oExtAttDef = $this->GetExtAttDef();
  1644. return $oExtAttDef->GetDefaultValue();
  1645. }
  1646. public function IsNullAllowed()
  1647. {
  1648. $oExtAttDef = $this->GetExtAttDef();
  1649. return $oExtAttDef->IsNullAllowed();
  1650. }
  1651. public function IsScalar()
  1652. {
  1653. $oExtAttDef = $this->GetExtAttDef();
  1654. return $oExtAttDef->IsScalar();
  1655. }
  1656. public function GetFilterDefinitions()
  1657. {
  1658. return array($this->GetCode() => new FilterFromAttribute($this));
  1659. }
  1660. public function GetBasicFilterOperators()
  1661. {
  1662. $oExtAttDef = $this->GetExtAttDef();
  1663. return $oExtAttDef->GetBasicFilterOperators();
  1664. }
  1665. public function GetBasicFilterLooseOperator()
  1666. {
  1667. $oExtAttDef = $this->GetExtAttDef();
  1668. return $oExtAttDef->GetBasicFilterLooseOperator();
  1669. }
  1670. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1671. {
  1672. $oExtAttDef = $this->GetExtAttDef();
  1673. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  1674. }
  1675. public function GetNullValue()
  1676. {
  1677. $oExtAttDef = $this->GetExtAttDef();
  1678. return $oExtAttDef->GetNullValue();
  1679. }
  1680. public function IsNull($proposedValue)
  1681. {
  1682. $oExtAttDef = $this->GetExtAttDef();
  1683. return $oExtAttDef->IsNull($proposedValue);
  1684. }
  1685. public function MakeRealValue($proposedValue)
  1686. {
  1687. $oExtAttDef = $this->GetExtAttDef();
  1688. return $oExtAttDef->MakeRealValue($proposedValue);
  1689. }
  1690. public function ScalarToSQL($value)
  1691. {
  1692. // This one could be used in case of filtering only
  1693. $oExtAttDef = $this->GetExtAttDef();
  1694. return $oExtAttDef->ScalarToSQL($value);
  1695. }
  1696. // Do not overload GetSQLExpression here because this is handled in the joins
  1697. //public function GetSQLExpressions() {return array();}
  1698. // Here, we get the data...
  1699. public function FromSQLToValue($aCols, $sPrefix = '')
  1700. {
  1701. $oExtAttDef = $this->GetExtAttDef();
  1702. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  1703. }
  1704. public function GetAsHTML($value)
  1705. {
  1706. $oExtAttDef = $this->GetExtAttDef();
  1707. return $oExtAttDef->GetAsHTML($value);
  1708. }
  1709. public function GetAsXML($value)
  1710. {
  1711. $oExtAttDef = $this->GetExtAttDef();
  1712. return $oExtAttDef->GetAsXML($value);
  1713. }
  1714. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"')
  1715. {
  1716. $oExtAttDef = $this->GetExtAttDef();
  1717. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  1718. }
  1719. }
  1720. /**
  1721. * Map a varchar column to an URL (formats the ouput in HMTL)
  1722. *
  1723. * @package iTopORM
  1724. */
  1725. class AttributeURL extends AttributeString
  1726. {
  1727. static protected function ListExpectedParams()
  1728. {
  1729. //return parent::ListExpectedParams();
  1730. return array_merge(parent::ListExpectedParams(), array("target"));
  1731. }
  1732. public function GetEditClass() {return "String";}
  1733. public function GetAsHTML($sValue)
  1734. {
  1735. $sTarget = $this->Get("target");
  1736. if (empty($sTarget)) $sTarget = "_blank";
  1737. $sLabel = Str::pure2html($sValue);
  1738. if (strlen($sLabel) > 40)
  1739. {
  1740. // Truncate the length to about 40 characters, by removing the middle
  1741. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  1742. }
  1743. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  1744. }
  1745. public function GetValidationPattern()
  1746. {
  1747. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  1748. }
  1749. }
  1750. /**
  1751. * A blob is an ormDocument, it is stored as several columns in the database
  1752. *
  1753. * @package iTopORM
  1754. */
  1755. class AttributeBlob extends AttributeDefinition
  1756. {
  1757. static protected function ListExpectedParams()
  1758. {
  1759. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  1760. }
  1761. public function GetEditClass() {return "Document";}
  1762. public function IsDirectField() {return true;}
  1763. public function IsScalar() {return true;}
  1764. public function IsWritable() {return true;}
  1765. public function GetDefaultValue() {return "";}
  1766. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  1767. // Facilitate things: allow the user to Set the value from a string
  1768. public function MakeRealValue($proposedValue)
  1769. {
  1770. if (!is_object($proposedValue))
  1771. {
  1772. return new ormDocument($proposedValue, 'text/plain');
  1773. }
  1774. return $proposedValue;
  1775. }
  1776. public function GetSQLExpressions()
  1777. {
  1778. $aColumns = array();
  1779. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1780. $aColumns[''] = $this->GetCode().'_mimetype';
  1781. $aColumns['_data'] = $this->GetCode().'_data';
  1782. $aColumns['_filename'] = $this->GetCode().'_filename';
  1783. return $aColumns;
  1784. }
  1785. public function FromSQLToValue($aCols, $sPrefix = '')
  1786. {
  1787. if (!isset($aCols[$sPrefix]))
  1788. {
  1789. $sAvailable = implode(', ', array_keys($aCols));
  1790. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1791. }
  1792. $sMimeType = $aCols[$sPrefix];
  1793. if (!isset($aCols[$sPrefix.'_data']))
  1794. {
  1795. $sAvailable = implode(', ', array_keys($aCols));
  1796. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  1797. }
  1798. $data = $aCols[$sPrefix.'_data'];
  1799. if (!isset($aCols[$sPrefix.'_filename']))
  1800. {
  1801. $sAvailable = implode(', ', array_keys($aCols));
  1802. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  1803. }
  1804. $sFileName = $aCols[$sPrefix.'_filename'];
  1805. $value = new ormDocument($data, $sMimeType, $sFileName);
  1806. return $value;
  1807. }
  1808. public function GetSQLValues($value)
  1809. {
  1810. // #@# Optimization: do not load blobs anytime
  1811. // As per mySQL doc, selecting blob columns will prevent mySQL from
  1812. // using memory in case a temporary table has to be created
  1813. // (temporary tables created on disk)
  1814. // We will have to remove the blobs from the list of attributes when doing the select
  1815. // then the use of Get() should finalize the load
  1816. if ($value instanceOf ormDocument)
  1817. {
  1818. $aValues = array();
  1819. $aValues[$this->GetCode().'_data'] = $value->GetData();
  1820. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  1821. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  1822. }
  1823. else
  1824. {
  1825. $aValues = array();
  1826. $aValues[$this->GetCode().'_data'] = '';
  1827. $aValues[$this->GetCode().'_mimetype'] = '';
  1828. $aValues[$this->GetCode().'_filename'] = '';
  1829. }
  1830. return $aValues;
  1831. }
  1832. public function GetSQLColumns()
  1833. {
  1834. $aColumns = array();
  1835. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  1836. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  1837. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  1838. return $aColumns;
  1839. }
  1840. public function GetFilterDefinitions()
  1841. {
  1842. return array();
  1843. // still not working... see later...
  1844. return array(
  1845. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  1846. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  1847. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  1848. );
  1849. }
  1850. public function GetBasicFilterOperators()
  1851. {
  1852. return array();
  1853. }
  1854. public function GetBasicFilterLooseOperator()
  1855. {
  1856. return '=';
  1857. }
  1858. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1859. {
  1860. return 'true';
  1861. }
  1862. public function GetAsHTML($value)
  1863. {
  1864. if (is_object($value))
  1865. {
  1866. return $value->GetAsHTML();
  1867. }
  1868. }
  1869. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1870. {
  1871. return ''; // Not exportable in CSV !
  1872. }
  1873. public function GetAsXML($value)
  1874. {
  1875. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  1876. }
  1877. }
  1878. /**
  1879. * One way encrypted (hashed) password
  1880. */
  1881. class AttributeOneWayPassword extends AttributeDefinition
  1882. {
  1883. static protected function ListExpectedParams()
  1884. {
  1885. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  1886. }
  1887. public function GetEditClass() {return "One Way Password";}
  1888. public function IsDirectField() {return true;}
  1889. public function IsScalar() {return true;}
  1890. public function IsWritable() {return true;}
  1891. public function GetDefaultValue() {return "";}
  1892. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  1893. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  1894. public function MakeRealValue($proposedValue)
  1895. {
  1896. $oPassword = $proposedValue;
  1897. if (!is_object($oPassword))
  1898. {
  1899. $oPassword = new ormPassword('', '');
  1900. $oPassword->SetPassword($proposedValue);
  1901. }
  1902. return $oPassword;
  1903. }
  1904. public function GetSQLExpressions()
  1905. {
  1906. $aColumns = array();
  1907. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1908. $aColumns[''] = $this->GetCode().'_hash';
  1909. $aColumns['_salt'] = $this->GetCode().'_salt';
  1910. return $aColumns;
  1911. }
  1912. public function FromSQLToValue($aCols, $sPrefix = '')
  1913. {
  1914. if (!isset($aCols[$sPrefix]))
  1915. {
  1916. $sAvailable = implode(', ', array_keys($aCols));
  1917. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1918. }
  1919. $hashed = $aCols[$sPrefix];
  1920. if (!isset($aCols[$sPrefix.'_salt']))
  1921. {
  1922. $sAvailable = implode(', ', array_keys($aCols));
  1923. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  1924. }
  1925. $sSalt = $aCols[$sPrefix.'_salt'];
  1926. $value = new ormPassword($hashed, $sSalt);
  1927. return $value;
  1928. }
  1929. public function GetSQLValues($value)
  1930. {
  1931. // #@# Optimization: do not load blobs anytime
  1932. // As per mySQL doc, selecting blob columns will prevent mySQL from
  1933. // using memory in case a temporary table has to be created
  1934. // (temporary tables created on disk)
  1935. // We will have to remove the blobs from the list of attributes when doing the select
  1936. // then the use of Get() should finalize the load
  1937. if ($value instanceOf ormPassword)
  1938. {
  1939. $aValues = array();
  1940. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  1941. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  1942. }
  1943. else
  1944. {
  1945. $aValues = array();
  1946. $aValues[$this->GetCode().'_hash'] = '';
  1947. $aValues[$this->GetCode().'_salt'] = '';
  1948. }
  1949. return $aValues;
  1950. }
  1951. public function GetSQLColumns()
  1952. {
  1953. $aColumns = array();
  1954. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  1955. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  1956. return $aColumns;
  1957. }
  1958. public function GetFilterDefinitions()
  1959. {
  1960. return array();
  1961. // still not working... see later...
  1962. }
  1963. public function GetBasicFilterOperators()
  1964. {
  1965. return array();
  1966. }
  1967. public function GetBasicFilterLooseOperator()
  1968. {
  1969. return '=';
  1970. }
  1971. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1972. {
  1973. return 'true';
  1974. }
  1975. public function GetAsHTML($value)
  1976. {
  1977. if (is_object($value))
  1978. {
  1979. return $value->GetAsHTML();
  1980. }
  1981. }
  1982. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"')
  1983. {
  1984. return ''; // Not exportable in CSV
  1985. }
  1986. public function GetAsXML($value)
  1987. {
  1988. return ''; // Not exportable in XML
  1989. }
  1990. }
  1991. // Indexed array having two dimensions
  1992. class AttributeTable extends AttributeText
  1993. {
  1994. public function GetEditClass() {return "Text";}
  1995. protected function GetSQLCol() {return "TEXT";}
  1996. public function GetMaxSize()
  1997. {
  1998. return null;
  1999. }
  2000. // Facilitate things: allow the user to Set the value from a string
  2001. public function MakeRealValue($proposedValue)
  2002. {
  2003. if (!is_array($proposedValue))
  2004. {
  2005. return array(0 => array(0 => $proposedValue));
  2006. }
  2007. return $proposedValue;
  2008. }
  2009. public function FromSQLToValue($aCols, $sPrefix = '')
  2010. {
  2011. try
  2012. {
  2013. $value = @unserialize($aCols[$sPrefix.'']);
  2014. if ($value === false)
  2015. {
  2016. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  2017. }
  2018. }
  2019. catch(Exception $e)
  2020. {
  2021. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  2022. }
  2023. return $value;
  2024. }
  2025. public function GetSQLValues($value)
  2026. {
  2027. $aValues = array();
  2028. $aValues[$this->Get("sql")] = serialize($value);
  2029. return $aValues;
  2030. }
  2031. public function GetAsHTML($value)
  2032. {
  2033. if (!is_array($value))
  2034. {
  2035. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2036. }
  2037. if (count($value) == 0)
  2038. {
  2039. return "";
  2040. }
  2041. $sRes = "<TABLE class=\"listResults\">";
  2042. $sRes .= "<TBODY>";
  2043. foreach($value as $iRow => $aRawData)
  2044. {
  2045. $sRes .= "<TR>";
  2046. foreach ($aRawData as $iCol => $cell)
  2047. {
  2048. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  2049. $sRes .= "<TD>$sCell</TD>";
  2050. }
  2051. $sRes .= "</TR>";
  2052. }
  2053. $sRes .= "</TBODY>";
  2054. $sRes .= "</TABLE>";
  2055. return $sRes;
  2056. }
  2057. }
  2058. // The PHP value is a hash array, it is stored as a TEXT column
  2059. class AttributePropertySet extends AttributeTable
  2060. {
  2061. public function GetEditClass() {return "Text";}
  2062. protected function GetSQLCol() {return "TEXT";}
  2063. // Facilitate things: allow the user to Set the value from a string
  2064. public function MakeRealValue($proposedValue)
  2065. {
  2066. if (!is_array($proposedValue))
  2067. {
  2068. return array('?' => (string)$proposedValue);
  2069. }
  2070. return $proposedValue;
  2071. }
  2072. public function GetAsHTML($value)
  2073. {
  2074. if (!is_array($value))
  2075. {
  2076. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2077. }
  2078. if (count($value) == 0)
  2079. {
  2080. return "";
  2081. }
  2082. $sRes = "<TABLE class=\"listResults\">";
  2083. $sRes .= "<TBODY>";
  2084. foreach($value as $sProperty => $sValue)
  2085. {
  2086. $sRes .= "<TR>";
  2087. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  2088. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  2089. $sRes .= "</TR>";
  2090. }
  2091. $sRes .= "</TBODY>";
  2092. $sRes .= "</TABLE>";
  2093. return $sRes;
  2094. }
  2095. }
  2096. ?>