attributedef.class.inc.php 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Typology for the attributes
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. require_once('MyHelpers.class.inc.php');
  25. require_once('ormdocument.class.inc.php');
  26. require_once('ormpassword.class.inc.php');
  27. /**
  28. * MissingColumnException - sent if an attribute is being created but the column is missing in the row
  29. *
  30. * @package iTopORM
  31. */
  32. class MissingColumnException extends Exception
  33. {}
  34. /**
  35. * add some description here...
  36. *
  37. * @package iTopORM
  38. */
  39. define('EXTKEY_RELATIVE', 1);
  40. /**
  41. * add some description here...
  42. *
  43. * @package iTopORM
  44. */
  45. define('EXTKEY_ABSOLUTE', 2);
  46. /**
  47. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  48. *
  49. * @package iTopORM
  50. */
  51. define('DEL_MANUAL', 1);
  52. /**
  53. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  54. *
  55. * @package iTopORM
  56. */
  57. define('DEL_AUTO', 2);
  58. /**
  59. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  60. *
  61. * @package iTopORM
  62. */
  63. abstract class AttributeDefinition
  64. {
  65. public function GetType()
  66. {
  67. return Dict::S('Core:'.get_class($this));
  68. }
  69. public function GetTypeDesc()
  70. {
  71. return Dict::S('Core:'.get_class($this).'+');
  72. }
  73. abstract public function GetEditClass();
  74. protected $m_sCode;
  75. private $m_aParams = array();
  76. protected $m_sHostClass = '!undefined!';
  77. protected function Get($sParamName) {return $this->m_aParams[$sParamName];}
  78. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  79. protected function GetOptional($sParamName, $default)
  80. {
  81. if (array_key_exists($sParamName, $this->m_aParams))
  82. {
  83. return $this->m_aParams[$sParamName];
  84. }
  85. else
  86. {
  87. return $default;
  88. }
  89. }
  90. public function __construct($sCode, $aParams)
  91. {
  92. $this->m_sCode = $sCode;
  93. $this->m_aParams = $aParams;
  94. $this->ConsistencyCheck();
  95. }
  96. public function OverloadParams($aParams)
  97. {
  98. foreach ($aParams as $sParam => $value)
  99. {
  100. if (!array_key_exists($sParam, $this->m_aParams))
  101. {
  102. throw new CoreException("Unknown attribute definition parameter '$sParam', please select a value in {".implode(", ", array_keys($this->m_aParams))."}");
  103. }
  104. else
  105. {
  106. $this->m_aParams[$sParam] = $value;
  107. }
  108. }
  109. }
  110. public function SetHostClass($sHostClass)
  111. {
  112. $this->m_sHostClass = $sHostClass;
  113. }
  114. public function GetHostClass()
  115. {
  116. return $this->m_sHostClass;
  117. }
  118. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  119. // to be overloaded
  120. static protected function ListExpectedParams()
  121. {
  122. return array();
  123. }
  124. private function ConsistencyCheck()
  125. {
  126. // Check that any mandatory param has been specified
  127. //
  128. $aExpectedParams = $this->ListExpectedParams();
  129. foreach($aExpectedParams as $sParamName)
  130. {
  131. if (!array_key_exists($sParamName, $this->m_aParams))
  132. {
  133. $aBacktrace = debug_backtrace();
  134. $sTargetClass = $aBacktrace[2]["class"];
  135. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  136. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  137. }
  138. }
  139. }
  140. // table, key field, name field
  141. public function ListDBJoins()
  142. {
  143. return "";
  144. // e.g: return array("Site", "infrid", "name");
  145. }
  146. public function IsDirectField() {return false;}
  147. public function IsScalar() {return false;}
  148. public function IsLinkSet() {return false;}
  149. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  150. public function IsExternalField() {return false;}
  151. public function IsWritable() {return false;}
  152. public function IsNullAllowed() {return true;}
  153. public function GetCode() {return $this->m_sCode;}
  154. public function GetLabel() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $this->m_sCode);}
  155. public function GetLabel_Obsolete()
  156. {
  157. // Written for compatibility with a data model written prior to version 0.9.1
  158. if (array_key_exists('label', $this->m_aParams))
  159. {
  160. return $this->m_aParams['label'];
  161. }
  162. else
  163. {
  164. return $this->GetLabel();
  165. }
  166. }
  167. public function GetDescription() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', '');}
  168. public function GetHelpOnEdition() {return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', '');}
  169. public function GetDescription_Obsolete()
  170. {
  171. // Written for compatibility with a data model written prior to version 0.9.1
  172. if (array_key_exists('description', $this->m_aParams))
  173. {
  174. return $this->m_aParams['description'];
  175. }
  176. else
  177. {
  178. return $this->GetDescription();
  179. }
  180. }
  181. public function GetValuesDef() {return null;}
  182. public function GetPrerequisiteAttributes() {return array();}
  183. public function GetNullValue() {return null;}
  184. public function IsNull($proposedValue) {return is_null($proposedValue);}
  185. public function MakeRealValue($proposedValue) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  186. public function GetSQLExpressions($sPrefix = '') {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  187. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  188. public function GetSQLColumns() {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  189. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  190. public function RequiresIndex() {return false;}
  191. // Import - differs slightly from SQL input, but identical in most cases
  192. //
  193. public function GetImportColumns() {return $this->GetSQLColumns();}
  194. public function FromImportToValue($aCols, $sPrefix = '')
  195. {
  196. $aValues = array();
  197. foreach ($this->GetSQLExpressions($sPrefix) as $sAlias => $sExpr)
  198. {
  199. // This is working, based on the assumption that importable fields
  200. // are not computed fields => the expression is the name of a column
  201. $aValues[$sPrefix.$sAlias] = $aCols[$sExpr];
  202. }
  203. return $this->FromSQLToValue($aValues, $sPrefix);
  204. }
  205. public function GetValidationPattern()
  206. {
  207. return '';
  208. }
  209. public function CheckFormat($value)
  210. {
  211. return true;
  212. }
  213. public function GetMaxSize()
  214. {
  215. return null;
  216. }
  217. public function MakeValue()
  218. {
  219. $sComputeFunc = $this->Get("compute_func");
  220. if (empty($sComputeFunc)) return null;
  221. return call_user_func($sComputeFunc);
  222. }
  223. abstract public function GetDefaultValue();
  224. //
  225. // To be overloaded in subclasses
  226. //
  227. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  228. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  229. //abstract protected GetBasicFilterHTMLInput();
  230. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  231. public function GetFilterDefinitions()
  232. {
  233. return array();
  234. }
  235. public function GetEditValue($sValue)
  236. {
  237. return (string)$sValue;
  238. }
  239. public function GetAsHTML($sValue, $oHostObject = null)
  240. {
  241. return Str::pure2html((string)$sValue);
  242. }
  243. public function GetAsXML($sValue, $oHostObject = null)
  244. {
  245. return Str::pure2xml((string)$sValue);
  246. }
  247. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  248. {
  249. return (string)$sValue;
  250. }
  251. public function GetAllowedValues($aArgs = array(), $sContains = '')
  252. {
  253. $oValSetDef = $this->GetValuesDef();
  254. if (!$oValSetDef) return null;
  255. return $oValSetDef->GetValues($aArgs, $sContains);
  256. }
  257. /**
  258. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  259. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  260. * does nothing special, and just calls the default (loose) operator
  261. * @param string $sSearchText The search string to analyze for smart patterns
  262. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  263. * @param Hash $aParams Values of the query parameters
  264. * @return Expression The search condition to be added (AND) to the current search
  265. */
  266. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  267. {
  268. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  269. $oRightExpr = new VariableExpression($sParamName);
  270. $sOperator = $this->GetBasicFilterLooseOperator();
  271. switch ($sOperator)
  272. {
  273. case 'Contains':
  274. $aParams[$sParamName] = "%$sSearchText%";
  275. $sSQLOperator = 'LIKE';
  276. break;
  277. default:
  278. $sSQLOperator = $sOperator;
  279. $aParams[$sParamName] = $sSearchText;
  280. }
  281. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  282. return $oNewCondition;
  283. }
  284. }
  285. /**
  286. * Set of objects directly linked to an object, and being part of its definition
  287. *
  288. * @package iTopORM
  289. */
  290. class AttributeLinkedSet extends AttributeDefinition
  291. {
  292. static protected function ListExpectedParams()
  293. {
  294. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  295. }
  296. public function GetEditClass() {return "List";}
  297. public function IsWritable() {return true;}
  298. public function IsLinkSet() {return true;}
  299. public function IsIndirect() {return false;}
  300. public function GetValuesDef() {return $this->Get("allowed_values");}
  301. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  302. public function GetDefaultValue($aArgs = array())
  303. {
  304. // Note: so far, this feature is a prototype,
  305. // later, the argument 'this' should always be present in the arguments
  306. //
  307. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  308. {
  309. $aValues = $this->Get('default_value')->GetValues($aArgs);
  310. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  311. return $oSet;
  312. }
  313. else
  314. {
  315. return DBObjectSet::FromScratch($this->Get('linked_class'));
  316. }
  317. }
  318. public function GetLinkedClass() {return $this->Get('linked_class');}
  319. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  320. public function GetBasicFilterOperators() {return array();}
  321. public function GetBasicFilterLooseOperator() {return '';}
  322. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  323. public function GetAsHTML($sValue, $oHostObject = null)
  324. {
  325. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  326. {
  327. $sValue->Rewind();
  328. $aItems = array();
  329. while ($oObj = $sValue->Fetch())
  330. {
  331. // Show only relevant information (hide the external key to the current object)
  332. $aAttributes = array();
  333. foreach(MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef)
  334. {
  335. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  336. if ($oAttDef->IsExternalField()) continue;
  337. $sAttValue = $oObj->GetAsHTML($sAttCode);
  338. if (strlen($sAttValue) > 0)
  339. {
  340. $aAttributes[] = $sAttValue;
  341. }
  342. }
  343. $sAttributes = implode(', ', $aAttributes);
  344. $aItems[] = $sAttributes;
  345. }
  346. return implode('<br/>', $aItems);
  347. }
  348. return null;
  349. }
  350. public function GetAsXML($sValue, $oHostObject = null)
  351. {
  352. return "Sorry, no yet implemented";
  353. }
  354. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  355. {
  356. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  357. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  358. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  359. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  360. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  361. {
  362. $sValue->Rewind();
  363. $aItems = array();
  364. while ($oObj = $sValue->Fetch())
  365. {
  366. // Show only relevant information (hide the external key to the current object)
  367. $aAttributes = array();
  368. foreach(MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef)
  369. {
  370. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  371. if ($oAttDef->IsExternalField()) continue;
  372. if (!$oAttDef->IsDirectField()) continue;
  373. if (!$oAttDef->IsScalar()) continue;
  374. $sAttValue = $oObj->GetAsCSV($sAttCode, $sSepValue, '');
  375. if (strlen($sAttValue) > 0)
  376. {
  377. $sAttributeData = str_replace($sAttributeQualifier, $sAttributeQualifier.$sAttributeQualifier, $sAttCode.$sSepValue.$sAttValue);
  378. $aAttributes[] = $sAttributeQualifier.$sAttributeData.$sAttributeQualifier;
  379. }
  380. }
  381. $sAttributes = implode($sSepAttribute, $aAttributes);
  382. $aItems[] = $sAttributes;
  383. }
  384. $sRes = implode($sSepItem, $aItems);
  385. }
  386. else
  387. {
  388. $sRes = '';
  389. }
  390. $sRes = str_replace($sTextQualifier, $sTextQualifier.$sTextQualifier, $sRes);
  391. $sRes = $sTextQualifier.$sRes.$sTextQualifier;
  392. return $sRes;
  393. }
  394. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  395. // Specific to this kind of attribute : transform a string into a value
  396. public function MakeValueFromString($sProposedValue, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  397. {
  398. if (is_null($sSepItem))
  399. {
  400. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  401. }
  402. if (is_null($sSepAttribute))
  403. {
  404. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  405. }
  406. if (is_null($sSepValue))
  407. {
  408. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  409. }
  410. if (is_null($sAttributeQualifier))
  411. {
  412. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  413. }
  414. $sTargetClass = $this->Get('linked_class');
  415. $sInput = str_replace($sSepItem, "\n", $sProposedValue);
  416. $oCSVParser = new CSVParser($sInput, $sSepAttribute, $sAttributeQualifier);
  417. $aInput = $oCSVParser->ToArray(0 /* do not skip lines */);
  418. $aLinks = array();
  419. foreach($aInput as $aRow)
  420. {
  421. $aNewRow = array();
  422. $oLink = MetaModel::NewObject($sTargetClass);
  423. $aExtKeys = array();
  424. foreach($aRow as $sCell)
  425. {
  426. $iSepPos = strpos($sCell, $sSepValue);
  427. if ($iSepPos === false)
  428. {
  429. // Houston...
  430. throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell));
  431. }
  432. $sAttCode = trim(substr($sCell, 0, $iSepPos));
  433. $sValue = substr($sCell, $iSepPos + strlen($sSepValue));
  434. if (preg_match('/^(.+)->(.+)$/', $sAttCode, $aMatches))
  435. {
  436. $sKeyAttCode = $aMatches[1];
  437. $sRemoteAttCode = $aMatches[2];
  438. $aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue;
  439. if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode))
  440. {
  441. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sKeyAttCode));
  442. }
  443. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  444. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  445. if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode))
  446. {
  447. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode));
  448. }
  449. }
  450. else
  451. {
  452. if(!MetaModel::IsValidAttCode($sTargetClass, $sAttCode))
  453. {
  454. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sAttCode));
  455. }
  456. $oLink->Set($sAttCode, $sValue);
  457. }
  458. }
  459. // Set external keys from search conditions
  460. foreach ($aExtKeys as $sKeyAttCode => $aReconciliation)
  461. {
  462. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  463. $sKeyClass = $oKeyAttDef->GetTargetClass();
  464. $oExtKeyFilter = new CMDBSearchFilter($sKeyClass);
  465. $aReconciliationDesc = array();
  466. foreach($aReconciliation as $sRemoteAttCode => $sValue)
  467. {
  468. $oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '=');
  469. $aReconciliationDesc[] = "$sRemoteAttCode=$sValue";
  470. }
  471. $oExtKeySet = new CMDBObjectSet($oExtKeyFilter);
  472. switch($oExtKeySet->Count())
  473. {
  474. case 0:
  475. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  476. throw new CoreException("Found no match", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  477. break;
  478. case 1:
  479. $oRemoteObj = $oExtKeySet->Fetch();
  480. $oLink->Set($sKeyAttCode, $oRemoteObj->GetKey());
  481. break;
  482. default:
  483. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  484. throw new CoreException("Found several matches", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  485. // Found several matches, ambiguous
  486. }
  487. }
  488. $aLinks[] = $oLink;
  489. }
  490. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  491. return $oSet;
  492. }
  493. }
  494. /**
  495. * Set of objects linked to an object (n-n), and being part of its definition
  496. *
  497. * @package iTopORM
  498. */
  499. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  500. {
  501. static protected function ListExpectedParams()
  502. {
  503. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  504. }
  505. public function IsIndirect() {return true;}
  506. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  507. public function GetEditClass() {return "LinkedSet";}
  508. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  509. }
  510. /**
  511. * Abstract class implementing default filters for a DB column
  512. *
  513. * @package iTopORM
  514. */
  515. class AttributeDBFieldVoid extends AttributeDefinition
  516. {
  517. static protected function ListExpectedParams()
  518. {
  519. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  520. }
  521. // To be overriden, used in GetSQLColumns
  522. protected function GetSQLCol() {return "VARCHAR(255)";}
  523. public function GetEditClass() {return "String";}
  524. public function GetValuesDef() {return $this->Get("allowed_values");}
  525. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  526. public function IsDirectField() {return true;}
  527. public function IsScalar() {return true;}
  528. public function IsWritable() {return true;}
  529. public function GetSQLExpr() {return $this->Get("sql");}
  530. public function GetDefaultValue() {return $this->MakeRealValue("");}
  531. public function IsNullAllowed() {return false;}
  532. //
  533. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  534. public function GetSQLExpressions($sPrefix = '')
  535. {
  536. $aColumns = array();
  537. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  538. $aColumns[''] = $this->Get("sql");
  539. return $aColumns;
  540. }
  541. public function FromSQLToValue($aCols, $sPrefix = '')
  542. {
  543. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  544. return $value;
  545. }
  546. public function GetSQLValues($value)
  547. {
  548. $aValues = array();
  549. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  550. return $aValues;
  551. }
  552. public function GetSQLColumns()
  553. {
  554. $aColumns = array();
  555. $aColumns[$this->Get("sql")] = $this->GetSQLCol();
  556. return $aColumns;
  557. }
  558. public function GetFilterDefinitions()
  559. {
  560. return array($this->GetCode() => new FilterFromAttribute($this));
  561. }
  562. public function GetBasicFilterOperators()
  563. {
  564. return array("="=>"equals", "!="=>"differs from");
  565. }
  566. public function GetBasicFilterLooseOperator()
  567. {
  568. return "=";
  569. }
  570. public function GetBasicFilterSQLExpr($sOpCode, $value)
  571. {
  572. $sQValue = CMDBSource::Quote($value);
  573. switch ($sOpCode)
  574. {
  575. case '!=':
  576. return $this->GetSQLExpr()." != $sQValue";
  577. break;
  578. case '=':
  579. default:
  580. return $this->GetSQLExpr()." = $sQValue";
  581. }
  582. }
  583. }
  584. /**
  585. * Base class for all kind of DB attributes, with the exception of external keys
  586. *
  587. * @package iTopORM
  588. */
  589. class AttributeDBField extends AttributeDBFieldVoid
  590. {
  591. static protected function ListExpectedParams()
  592. {
  593. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  594. }
  595. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"));}
  596. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  597. }
  598. /**
  599. * Map an integer column to an attribute
  600. *
  601. * @package iTopORM
  602. */
  603. class AttributeInteger extends AttributeDBField
  604. {
  605. static protected function ListExpectedParams()
  606. {
  607. return parent::ListExpectedParams();
  608. //return array_merge(parent::ListExpectedParams(), array());
  609. }
  610. public function GetEditClass() {return "String";}
  611. protected function GetSQLCol() {return "INT(11)";}
  612. public function GetValidationPattern()
  613. {
  614. return "^[0-9]+$";
  615. }
  616. public function GetBasicFilterOperators()
  617. {
  618. return array(
  619. "!="=>"differs from",
  620. "="=>"equals",
  621. ">"=>"greater (strict) than",
  622. ">="=>"greater than",
  623. "<"=>"less (strict) than",
  624. "<="=>"less than",
  625. "in"=>"in"
  626. );
  627. }
  628. public function GetBasicFilterLooseOperator()
  629. {
  630. // Unless we implement an "equals approximately..." or "same order of magnitude"
  631. return "=";
  632. }
  633. public function GetBasicFilterSQLExpr($sOpCode, $value)
  634. {
  635. $sQValue = CMDBSource::Quote($value);
  636. switch ($sOpCode)
  637. {
  638. case '!=':
  639. return $this->GetSQLExpr()." != $sQValue";
  640. break;
  641. case '>':
  642. return $this->GetSQLExpr()." > $sQValue";
  643. break;
  644. case '>=':
  645. return $this->GetSQLExpr()." >= $sQValue";
  646. break;
  647. case '<':
  648. return $this->GetSQLExpr()." < $sQValue";
  649. break;
  650. case '<=':
  651. return $this->GetSQLExpr()." <= $sQValue";
  652. break;
  653. case 'in':
  654. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  655. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  656. break;
  657. case '=':
  658. default:
  659. return $this->GetSQLExpr()." = \"$value\"";
  660. }
  661. }
  662. public function GetNullValue()
  663. {
  664. return null;
  665. }
  666. public function IsNull($proposedValue)
  667. {
  668. return is_null($proposedValue);
  669. }
  670. public function MakeRealValue($proposedValue)
  671. {
  672. if (is_null($proposedValue)) return null;
  673. if ($proposedValue === '') return null; // 0 is transformed into '' !
  674. return (int)$proposedValue;
  675. }
  676. public function ScalarToSQL($value)
  677. {
  678. assert(is_numeric($value) || is_null($value));
  679. return $value; // supposed to be an int
  680. }
  681. }
  682. /**
  683. * Map a decimal value column (suitable for financial computations) to an attribute
  684. * internally in PHP such numbers are represented as string. Should you want to perform
  685. * a calculation on them, it is recommended to use the BC Math functions in order to
  686. * retain the precision
  687. *
  688. * @package iTopORM
  689. */
  690. class AttributeDecimal extends AttributeDBField
  691. {
  692. static protected function ListExpectedParams()
  693. {
  694. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  695. }
  696. public function GetEditClass() {return "String";}
  697. protected function GetSQLCol() {return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")";}
  698. public function GetValidationPattern()
  699. {
  700. $iNbDigits = $this->Get('digits');
  701. $iPrecision = $this->Get('decimals');
  702. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  703. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  704. }
  705. public function GetBasicFilterOperators()
  706. {
  707. return array(
  708. "!="=>"differs from",
  709. "="=>"equals",
  710. ">"=>"greater (strict) than",
  711. ">="=>"greater than",
  712. "<"=>"less (strict) than",
  713. "<="=>"less than",
  714. "in"=>"in"
  715. );
  716. }
  717. public function GetBasicFilterLooseOperator()
  718. {
  719. // Unless we implement an "equals approximately..." or "same order of magnitude"
  720. return "=";
  721. }
  722. public function GetBasicFilterSQLExpr($sOpCode, $value)
  723. {
  724. $sQValue = CMDBSource::Quote($value);
  725. switch ($sOpCode)
  726. {
  727. case '!=':
  728. return $this->GetSQLExpr()." != $sQValue";
  729. break;
  730. case '>':
  731. return $this->GetSQLExpr()." > $sQValue";
  732. break;
  733. case '>=':
  734. return $this->GetSQLExpr()." >= $sQValue";
  735. break;
  736. case '<':
  737. return $this->GetSQLExpr()." < $sQValue";
  738. break;
  739. case '<=':
  740. return $this->GetSQLExpr()." <= $sQValue";
  741. break;
  742. case 'in':
  743. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  744. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  745. break;
  746. case '=':
  747. default:
  748. return $this->GetSQLExpr()." = \"$value\"";
  749. }
  750. }
  751. public function GetNullValue()
  752. {
  753. return null;
  754. }
  755. public function IsNull($proposedValue)
  756. {
  757. return is_null($proposedValue);
  758. }
  759. public function MakeRealValue($proposedValue)
  760. {
  761. if (is_null($proposedValue)) return null;
  762. if ($proposedValue == '') return null;
  763. return (string)$proposedValue;
  764. }
  765. public function ScalarToSQL($value)
  766. {
  767. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  768. return (string)$value; // treated as a string
  769. }
  770. }
  771. /**
  772. * Map a boolean column to an attribute
  773. *
  774. * @package iTopORM
  775. */
  776. class AttributeBoolean extends AttributeInteger
  777. {
  778. static protected function ListExpectedParams()
  779. {
  780. return parent::ListExpectedParams();
  781. //return array_merge(parent::ListExpectedParams(), array());
  782. }
  783. public function GetEditClass() {return "Integer";}
  784. protected function GetSQLCol() {return "TINYINT(1)";}
  785. public function MakeRealValue($proposedValue)
  786. {
  787. if (is_null($proposedValue)) return null;
  788. if ($proposedValue === '') return null;
  789. if ((int)$proposedValue) return true;
  790. return false;
  791. }
  792. public function ScalarToSQL($value)
  793. {
  794. if ($value) return 1;
  795. return 0;
  796. }
  797. }
  798. /**
  799. * Map a varchar column (size < ?) to an attribute
  800. *
  801. * @package iTopORM
  802. */
  803. class AttributeString extends AttributeDBField
  804. {
  805. static protected function ListExpectedParams()
  806. {
  807. return parent::ListExpectedParams();
  808. //return array_merge(parent::ListExpectedParams(), array());
  809. }
  810. public function GetEditClass() {return "String";}
  811. protected function GetSQLCol() {return "VARCHAR(255)";}
  812. public function CheckFormat($value)
  813. {
  814. $sRegExp = $this->GetValidationPattern();
  815. if (empty($sRegExp))
  816. {
  817. return true;
  818. }
  819. else
  820. {
  821. $sRegExp = str_replace('/', '\\/', $sRegExp);
  822. return preg_match("/$sRegExp/", $value);
  823. }
  824. }
  825. public function GetMaxSize()
  826. {
  827. return 255;
  828. }
  829. public function GetBasicFilterOperators()
  830. {
  831. return array(
  832. "="=>"equals",
  833. "!="=>"differs from",
  834. "Like"=>"equals (no case)",
  835. "NotLike"=>"differs from (no case)",
  836. "Contains"=>"contains",
  837. "Begins with"=>"begins with",
  838. "Finishes with"=>"finishes with"
  839. );
  840. }
  841. public function GetBasicFilterLooseOperator()
  842. {
  843. return "Contains";
  844. }
  845. public function GetBasicFilterSQLExpr($sOpCode, $value)
  846. {
  847. $sQValue = CMDBSource::Quote($value);
  848. switch ($sOpCode)
  849. {
  850. case '=':
  851. case '!=':
  852. return $this->GetSQLExpr()." $sOpCode $sQValue";
  853. case 'Begins with':
  854. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  855. case 'Finishes with':
  856. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  857. case 'Contains':
  858. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  859. case 'NotLike':
  860. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  861. case 'Like':
  862. default:
  863. return $this->GetSQLExpr()." LIKE $sQValue";
  864. }
  865. }
  866. public function GetNullValue()
  867. {
  868. return '';
  869. }
  870. public function IsNull($proposedValue)
  871. {
  872. return ($proposedValue == '');
  873. }
  874. public function MakeRealValue($proposedValue)
  875. {
  876. if (is_null($proposedValue)) return '';
  877. return (string)$proposedValue;
  878. }
  879. public function ScalarToSQL($value)
  880. {
  881. if (!is_string($value) && !is_null($value))
  882. {
  883. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  884. }
  885. return $value;
  886. }
  887. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  888. {
  889. $sFrom = array("\r\n", $sTextQualifier);
  890. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  891. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  892. return $sTextQualifier.$sEscaped.$sTextQualifier;
  893. }
  894. }
  895. /**
  896. * An attibute that matches an object class
  897. *
  898. * @package iTopORM
  899. */
  900. class AttributeClass extends AttributeString
  901. {
  902. static protected function ListExpectedParams()
  903. {
  904. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  905. }
  906. public function __construct($sCode, $aParams)
  907. {
  908. $this->m_sCode = $sCode;
  909. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  910. parent::__construct($sCode, $aParams);
  911. }
  912. public function GetDefaultValue()
  913. {
  914. $sDefault = parent::GetDefaultValue();
  915. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  916. {
  917. // For this kind of attribute specifying null as default value
  918. // is authorized even if null is not allowed
  919. // Pick the first one...
  920. $aClasses = $this->GetAllowedValues();
  921. $sDefault = key($aClasses);
  922. }
  923. return $sDefault;
  924. }
  925. public function GetAsHTML($sValue, $oHostObject = null)
  926. {
  927. if (empty($sValue)) return '';
  928. return MetaModel::GetName($sValue);
  929. }
  930. public function RequiresIndex()
  931. {
  932. return true;
  933. }
  934. public function GetBasicFilterLooseOperator()
  935. {
  936. return '=';
  937. }
  938. }
  939. /**
  940. * An attibute that matches one of the language codes availables in the dictionnary
  941. *
  942. * @package iTopORM
  943. */
  944. class AttributeApplicationLanguage extends AttributeString
  945. {
  946. static protected function ListExpectedParams()
  947. {
  948. return parent::ListExpectedParams();
  949. }
  950. public function __construct($sCode, $aParams)
  951. {
  952. $this->m_sCode = $sCode;
  953. $aAvailableLanguages = Dict::GetLanguages();
  954. $aLanguageCodes = array();
  955. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  956. {
  957. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  958. }
  959. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  960. parent::__construct($sCode, $aParams);
  961. }
  962. public function RequiresIndex()
  963. {
  964. return true;
  965. }
  966. public function GetBasicFilterLooseOperator()
  967. {
  968. return '=';
  969. }
  970. }
  971. /**
  972. * The attribute dedicated to the finalclass automatic attribute
  973. *
  974. * @package iTopORM
  975. */
  976. class AttributeFinalClass extends AttributeString
  977. {
  978. public function __construct($sCode, $aParams)
  979. {
  980. $this->m_sCode = $sCode;
  981. $aParams["allowed_values"] = null;
  982. parent::__construct($sCode, $aParams);
  983. $this->m_sValue = $this->Get("default_value");
  984. }
  985. public function IsWritable()
  986. {
  987. return false;
  988. }
  989. public function RequiresIndex()
  990. {
  991. return true;
  992. }
  993. public function SetFixedValue($sValue)
  994. {
  995. $this->m_sValue = $sValue;
  996. }
  997. public function GetDefaultValue()
  998. {
  999. return $this->m_sValue;
  1000. }
  1001. public function GetAsHTML($sValue, $oHostObject = null)
  1002. {
  1003. if (empty($sValue)) return '';
  1004. return MetaModel::GetName($sValue);
  1005. }
  1006. public function GetBasicFilterLooseOperator()
  1007. {
  1008. return '=';
  1009. }
  1010. }
  1011. /**
  1012. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  1013. *
  1014. * @package iTopORM
  1015. */
  1016. class AttributePassword extends AttributeString
  1017. {
  1018. static protected function ListExpectedParams()
  1019. {
  1020. return parent::ListExpectedParams();
  1021. //return array_merge(parent::ListExpectedParams(), array());
  1022. }
  1023. public function GetEditClass() {return "Password";}
  1024. protected function GetSQLCol() {return "VARCHAR(64)";}
  1025. public function GetMaxSize()
  1026. {
  1027. return 64;
  1028. }
  1029. public function GetFilterDefinitions()
  1030. {
  1031. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  1032. // not allowed to search on passwords!
  1033. return array();
  1034. }
  1035. public function GetAsHTML($sValue, $oHostObject = null)
  1036. {
  1037. if (strlen($sValue) == 0)
  1038. {
  1039. return '';
  1040. }
  1041. else
  1042. {
  1043. return '******';
  1044. }
  1045. }
  1046. }
  1047. /**
  1048. * Map a text column (size < 255) to an attribute that is encrypted in the database
  1049. * The encryption is based on a key set per iTop instance. Thus if you export your
  1050. * database (in SQL) to someone else without providing the key at the same time
  1051. * the encrypted fields will remain encrypted
  1052. *
  1053. * @package iTopORM
  1054. */
  1055. class AttributeEncryptedString extends AttributeString
  1056. {
  1057. static $sKey = null; // Encryption key used for all encrypted fields
  1058. public function __construct($sCode, $aParams)
  1059. {
  1060. parent::__construct($sCode, $aParams);
  1061. if (self::$sKey == null)
  1062. {
  1063. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1064. }
  1065. }
  1066. protected function GetSQLCol() {return "TINYBLOB";}
  1067. public function GetMaxSize()
  1068. {
  1069. return 255;
  1070. }
  1071. public function GetFilterDefinitions()
  1072. {
  1073. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  1074. // not allowed to search on encrypted fields !
  1075. return array();
  1076. }
  1077. public function MakeRealValue($proposedValue)
  1078. {
  1079. if (is_null($proposedValue)) return null;
  1080. return (string)$proposedValue;
  1081. }
  1082. /**
  1083. * Decrypt the value when reading from the database
  1084. */
  1085. public function FromSQLToValue($aCols, $sPrefix = '')
  1086. {
  1087. $oSimpleCrypt = new SimpleCrypt();
  1088. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  1089. return $sValue;
  1090. }
  1091. /**
  1092. * Encrypt the value before storing it in the database
  1093. */
  1094. public function GetSQLValues($value)
  1095. {
  1096. $oSimpleCrypt = new SimpleCrypt();
  1097. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  1098. $aValues = array();
  1099. $aValues[$this->Get("sql")] = $encryptedValue;
  1100. return $aValues;
  1101. }
  1102. }
  1103. /**
  1104. * Map a text column (size > ?) to an attribute
  1105. *
  1106. * @package iTopORM
  1107. */
  1108. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  1109. class AttributeText extends AttributeString
  1110. {
  1111. public function GetEditClass() {return "Text";}
  1112. protected function GetSQLCol() {return "TEXT";}
  1113. public function GetMaxSize()
  1114. {
  1115. // Is there a way to know the current limitation for mysql?
  1116. // See mysql_field_len()
  1117. return 65535;
  1118. }
  1119. public function GetAsHTML($sValue, $oHostObject = null)
  1120. {
  1121. $sValue = parent::GetAsHTML($sValue);
  1122. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1123. {
  1124. foreach($aAllMatches as $iPos => $aMatches)
  1125. {
  1126. $sClass = $aMatches[1];
  1127. $sName = $aMatches[2];
  1128. if (MetaModel::IsValidClass($sClass))
  1129. {
  1130. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  1131. if (is_object($oObj))
  1132. {
  1133. // Propose a std link to the object
  1134. $sValue = str_replace($aMatches[0], $oObj->GetHyperlink(), $sValue);
  1135. }
  1136. else
  1137. {
  1138. // Propose a std link to the object
  1139. $sClassLabel = MetaModel::GetName($sClass);
  1140. $sValue = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sValue);
  1141. // Later: propose a link to create a new object
  1142. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  1143. //$sValue = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="./UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sValue);
  1144. }
  1145. }
  1146. }
  1147. }
  1148. return str_replace("\n", "<br>\n", $sValue);
  1149. }
  1150. public function GetEditValue($sValue)
  1151. {
  1152. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1153. {
  1154. foreach($aAllMatches as $iPos => $aMatches)
  1155. {
  1156. $sClass = $aMatches[1];
  1157. $sName = $aMatches[2];
  1158. if (MetaModel::IsValidClass($sClass))
  1159. {
  1160. $sClassLabel = MetaModel::GetName($sClass);
  1161. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  1162. }
  1163. }
  1164. }
  1165. return $sValue;
  1166. }
  1167. public function MakeRealValue($proposedValue)
  1168. {
  1169. $sValue = $proposedValue;
  1170. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1171. {
  1172. foreach($aAllMatches as $iPos => $aMatches)
  1173. {
  1174. $sClassLabel = $aMatches[1];
  1175. $sName = $aMatches[2];
  1176. if (!MetaModel::IsValidClass($sClassLabel))
  1177. {
  1178. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  1179. if ($sClass)
  1180. {
  1181. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  1182. }
  1183. }
  1184. }
  1185. }
  1186. return $sValue;
  1187. }
  1188. public function GetAsXML($value, $oHostObject = null)
  1189. {
  1190. return Str::pure2xml($value);
  1191. }
  1192. }
  1193. /**
  1194. * Map a log to an attribute
  1195. *
  1196. * @package iTopORM
  1197. */
  1198. class AttributeLongText extends AttributeText
  1199. {
  1200. protected function GetSQLCol() {return "LONGTEXT";}
  1201. public function GetMaxSize()
  1202. {
  1203. // Is there a way to know the current limitation for mysql?
  1204. // See mysql_field_len()
  1205. return 65535*1024; // Limited... still 64 Mb!
  1206. }
  1207. }
  1208. /**
  1209. * Map a text column (size > ?), containing HTML code, to an attribute
  1210. *
  1211. * @package iTopORM
  1212. */
  1213. class AttributeHTML extends AttributeText
  1214. {
  1215. public function GetEditClass() {return "HTML";}
  1216. public function GetAsHTML($sValue, $oHostObject = null)
  1217. {
  1218. return $sValue;
  1219. }
  1220. }
  1221. /**
  1222. * Specialization of a string: email
  1223. *
  1224. * @package iTopORM
  1225. */
  1226. class AttributeEmailAddress extends AttributeString
  1227. {
  1228. public function GetValidationPattern()
  1229. {
  1230. // return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  1231. return "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$";
  1232. }
  1233. public function GetAsHTML($sValue, $oHostObject = null)
  1234. {
  1235. if (empty($sValue)) return '';
  1236. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  1237. }
  1238. }
  1239. /**
  1240. * Specialization of a string: IP address
  1241. *
  1242. * @package iTopORM
  1243. */
  1244. class AttributeIPAddress extends AttributeString
  1245. {
  1246. public function GetValidationPattern()
  1247. {
  1248. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  1249. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  1250. }
  1251. }
  1252. /**
  1253. * Specialization of a string: OQL expression
  1254. *
  1255. * @package iTopORM
  1256. */
  1257. class AttributeOQL extends AttributeText
  1258. {
  1259. }
  1260. /**
  1261. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1262. *
  1263. * @package iTopORM
  1264. */
  1265. class AttributeTemplateString extends AttributeString
  1266. {
  1267. }
  1268. /**
  1269. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1270. *
  1271. * @package iTopORM
  1272. */
  1273. class AttributeTemplateText extends AttributeText
  1274. {
  1275. }
  1276. /**
  1277. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1278. *
  1279. * @package iTopORM
  1280. */
  1281. class AttributeTemplateHTML extends AttributeText
  1282. {
  1283. public function GetEditClass() {return "HTML";}
  1284. public function GetAsHTML($sValue, $oHostObject = null)
  1285. {
  1286. return $sValue;
  1287. }
  1288. }
  1289. /**
  1290. * Specialization of a text: wiki formatting
  1291. *
  1292. * @package iTopORM
  1293. */
  1294. class AttributeWikiText extends AttributeText
  1295. {
  1296. public function GetAsHTML($value, $oHostObject = null)
  1297. {
  1298. // [SELECT xxxx.... [label]] => hyperlink to a result list
  1299. // {SELECT xxxx.... [label]} => result list displayed inline
  1300. // [myclass/nnn [label]] => hyperlink to an object
  1301. // {myclass/nnn/attcode} => attribute displayed inline
  1302. // etc.
  1303. return parent::GetAsHTML($value);
  1304. }
  1305. }
  1306. /**
  1307. * Map a enum column to an attribute
  1308. *
  1309. * @package iTopORM
  1310. */
  1311. class AttributeEnum extends AttributeString
  1312. {
  1313. static protected function ListExpectedParams()
  1314. {
  1315. return parent::ListExpectedParams();
  1316. //return array_merge(parent::ListExpectedParams(), array());
  1317. }
  1318. public function GetEditClass() {return "String";}
  1319. protected function GetSQLCol()
  1320. {
  1321. $oValDef = $this->GetValuesDef();
  1322. if ($oValDef)
  1323. {
  1324. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  1325. }
  1326. else
  1327. {
  1328. $aValues = array();
  1329. }
  1330. if (count($aValues) > 0)
  1331. {
  1332. // The syntax used here do matters
  1333. // In particular, I had to remove unnecessary spaces to
  1334. // make sure that this string will match the field type returned by the DB
  1335. // (used to perform a comparison between the current DB format and the data model)
  1336. return "ENUM(".implode(",", $aValues).")";
  1337. }
  1338. else
  1339. {
  1340. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  1341. }
  1342. }
  1343. public function ScalarToSQL($value)
  1344. {
  1345. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  1346. // but that wasn't working for enums, because '' is NOT one of the allowed values
  1347. // that's why a null value must be forced to a real null
  1348. $value = parent::ScalarToSQL($value);
  1349. if ($this->IsNull($value))
  1350. {
  1351. return null;
  1352. }
  1353. else
  1354. {
  1355. return $value;
  1356. }
  1357. }
  1358. public function RequiresIndex()
  1359. {
  1360. return false;
  1361. }
  1362. public function GetBasicFilterOperators()
  1363. {
  1364. return parent::GetBasicFilterOperators();
  1365. }
  1366. public function GetBasicFilterLooseOperator()
  1367. {
  1368. return '=';
  1369. }
  1370. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1371. {
  1372. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1373. }
  1374. public function GetAsHTML($sValue, $oHostObject = null)
  1375. {
  1376. if (is_null($sValue))
  1377. {
  1378. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1379. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  1380. }
  1381. else
  1382. {
  1383. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1384. }
  1385. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', $sValue);
  1386. // later, we could imagine a detailed description in the title
  1387. return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  1388. }
  1389. public function GetEditValue($sValue)
  1390. {
  1391. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, $sValue);
  1392. return $sLabel;
  1393. }
  1394. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1395. {
  1396. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  1397. if (is_null($aRawValues)) return null;
  1398. $aLocalizedValues = array();
  1399. foreach ($aRawValues as $sKey => $sValue)
  1400. {
  1401. $aLocalizedValues[$sKey] = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sKey, $sKey);
  1402. }
  1403. return $aLocalizedValues;
  1404. }
  1405. /**
  1406. * Processes the input value to align it with the values supported
  1407. * by this type of attribute. In this case: turns empty strings into nulls
  1408. * @param mixed $proposedValue The value to be set for the attribute
  1409. * @return mixed The actual value that will be set
  1410. */
  1411. public function MakeRealValue($proposedValue)
  1412. {
  1413. if ($proposedValue == '') return null;
  1414. return parent::MakeRealValue($proposedValue);
  1415. }
  1416. }
  1417. /**
  1418. * Map a date+time column to an attribute
  1419. *
  1420. * @package iTopORM
  1421. */
  1422. class AttributeDateTime extends AttributeDBField
  1423. {
  1424. //const MYDATETIMEZONE = "UTC";
  1425. const MYDATETIMEZONE = "Europe/Paris";
  1426. static protected $const_TIMEZONE = null; // set once for all upon object construct
  1427. static public function InitStatics()
  1428. {
  1429. // Init static constant once for all (remove when PHP allows real static const)
  1430. self::$const_TIMEZONE = new DateTimeZone(self::MYDATETIMEZONE);
  1431. // #@# Init default timezone -> do not get a notice... to be improved !!!
  1432. // duplicated in the email test page (the mail function does trigger a notice as well)
  1433. date_default_timezone_set(self::MYDATETIMEZONE);
  1434. }
  1435. static protected function GetDateFormat()
  1436. {
  1437. return "Y-m-d H:i:s";
  1438. }
  1439. static protected function ListExpectedParams()
  1440. {
  1441. return parent::ListExpectedParams();
  1442. //return array_merge(parent::ListExpectedParams(), array());
  1443. }
  1444. public function GetEditClass() {return "DateTime";}
  1445. protected function GetSQLCol() {return "TIMESTAMP";}
  1446. public static function GetAsUnixSeconds($value)
  1447. {
  1448. $oDeadlineDateTime = new DateTime($value, self::$const_TIMEZONE);
  1449. $iUnixSeconds = $oDeadlineDateTime->format('U');
  1450. return $iUnixSeconds;
  1451. }
  1452. // #@# THIS HAS TO REVISED
  1453. // Having null not allowed was interpreted by mySQL
  1454. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  1455. // Then, on each update of the record, the field was modified.
  1456. // We will have to specify the default value if we want to restore this option
  1457. // In fact, we could also have more verbs dedicated to the DB:
  1458. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  1459. public function IsNullAllowed() {return true;}
  1460. public function GetDefaultValue()
  1461. {
  1462. $default = parent::GetDefaultValue();
  1463. if (!parent::IsNullAllowed())
  1464. {
  1465. if (empty($default))
  1466. {
  1467. $default = date(self::GetDateFormat());
  1468. }
  1469. }
  1470. return $default;
  1471. }
  1472. // END OF THE WORKAROUND
  1473. ///////////////////////////////////////////////////////////////
  1474. public function GetValidationPattern()
  1475. {
  1476. 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$";
  1477. }
  1478. public function GetBasicFilterOperators()
  1479. {
  1480. return array(
  1481. "="=>"equals",
  1482. "!="=>"differs from",
  1483. "<"=>"before",
  1484. "<="=>"before",
  1485. ">"=>"after (strictly)",
  1486. ">="=>"after",
  1487. "SameDay"=>"same day (strip time)",
  1488. "SameMonth"=>"same year/month",
  1489. "SameYear"=>"same year",
  1490. "Today"=>"today",
  1491. ">|"=>"after today + N days",
  1492. "<|"=>"before today + N days",
  1493. "=|"=>"equals today + N days",
  1494. );
  1495. }
  1496. public function GetBasicFilterLooseOperator()
  1497. {
  1498. // Unless we implement a "same xxx, depending on given precision" !
  1499. return "=";
  1500. }
  1501. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1502. {
  1503. $sQValue = CMDBSource::Quote($value);
  1504. switch ($sOpCode)
  1505. {
  1506. case '=':
  1507. case '!=':
  1508. case '<':
  1509. case '<=':
  1510. case '>':
  1511. case '>=':
  1512. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1513. case 'SameDay':
  1514. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  1515. case 'SameMonth':
  1516. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  1517. case 'SameYear':
  1518. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  1519. case 'Today':
  1520. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  1521. case '>|':
  1522. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1523. case '<|':
  1524. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1525. case '=|':
  1526. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  1527. default:
  1528. return $this->GetSQLExpr()." = $sQValue";
  1529. }
  1530. }
  1531. public function MakeRealValue($proposedValue)
  1532. {
  1533. if (is_null($proposedValue))
  1534. {
  1535. return null;
  1536. }
  1537. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  1538. {
  1539. return null;
  1540. }
  1541. if (!is_numeric($proposedValue))
  1542. {
  1543. return $proposedValue;
  1544. }
  1545. return date(self::GetDateFormat(), $proposedValue);
  1546. }
  1547. public function ScalarToSQL($value)
  1548. {
  1549. if (is_null($value))
  1550. {
  1551. return null;
  1552. }
  1553. elseif (empty($value))
  1554. {
  1555. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  1556. return '0000-00-00 00:00:00';
  1557. }
  1558. return $value;
  1559. }
  1560. public function GetAsHTML($value, $oHostObject = null)
  1561. {
  1562. return Str::pure2html($value);
  1563. }
  1564. public function GetAsXML($value, $oHostObject = null)
  1565. {
  1566. return Str::pure2xml($value);
  1567. }
  1568. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1569. {
  1570. $sFrom = array("\r\n", $sTextQualifier);
  1571. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1572. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1573. return '"'.$sEscaped.'"';
  1574. }
  1575. /**
  1576. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  1577. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  1578. * does nothing special, and just calls the default (loose) operator
  1579. * @param string $sSearchText The search string to analyze for smart patterns
  1580. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  1581. * @param Hash $aParams Values of the query parameters
  1582. * @return Expression The search condition to be added (AND) to the current search
  1583. */
  1584. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  1585. {
  1586. // Possible smart patterns
  1587. $aPatterns = array(
  1588. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  1589. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  1590. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  1591. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  1592. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  1593. );
  1594. $sPatternFound = '';
  1595. $aMatches = array();
  1596. foreach($aPatterns as $sPatName => $sPattern)
  1597. {
  1598. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  1599. {
  1600. $sPatternFound = $sPatName;
  1601. break;
  1602. }
  1603. }
  1604. switch($sPatternFound)
  1605. {
  1606. case 'between':
  1607. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  1608. $oRightExpr = new VariableExpression($sParamName1);
  1609. $aParams[$sParamName1] = $aMatches[1];
  1610. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  1611. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  1612. $oRightExpr = new VariableExpression($sParamName2);
  1613. $sOperator = $this->GetBasicFilterLooseOperator();
  1614. $aParams[$sParamName2] = $aMatches[2];
  1615. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  1616. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  1617. break;
  1618. case 'greater than':
  1619. case 'greater than or equal':
  1620. case 'less than':
  1621. case 'less than or equal':
  1622. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  1623. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  1624. $oRightExpr = new VariableExpression($sParamName);
  1625. $aParams[$sParamName] = $aMatches[1];
  1626. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  1627. break;
  1628. default:
  1629. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  1630. }
  1631. return $oNewCondition;
  1632. }
  1633. }
  1634. /**
  1635. * Store a duration as a number of seconds
  1636. *
  1637. * @package iTopORM
  1638. */
  1639. class AttributeDuration extends AttributeInteger
  1640. {
  1641. public function GetEditClass() {return "Duration";}
  1642. protected function GetSQLCol() {return "INT(11) UNSIGNED";}
  1643. public function GetNullValue() {return '0';}
  1644. public function GetDefaultValue()
  1645. {
  1646. return 0;
  1647. }
  1648. public function MakeRealValue($proposedValue)
  1649. {
  1650. if (is_null($proposedValue)) return null;
  1651. if (!is_numeric($proposedValue)) return null;
  1652. if ( ((int)$proposedValue) < 0) return null;
  1653. return (int)$proposedValue;
  1654. }
  1655. public function ScalarToSQL($value)
  1656. {
  1657. if (is_null($value))
  1658. {
  1659. return null;
  1660. }
  1661. return $value;
  1662. }
  1663. public function GetAsHTML($value, $oHostObject = null)
  1664. {
  1665. return Str::pure2html(self::FormatDuration($value));
  1666. }
  1667. static function FormatDuration($duration)
  1668. {
  1669. $aDuration = self::SplitDuration($duration);
  1670. $sResult = '';
  1671. if ($duration < 60)
  1672. {
  1673. // Less than 1 min
  1674. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  1675. }
  1676. else if ($duration < 3600)
  1677. {
  1678. // less than 1 hour, display it in minutes/seconds
  1679. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  1680. }
  1681. else if ($duration < 86400)
  1682. {
  1683. // Less than 1 day, display it in hours/minutes/seconds
  1684. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  1685. }
  1686. else
  1687. {
  1688. // more than 1 day, display it in days/hours/minutes/seconds
  1689. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  1690. }
  1691. return $sResult;
  1692. }
  1693. static function SplitDuration($duration)
  1694. {
  1695. $days = floor($duration / 86400);
  1696. $hours = floor(($duration - (86400*$days)) / 3600);
  1697. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  1698. $seconds = ($duration % 60); // modulo
  1699. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  1700. }
  1701. }
  1702. /**
  1703. * Map a date+time column to an attribute
  1704. *
  1705. * @package iTopORM
  1706. */
  1707. class AttributeDate extends AttributeDateTime
  1708. {
  1709. const MYDATEFORMAT = "Y-m-d";
  1710. static protected function GetDateFormat()
  1711. {
  1712. return "Y-m-d";
  1713. }
  1714. static public function InitStatics()
  1715. {
  1716. // Nothing to do...
  1717. }
  1718. static protected function ListExpectedParams()
  1719. {
  1720. return parent::ListExpectedParams();
  1721. //return array_merge(parent::ListExpectedParams(), array());
  1722. }
  1723. public function GetEditClass() {return "Date";}
  1724. protected function GetSQLCol() {return "DATE";}
  1725. public function GetValidationPattern()
  1726. {
  1727. 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)))$";
  1728. }
  1729. }
  1730. // Init static constant once for all (remove when PHP allows real static const)
  1731. AttributeDate::InitStatics();
  1732. /**
  1733. * A dead line stored as a date & time
  1734. * The only difference with the DateTime attribute is the display:
  1735. * relative to the current time
  1736. */
  1737. class AttributeDeadline extends AttributeDateTime
  1738. {
  1739. public function GetAsHTML($value, $oHostObject = null)
  1740. {
  1741. $sResult = '';
  1742. if ($value !== null)
  1743. {
  1744. $value = AttributeDateTime::GetAsUnixSeconds($value);
  1745. $difference = $value - time();
  1746. if ($difference >= 0)
  1747. {
  1748. $sResult = self::FormatDuration($difference);
  1749. }
  1750. else
  1751. {
  1752. $sResult = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  1753. }
  1754. }
  1755. return $sResult;
  1756. }
  1757. static function FormatDuration($duration)
  1758. {
  1759. $days = floor($duration / 86400);
  1760. $hours = floor(($duration - (86400*$days)) / 3600);
  1761. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  1762. $sResult = '';
  1763. if ($duration < 60)
  1764. {
  1765. // Less than 1 min
  1766. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  1767. }
  1768. else if ($duration < 3600)
  1769. {
  1770. // less than 1 hour, display it in minutes
  1771. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  1772. }
  1773. else if ($duration < 86400)
  1774. {
  1775. // Less that 1 day, display it in hours/minutes
  1776. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  1777. }
  1778. else
  1779. {
  1780. // Less that 1 day, display it in hours/minutes
  1781. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  1782. }
  1783. return $sResult;
  1784. }
  1785. }
  1786. // Init static constant once for all (remove when PHP allows real static const)
  1787. AttributeDateTime::InitStatics();
  1788. /**
  1789. * Map a foreign key to an attribute
  1790. * AttributeExternalKey and AttributeExternalField may be an external key
  1791. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  1792. * where an AttributeExternalField corresponds to a column into another table (class)
  1793. *
  1794. * @package iTopORM
  1795. */
  1796. class AttributeExternalKey extends AttributeDBFieldVoid
  1797. {
  1798. static protected function ListExpectedParams()
  1799. {
  1800. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  1801. }
  1802. public function GetEditClass() {return "ExtKey";}
  1803. protected function GetSQLCol() {return "INT(11)";}
  1804. public function RequiresIndex()
  1805. {
  1806. return true;
  1807. }
  1808. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  1809. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  1810. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  1811. public function GetKeyAttCode() {return $this->GetCode();}
  1812. public function GetDefaultValue() {return 0;}
  1813. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  1814. public function GetBasicFilterOperators()
  1815. {
  1816. return parent::GetBasicFilterOperators();
  1817. }
  1818. public function GetBasicFilterLooseOperator()
  1819. {
  1820. return parent::GetBasicFilterLooseOperator();
  1821. }
  1822. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1823. {
  1824. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1825. }
  1826. // overloaded here so that an ext key always have the answer to
  1827. // "what are your possible values?"
  1828. public function GetValuesDef()
  1829. {
  1830. $oValSetDef = $this->Get("allowed_values");
  1831. if (!$oValSetDef)
  1832. {
  1833. // Let's propose every existing value
  1834. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1835. }
  1836. return $oValSetDef;
  1837. }
  1838. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1839. {
  1840. try
  1841. {
  1842. return parent::GetAllowedValues($aArgs, $sContains);
  1843. }
  1844. catch (MissingQueryArgument $e)
  1845. {
  1846. // Some required arguments could not be found, enlarge to any existing value
  1847. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  1848. return $oValSetDef->GetValues($aArgs, $sContains);
  1849. }
  1850. }
  1851. public function GetDeletionPropagationOption()
  1852. {
  1853. return $this->Get("on_target_delete");
  1854. }
  1855. public function GetNullValue()
  1856. {
  1857. return 0;
  1858. }
  1859. public function IsNull($proposedValue)
  1860. {
  1861. return ($proposedValue == 0);
  1862. }
  1863. public function MakeRealValue($proposedValue)
  1864. {
  1865. if (is_null($proposedValue)) return 0;
  1866. if ($proposedValue === '') return 0;
  1867. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  1868. return (int)$proposedValue;
  1869. }
  1870. public function GetMaximumComboLength()
  1871. {
  1872. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  1873. }
  1874. public function GetMinAutoCompleteChars()
  1875. {
  1876. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  1877. }
  1878. public function AllowTargetCreation()
  1879. {
  1880. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  1881. }
  1882. }
  1883. /**
  1884. * An attribute which corresponds to an external key (direct or indirect)
  1885. *
  1886. * @package iTopORM
  1887. */
  1888. class AttributeExternalField extends AttributeDefinition
  1889. {
  1890. static protected function ListExpectedParams()
  1891. {
  1892. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  1893. }
  1894. public function GetEditClass() {return "ExtField";}
  1895. protected function GetSQLCol()
  1896. {
  1897. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  1898. $oExtAttDef = $this->GetExtAttDef();
  1899. return $oExtAttDef->GetSQLCol();
  1900. }
  1901. public function GetSQLExpressions($sPrefix = '')
  1902. {
  1903. if ($sPrefix == '')
  1904. {
  1905. return array('' => $this->GetCode());
  1906. }
  1907. else
  1908. {
  1909. return $sPrefix;
  1910. }
  1911. }
  1912. public function GetLabel()
  1913. {
  1914. $oRemoteAtt = $this->GetExtAttDef();
  1915. $sDefault = $oRemoteAtt->GetLabel();
  1916. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, $sDefault);
  1917. }
  1918. public function GetDescription()
  1919. {
  1920. $oRemoteAtt = $this->GetExtAttDef();
  1921. $sDefault = $oRemoteAtt->GetDescription();
  1922. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', $sDefault);
  1923. }
  1924. public function GetHelpOnEdition()
  1925. {
  1926. $oRemoteAtt = $this->GetExtAttDef();
  1927. $sDefault = $oRemoteAtt->GetHelpOnEdition();
  1928. return Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', $sDefault);
  1929. }
  1930. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  1931. {
  1932. switch($iType)
  1933. {
  1934. case EXTKEY_ABSOLUTE:
  1935. // see further
  1936. $oRemoteAtt = $this->GetExtAttDef();
  1937. return $oRemoteAtt->IsExternalKey($iType);
  1938. case EXTKEY_RELATIVE:
  1939. return false;
  1940. default:
  1941. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1942. }
  1943. }
  1944. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  1945. {
  1946. return $this->GetKeyAttDef($iType)->GetTargetClass();
  1947. }
  1948. public function IsExternalField() {return true;}
  1949. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  1950. public function GetExtAttCode() {return $this->Get("target_attcode");}
  1951. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  1952. {
  1953. switch($iType)
  1954. {
  1955. case EXTKEY_ABSOLUTE:
  1956. // see further
  1957. $oRemoteAtt = $this->GetExtAttDef();
  1958. if ($oRemoteAtt->IsExternalField())
  1959. {
  1960. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1961. }
  1962. else if ($oRemoteAtt->IsExternalKey())
  1963. {
  1964. return $oRemoteAtt;
  1965. }
  1966. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  1967. case EXTKEY_RELATIVE:
  1968. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  1969. default:
  1970. throw new CoreException("Unexpected value for argument iType: '$iType'");
  1971. }
  1972. }
  1973. public function GetExtAttDef()
  1974. {
  1975. $oKeyAttDef = $this->GetKeyAttDef();
  1976. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->Get("targetclass"), $this->Get("target_attcode"));
  1977. 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"));
  1978. return $oExtAttDef;
  1979. }
  1980. public function GetSQLExpr()
  1981. {
  1982. $oExtAttDef = $this->GetExtAttDef();
  1983. return $oExtAttDef->GetSQLExpr();
  1984. }
  1985. public function GetDefaultValue()
  1986. {
  1987. $oExtAttDef = $this->GetExtAttDef();
  1988. return $oExtAttDef->GetDefaultValue();
  1989. }
  1990. public function IsNullAllowed()
  1991. {
  1992. $oExtAttDef = $this->GetExtAttDef();
  1993. return $oExtAttDef->IsNullAllowed();
  1994. }
  1995. public function IsScalar()
  1996. {
  1997. $oExtAttDef = $this->GetExtAttDef();
  1998. return $oExtAttDef->IsScalar();
  1999. }
  2000. public function GetFilterDefinitions()
  2001. {
  2002. return array($this->GetCode() => new FilterFromAttribute($this));
  2003. }
  2004. public function GetBasicFilterOperators()
  2005. {
  2006. $oExtAttDef = $this->GetExtAttDef();
  2007. return $oExtAttDef->GetBasicFilterOperators();
  2008. }
  2009. public function GetBasicFilterLooseOperator()
  2010. {
  2011. $oExtAttDef = $this->GetExtAttDef();
  2012. return $oExtAttDef->GetBasicFilterLooseOperator();
  2013. }
  2014. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2015. {
  2016. $oExtAttDef = $this->GetExtAttDef();
  2017. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  2018. }
  2019. public function GetNullValue()
  2020. {
  2021. $oExtAttDef = $this->GetExtAttDef();
  2022. return $oExtAttDef->GetNullValue();
  2023. }
  2024. public function IsNull($proposedValue)
  2025. {
  2026. $oExtAttDef = $this->GetExtAttDef();
  2027. return $oExtAttDef->IsNull($proposedValue);
  2028. }
  2029. public function MakeRealValue($proposedValue)
  2030. {
  2031. $oExtAttDef = $this->GetExtAttDef();
  2032. return $oExtAttDef->MakeRealValue($proposedValue);
  2033. }
  2034. public function ScalarToSQL($value)
  2035. {
  2036. // This one could be used in case of filtering only
  2037. $oExtAttDef = $this->GetExtAttDef();
  2038. return $oExtAttDef->ScalarToSQL($value);
  2039. }
  2040. // Do not overload GetSQLExpression here because this is handled in the joins
  2041. //public function GetSQLExpressions($sPrefix = '') {return array();}
  2042. // Here, we get the data...
  2043. public function FromSQLToValue($aCols, $sPrefix = '')
  2044. {
  2045. $oExtAttDef = $this->GetExtAttDef();
  2046. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  2047. }
  2048. public function GetAsHTML($value, $oHostObject = null)
  2049. {
  2050. $oExtAttDef = $this->GetExtAttDef();
  2051. return $oExtAttDef->GetAsHTML($value);
  2052. }
  2053. public function GetAsXML($value, $oHostObject = null)
  2054. {
  2055. $oExtAttDef = $this->GetExtAttDef();
  2056. return $oExtAttDef->GetAsXML($value);
  2057. }
  2058. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null)
  2059. {
  2060. $oExtAttDef = $this->GetExtAttDef();
  2061. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  2062. }
  2063. }
  2064. /**
  2065. * Map a varchar column to an URL (formats the ouput in HMTL)
  2066. *
  2067. * @package iTopORM
  2068. */
  2069. class AttributeURL extends AttributeString
  2070. {
  2071. static protected function ListExpectedParams()
  2072. {
  2073. //return parent::ListExpectedParams();
  2074. return array_merge(parent::ListExpectedParams(), array("target"));
  2075. }
  2076. public function GetEditClass() {return "String";}
  2077. public function GetAsHTML($sValue, $oHostObject = null)
  2078. {
  2079. $sTarget = $this->Get("target");
  2080. if (empty($sTarget)) $sTarget = "_blank";
  2081. $sLabel = Str::pure2html($sValue);
  2082. if (strlen($sLabel) > 40)
  2083. {
  2084. // Truncate the length to about 40 characters, by removing the middle
  2085. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  2086. }
  2087. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  2088. }
  2089. public function GetValidationPattern()
  2090. {
  2091. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  2092. }
  2093. }
  2094. /**
  2095. * A blob is an ormDocument, it is stored as several columns in the database
  2096. *
  2097. * @package iTopORM
  2098. */
  2099. class AttributeBlob extends AttributeDefinition
  2100. {
  2101. static protected function ListExpectedParams()
  2102. {
  2103. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  2104. }
  2105. public function GetEditClass() {return "Document";}
  2106. public function IsDirectField() {return true;}
  2107. public function IsScalar() {return true;}
  2108. public function IsWritable() {return true;}
  2109. public function GetDefaultValue() {return "";}
  2110. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2111. // Facilitate things: allow the user to Set the value from a string
  2112. public function MakeRealValue($proposedValue)
  2113. {
  2114. if (!is_object($proposedValue))
  2115. {
  2116. return new ormDocument($proposedValue, 'text/plain');
  2117. }
  2118. return $proposedValue;
  2119. }
  2120. public function GetSQLExpressions($sPrefix = '')
  2121. {
  2122. if ($sPrefix == '')
  2123. {
  2124. $sPrefix = $this->GetCode();
  2125. }
  2126. $aColumns = array();
  2127. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2128. $aColumns[''] = $sPrefix.'_mimetype';
  2129. $aColumns['_data'] = $sPrefix.'_data';
  2130. $aColumns['_filename'] = $sPrefix.'_filename';
  2131. return $aColumns;
  2132. }
  2133. public function FromSQLToValue($aCols, $sPrefix = '')
  2134. {
  2135. if (!isset($aCols[$sPrefix]))
  2136. {
  2137. $sAvailable = implode(', ', array_keys($aCols));
  2138. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2139. }
  2140. $sMimeType = $aCols[$sPrefix];
  2141. if (!isset($aCols[$sPrefix.'_data']))
  2142. {
  2143. $sAvailable = implode(', ', array_keys($aCols));
  2144. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  2145. }
  2146. $data = $aCols[$sPrefix.'_data'];
  2147. if (!isset($aCols[$sPrefix.'_filename']))
  2148. {
  2149. $sAvailable = implode(', ', array_keys($aCols));
  2150. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  2151. }
  2152. $sFileName = $aCols[$sPrefix.'_filename'];
  2153. $value = new ormDocument($data, $sMimeType, $sFileName);
  2154. return $value;
  2155. }
  2156. public function GetSQLValues($value)
  2157. {
  2158. // #@# Optimization: do not load blobs anytime
  2159. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2160. // using memory in case a temporary table has to be created
  2161. // (temporary tables created on disk)
  2162. // We will have to remove the blobs from the list of attributes when doing the select
  2163. // then the use of Get() should finalize the load
  2164. if ($value instanceOf ormDocument)
  2165. {
  2166. $aValues = array();
  2167. $aValues[$this->GetCode().'_data'] = $value->GetData();
  2168. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  2169. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  2170. }
  2171. else
  2172. {
  2173. $aValues = array();
  2174. $aValues[$this->GetCode().'_data'] = '';
  2175. $aValues[$this->GetCode().'_mimetype'] = '';
  2176. $aValues[$this->GetCode().'_filename'] = '';
  2177. }
  2178. return $aValues;
  2179. }
  2180. public function GetSQLColumns()
  2181. {
  2182. $aColumns = array();
  2183. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  2184. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  2185. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  2186. return $aColumns;
  2187. }
  2188. public function GetFilterDefinitions()
  2189. {
  2190. return array();
  2191. // still not working... see later...
  2192. return array(
  2193. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  2194. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  2195. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  2196. );
  2197. }
  2198. public function GetBasicFilterOperators()
  2199. {
  2200. return array();
  2201. }
  2202. public function GetBasicFilterLooseOperator()
  2203. {
  2204. return '=';
  2205. }
  2206. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2207. {
  2208. return 'true';
  2209. }
  2210. public function GetAsHTML($value, $oHostObject = null)
  2211. {
  2212. if (is_object($value))
  2213. {
  2214. return $value->GetAsHTML();
  2215. }
  2216. }
  2217. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2218. {
  2219. return ''; // Not exportable in CSV !
  2220. }
  2221. public function GetAsXML($value, $oHostObject = null)
  2222. {
  2223. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  2224. }
  2225. }
  2226. /**
  2227. * One way encrypted (hashed) password
  2228. */
  2229. class AttributeOneWayPassword extends AttributeDefinition
  2230. {
  2231. static protected function ListExpectedParams()
  2232. {
  2233. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  2234. }
  2235. public function GetEditClass() {return "One Way Password";}
  2236. public function IsDirectField() {return true;}
  2237. public function IsScalar() {return true;}
  2238. public function IsWritable() {return true;}
  2239. public function GetDefaultValue() {return "";}
  2240. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2241. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  2242. public function MakeRealValue($proposedValue)
  2243. {
  2244. $oPassword = $proposedValue;
  2245. if (!is_object($oPassword))
  2246. {
  2247. $oPassword = new ormPassword('', '');
  2248. $oPassword->SetPassword($proposedValue);
  2249. }
  2250. return $oPassword;
  2251. }
  2252. public function GetSQLExpressions($sPrefix = '')
  2253. {
  2254. if ($sPrefix == '')
  2255. {
  2256. $sPrefix = $this->GetCode();
  2257. }
  2258. $aColumns = array();
  2259. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2260. $aColumns[''] = $sPrefix.'_hash';
  2261. $aColumns['_salt'] = $sPrefix.'_salt';
  2262. return $aColumns;
  2263. }
  2264. public function FromSQLToValue($aCols, $sPrefix = '')
  2265. {
  2266. if (!isset($aCols[$sPrefix]))
  2267. {
  2268. $sAvailable = implode(', ', array_keys($aCols));
  2269. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2270. }
  2271. $hashed = $aCols[$sPrefix];
  2272. if (!isset($aCols[$sPrefix.'_salt']))
  2273. {
  2274. $sAvailable = implode(', ', array_keys($aCols));
  2275. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  2276. }
  2277. $sSalt = $aCols[$sPrefix.'_salt'];
  2278. $value = new ormPassword($hashed, $sSalt);
  2279. return $value;
  2280. }
  2281. public function GetSQLValues($value)
  2282. {
  2283. // #@# Optimization: do not load blobs anytime
  2284. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2285. // using memory in case a temporary table has to be created
  2286. // (temporary tables created on disk)
  2287. // We will have to remove the blobs from the list of attributes when doing the select
  2288. // then the use of Get() should finalize the load
  2289. if ($value instanceOf ormPassword)
  2290. {
  2291. $aValues = array();
  2292. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  2293. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  2294. }
  2295. else
  2296. {
  2297. $aValues = array();
  2298. $aValues[$this->GetCode().'_hash'] = '';
  2299. $aValues[$this->GetCode().'_salt'] = '';
  2300. }
  2301. return $aValues;
  2302. }
  2303. public function GetSQLColumns()
  2304. {
  2305. $aColumns = array();
  2306. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  2307. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  2308. return $aColumns;
  2309. }
  2310. public function GetImportColumns()
  2311. {
  2312. $aColumns = array();
  2313. $aColumns[$this->GetCode()] = 'TINYTEXT';
  2314. return $aColumns;
  2315. }
  2316. public function FromImportToValue($aCols, $sPrefix = '')
  2317. {
  2318. if (!isset($aCols[$sPrefix]))
  2319. {
  2320. $sAvailable = implode(', ', array_keys($aCols));
  2321. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2322. }
  2323. $sClearPwd = $aCols[$sPrefix];
  2324. $oPassword = new ormPassword('', '');
  2325. $oPassword->SetPassword($sClearPwd);
  2326. return $oPassword;
  2327. }
  2328. public function GetFilterDefinitions()
  2329. {
  2330. return array();
  2331. // still not working... see later...
  2332. }
  2333. public function GetBasicFilterOperators()
  2334. {
  2335. return array();
  2336. }
  2337. public function GetBasicFilterLooseOperator()
  2338. {
  2339. return '=';
  2340. }
  2341. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2342. {
  2343. return 'true';
  2344. }
  2345. public function GetAsHTML($value, $oHostObject = null)
  2346. {
  2347. if (is_object($value))
  2348. {
  2349. return $value->GetAsHTML();
  2350. }
  2351. }
  2352. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2353. {
  2354. return ''; // Not exportable in CSV
  2355. }
  2356. public function GetAsXML($value, $oHostObject = null)
  2357. {
  2358. return ''; // Not exportable in XML
  2359. }
  2360. }
  2361. // Indexed array having two dimensions
  2362. class AttributeTable extends AttributeText
  2363. {
  2364. public function GetEditClass() {return "Text";}
  2365. protected function GetSQLCol() {return "TEXT";}
  2366. public function GetMaxSize()
  2367. {
  2368. return null;
  2369. }
  2370. // Facilitate things: allow the user to Set the value from a string
  2371. public function MakeRealValue($proposedValue)
  2372. {
  2373. if (!is_array($proposedValue))
  2374. {
  2375. return array(0 => array(0 => $proposedValue));
  2376. }
  2377. return $proposedValue;
  2378. }
  2379. public function FromSQLToValue($aCols, $sPrefix = '')
  2380. {
  2381. try
  2382. {
  2383. $value = @unserialize($aCols[$sPrefix.'']);
  2384. if ($value === false)
  2385. {
  2386. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  2387. }
  2388. }
  2389. catch(Exception $e)
  2390. {
  2391. $value = $this->MakeRealValue($aCols[$sPrefix.'']);
  2392. }
  2393. return $value;
  2394. }
  2395. public function GetSQLValues($value)
  2396. {
  2397. $aValues = array();
  2398. $aValues[$this->Get("sql")] = serialize($value);
  2399. return $aValues;
  2400. }
  2401. public function GetAsHTML($value, $oHostObject = null)
  2402. {
  2403. if (!is_array($value))
  2404. {
  2405. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2406. }
  2407. if (count($value) == 0)
  2408. {
  2409. return "";
  2410. }
  2411. $sRes = "<TABLE class=\"listResults\">";
  2412. $sRes .= "<TBODY>";
  2413. foreach($value as $iRow => $aRawData)
  2414. {
  2415. $sRes .= "<TR>";
  2416. foreach ($aRawData as $iCol => $cell)
  2417. {
  2418. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  2419. $sRes .= "<TD>$sCell</TD>";
  2420. }
  2421. $sRes .= "</TR>";
  2422. }
  2423. $sRes .= "</TBODY>";
  2424. $sRes .= "</TABLE>";
  2425. return $sRes;
  2426. }
  2427. }
  2428. // The PHP value is a hash array, it is stored as a TEXT column
  2429. class AttributePropertySet extends AttributeTable
  2430. {
  2431. public function GetEditClass() {return "Text";}
  2432. protected function GetSQLCol() {return "TEXT";}
  2433. // Facilitate things: allow the user to Set the value from a string
  2434. public function MakeRealValue($proposedValue)
  2435. {
  2436. if (!is_array($proposedValue))
  2437. {
  2438. return array('?' => (string)$proposedValue);
  2439. }
  2440. return $proposedValue;
  2441. }
  2442. public function GetAsHTML($value, $oHostObject = null)
  2443. {
  2444. if (!is_array($value))
  2445. {
  2446. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  2447. }
  2448. if (count($value) == 0)
  2449. {
  2450. return "";
  2451. }
  2452. $sRes = "<TABLE class=\"listResults\">";
  2453. $sRes .= "<TBODY>";
  2454. foreach($value as $sProperty => $sValue)
  2455. {
  2456. $sRes .= "<TR>";
  2457. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  2458. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  2459. $sRes .= "</TR>";
  2460. }
  2461. $sRes .= "</TBODY>";
  2462. $sRes .= "</TABLE>";
  2463. return $sRes;
  2464. }
  2465. }
  2466. /**
  2467. * The attribute dedicated to the friendly name automatic attribute (not written)
  2468. *
  2469. * @package iTopORM
  2470. */
  2471. class AttributeComputedFieldVoid extends AttributeDefinition
  2472. {
  2473. static protected function ListExpectedParams()
  2474. {
  2475. return array_merge(parent::ListExpectedParams(), array());
  2476. }
  2477. public function GetEditClass() {return "";}
  2478. public function GetValuesDef() {return null;}
  2479. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  2480. public function IsDirectField() {return true;}
  2481. public function IsScalar() {return true;}
  2482. public function IsWritable() {return false;}
  2483. public function GetSQLExpr() {return null;}
  2484. public function GetDefaultValue() {return $this->MakeRealValue("");}
  2485. public function IsNullAllowed() {return false;}
  2486. //
  2487. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  2488. public function GetSQLExpressions($sPrefix = '')
  2489. {
  2490. if ($sPrefix == '')
  2491. {
  2492. $sPrefix = $this->GetCode();
  2493. }
  2494. return array('' => $sPrefix);
  2495. }
  2496. public function FromSQLToValue($aCols, $sPrefix = '')
  2497. {
  2498. return null;
  2499. }
  2500. public function GetSQLValues($value)
  2501. {
  2502. return array();
  2503. }
  2504. public function GetSQLColumns()
  2505. {
  2506. return array();
  2507. }
  2508. public function GetFilterDefinitions()
  2509. {
  2510. return array($this->GetCode() => new FilterFromAttribute($this));
  2511. }
  2512. public function GetBasicFilterOperators()
  2513. {
  2514. return array();
  2515. }
  2516. public function GetBasicFilterLooseOperator()
  2517. {
  2518. return "=";
  2519. }
  2520. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2521. {
  2522. $sQValue = CMDBSource::Quote($value);
  2523. switch ($sOpCode)
  2524. {
  2525. case '!=':
  2526. return $this->GetSQLExpr()." != $sQValue";
  2527. break;
  2528. case '=':
  2529. default:
  2530. return $this->GetSQLExpr()." = $sQValue";
  2531. }
  2532. }
  2533. }
  2534. /**
  2535. * The attribute dedicated to the friendly name automatic attribute (not written)
  2536. *
  2537. * @package iTopORM
  2538. */
  2539. class AttributeFriendlyName extends AttributeComputedFieldVoid
  2540. {
  2541. public function __construct($sCode, $sExtKeyAttCode)
  2542. {
  2543. $this->m_sCode = $sCode;
  2544. $aParams = array();
  2545. // $aParams["is_null_allowed"] = false,
  2546. $aParams["default_value"] = '';
  2547. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  2548. parent::__construct($sCode, $aParams);
  2549. $this->m_sValue = $this->Get("default_value");
  2550. }
  2551. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  2552. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  2553. protected function GetSQLCol() {return "";}
  2554. public function FromSQLToValue($aCols, $sPrefix = '')
  2555. {
  2556. $sValue = $aCols[$sPrefix];
  2557. return $sValue;
  2558. }
  2559. /**
  2560. * Encrypt the value before storing it in the database
  2561. */
  2562. public function GetSQLValues($value)
  2563. {
  2564. return array();
  2565. }
  2566. public function IsWritable()
  2567. {
  2568. return false;
  2569. }
  2570. public function IsDirectField()
  2571. {
  2572. return false;
  2573. }
  2574. public function SetFixedValue($sValue)
  2575. {
  2576. $this->m_sValue = $sValue;
  2577. }
  2578. public function GetDefaultValue()
  2579. {
  2580. return $this->m_sValue;
  2581. }
  2582. public function GetAsHTML($sValue, $oHostObject = null)
  2583. {
  2584. return Str::pure2html((string)$sValue);
  2585. }
  2586. }
  2587. ?>