attributedef.class.inc.php 97 KB

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