attributedef.class.inc.php 96 KB

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