attributedef.class.inc.php 65 KB

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