attributedef.class.inc.php 61 KB

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