attributedef.class.inc.php 82 KB

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