attributedef.class.inc.php 99 KB

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