attributedef.class.inc.php 61 KB

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