attributedef.class.inc.php 87 KB

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