attributedef.class.inc.php 92 KB

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