attributedef.class.inc.php 60 KB

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