attributedef.class.inc.php 86 KB

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