attributedef.class.inc.php 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493
  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('ormstopwatch.class.inc.php');
  27. require_once('ormpassword.class.inc.php');
  28. require_once('ormcaselog.class.inc.php');
  29. /**
  30. * MissingColumnException - sent if an attribute is being created but the column is missing in the row
  31. *
  32. * @package iTopORM
  33. */
  34. class MissingColumnException extends Exception
  35. {}
  36. /**
  37. * add some description here...
  38. *
  39. * @package iTopORM
  40. */
  41. define('EXTKEY_RELATIVE', 1);
  42. /**
  43. * add some description here...
  44. *
  45. * @package iTopORM
  46. */
  47. define('EXTKEY_ABSOLUTE', 2);
  48. /**
  49. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  50. *
  51. * @package iTopORM
  52. */
  53. define('DEL_MANUAL', 1);
  54. /**
  55. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  56. *
  57. * @package iTopORM
  58. */
  59. define('DEL_AUTO', 2);
  60. /**
  61. * Fully silent delete... not yet implemented
  62. */
  63. define('DEL_SILENT', 2);
  64. /**
  65. * For HierarchicalKeys only: move all the children up one level automatically
  66. */
  67. define('DEL_MOVEUP', 3);
  68. /**
  69. * For Link sets: tracking_level
  70. *
  71. * @package iTopORM
  72. */
  73. define('LINKSET_TRACKING_NONE', 0); // Do not track changes in the link set
  74. define('LINKSET_TRACKING_LIST', 1); // Do track added/removed items
  75. define('LINKSET_TRACKING_DETAILS', 2); // Do track modified items
  76. define('LINKSET_TRACKING_ALL', 3); // Do track added/removed/modified items
  77. /**
  78. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  79. *
  80. * @package iTopORM
  81. */
  82. abstract class AttributeDefinition
  83. {
  84. public function GetType()
  85. {
  86. return Dict::S('Core:'.get_class($this));
  87. }
  88. public function GetTypeDesc()
  89. {
  90. return Dict::S('Core:'.get_class($this).'+');
  91. }
  92. abstract public function GetEditClass();
  93. protected $m_sCode;
  94. private $m_aParams = array();
  95. protected $m_sHostClass = '!undefined!';
  96. public function Get($sParamName) {return $this->m_aParams[$sParamName];}
  97. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  98. protected function GetOptional($sParamName, $default)
  99. {
  100. if (array_key_exists($sParamName, $this->m_aParams))
  101. {
  102. return $this->m_aParams[$sParamName];
  103. }
  104. else
  105. {
  106. return $default;
  107. }
  108. }
  109. public function __construct($sCode, $aParams)
  110. {
  111. $this->m_sCode = $sCode;
  112. $this->m_aParams = $aParams;
  113. $this->ConsistencyCheck();
  114. }
  115. public function GetParams()
  116. {
  117. return $this->m_aParams;
  118. }
  119. public function SetHostClass($sHostClass)
  120. {
  121. $this->m_sHostClass = $sHostClass;
  122. }
  123. public function GetHostClass()
  124. {
  125. return $this->m_sHostClass;
  126. }
  127. public function ListSubItems()
  128. {
  129. $aSubItems = array();
  130. foreach(MetaModel::ListAttributeDefs($this->m_sHostClass) as $sAttCode => $oAttDef)
  131. {
  132. if ($oAttDef instanceof AttributeSubItem)
  133. {
  134. if ($oAttDef->Get('target_attcode') == $this->m_sCode)
  135. {
  136. $aSubItems[$sAttCode] = $oAttDef;
  137. }
  138. }
  139. }
  140. return $aSubItems;
  141. }
  142. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  143. // to be overloaded
  144. static public function ListExpectedParams()
  145. {
  146. return array();
  147. }
  148. private function ConsistencyCheck()
  149. {
  150. // Check that any mandatory param has been specified
  151. //
  152. $aExpectedParams = $this->ListExpectedParams();
  153. foreach($aExpectedParams as $sParamName)
  154. {
  155. if (!array_key_exists($sParamName, $this->m_aParams))
  156. {
  157. $aBacktrace = debug_backtrace();
  158. $sTargetClass = $aBacktrace[2]["class"];
  159. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  160. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  161. }
  162. }
  163. }
  164. // table, key field, name field
  165. public function ListDBJoins()
  166. {
  167. return "";
  168. // e.g: return array("Site", "infrid", "name");
  169. }
  170. public function GetFinalAttDef()
  171. {
  172. return $this;
  173. }
  174. public function IsDirectField() {return false;}
  175. public function IsScalar() {return false;}
  176. public function IsLinkSet() {return false;}
  177. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  178. public function IsHierarchicalKey() {return false;}
  179. public function IsExternalField() {return false;}
  180. public function IsWritable() {return false;}
  181. public function LoadInObject() {return true;}
  182. public function GetValue($oHostObject){return null;} // must return the value if LoadInObject returns false
  183. public function IsNullAllowed() {return true;}
  184. public function GetCode() {return $this->m_sCode;}
  185. public function GetLabel($sDefault = null)
  186. {
  187. // If no default value is specified, let's define the most relevant one for developping purposes
  188. if (is_null($sDefault))
  189. {
  190. $sDefault = str_replace('_', ' ', $this->m_sCode);
  191. }
  192. $sLabel = Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, '');
  193. if (strlen($sLabel) == 0)
  194. {
  195. // Nothing found: go higher in the hierarchy (if possible)
  196. //
  197. $sLabel = $sDefault;
  198. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  199. if ($sParentClass)
  200. {
  201. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  202. {
  203. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  204. $sLabel = $oAttDef->GetLabel($sDefault);
  205. }
  206. }
  207. }
  208. return $sLabel;
  209. }
  210. /**
  211. * Get the label corresponding to the given value
  212. * To be overloaded for localized enums
  213. */
  214. public function GetValueLabel($sValue)
  215. {
  216. return $this->GetAsHTML($sValue);
  217. }
  218. public function GetLabel_Obsolete()
  219. {
  220. // Written for compatibility with a data model written prior to version 0.9.1
  221. if (array_key_exists('label', $this->m_aParams))
  222. {
  223. return $this->m_aParams['label'];
  224. }
  225. else
  226. {
  227. return $this->GetLabel();
  228. }
  229. }
  230. public function GetDescription($sDefault = null)
  231. {
  232. // If no default value is specified, let's define the most relevant one for developping purposes
  233. if (is_null($sDefault))
  234. {
  235. $sDefault = '';
  236. }
  237. $sLabel = Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', '');
  238. if (strlen($sLabel) == 0)
  239. {
  240. // Nothing found: go higher in the hierarchy (if possible)
  241. //
  242. $sLabel = $sDefault;
  243. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  244. if ($sParentClass)
  245. {
  246. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  247. {
  248. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  249. $sLabel = $oAttDef->GetDescription($sDefault);
  250. }
  251. }
  252. }
  253. return $sLabel;
  254. }
  255. public function GetHelpOnEdition($sDefault = null)
  256. {
  257. // If no default value is specified, let's define the most relevant one for developping purposes
  258. if (is_null($sDefault))
  259. {
  260. $sDefault = '';
  261. }
  262. $sLabel = Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', '');
  263. if (strlen($sLabel) == 0)
  264. {
  265. // Nothing found: go higher in the hierarchy (if possible)
  266. //
  267. $sLabel = $sDefault;
  268. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  269. if ($sParentClass)
  270. {
  271. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  272. {
  273. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  274. $sLabel = $oAttDef->GetHelpOnEdition($sDefault);
  275. }
  276. }
  277. }
  278. return $sLabel;
  279. }
  280. public function GetHelpOnSmartSearch()
  281. {
  282. $aParents = array_merge(array(get_class($this) => get_class($this)), class_parents($this));
  283. foreach ($aParents as $sClass)
  284. {
  285. $sHelp = Dict::S("Core:$sClass?SmartSearch", '-missing-');
  286. if ($sHelp != '-missing-')
  287. {
  288. return $sHelp;
  289. }
  290. }
  291. return '';
  292. }
  293. public function GetDescription_Obsolete()
  294. {
  295. // Written for compatibility with a data model written prior to version 0.9.1
  296. if (array_key_exists('description', $this->m_aParams))
  297. {
  298. return $this->m_aParams['description'];
  299. }
  300. else
  301. {
  302. return $this->GetDescription();
  303. }
  304. }
  305. public function GetValuesDef() {return null;}
  306. public function GetPrerequisiteAttributes() {return array();}
  307. public function GetNullValue() {return null;}
  308. public function IsNull($proposedValue) {return is_null($proposedValue);}
  309. public function MakeRealValue($proposedValue, $oHostObj) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  310. public function Equals($val1, $val2) {return ($val1 == $val2);}
  311. public function GetSQLExpressions($sPrefix = '') {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  312. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  313. public function GetSQLColumns() {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  314. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  315. public function RequiresIndex() {return false;}
  316. public function GetOrderBySQLExpressions($sClassAlias)
  317. {
  318. // Note: This is the responsibility of this function to place backticks around column aliases
  319. return array('`'.$sClassAlias.$this->GetCode().'`');
  320. }
  321. public function GetOrderByHint()
  322. {
  323. return '';
  324. }
  325. // Import - differs slightly from SQL input, but identical in most cases
  326. //
  327. public function GetImportColumns() {return $this->GetSQLColumns();}
  328. public function FromImportToValue($aCols, $sPrefix = '')
  329. {
  330. $aValues = array();
  331. foreach ($this->GetSQLExpressions($sPrefix) as $sAlias => $sExpr)
  332. {
  333. // This is working, based on the assumption that importable fields
  334. // are not computed fields => the expression is the name of a column
  335. $aValues[$sPrefix.$sAlias] = $aCols[$sExpr];
  336. }
  337. return $this->FromSQLToValue($aValues, $sPrefix);
  338. }
  339. public function GetValidationPattern()
  340. {
  341. return '';
  342. }
  343. public function CheckFormat($value)
  344. {
  345. return true;
  346. }
  347. public function GetMaxSize()
  348. {
  349. return null;
  350. }
  351. public function MakeValue()
  352. {
  353. $sComputeFunc = $this->Get("compute_func");
  354. if (empty($sComputeFunc)) return null;
  355. return call_user_func($sComputeFunc);
  356. }
  357. abstract public function GetDefaultValue();
  358. //
  359. // To be overloaded in subclasses
  360. //
  361. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  362. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  363. //abstract protected GetBasicFilterHTMLInput();
  364. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  365. public function GetFilterDefinitions()
  366. {
  367. return array();
  368. }
  369. public function GetEditValue($sValue, $oHostObj = null)
  370. {
  371. return (string)$sValue;
  372. }
  373. /**
  374. * Override to display the value in the GUI
  375. */
  376. public function GetAsHTML($sValue, $oHostObject = null)
  377. {
  378. return Str::pure2html((string)$sValue);
  379. }
  380. /**
  381. * Override to export the value in XML
  382. */
  383. public function GetAsXML($sValue, $oHostObject = null)
  384. {
  385. return Str::pure2xml((string)$sValue);
  386. }
  387. /**
  388. * Override to escape the value when read by DBObject::GetAsCSV()
  389. */
  390. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  391. {
  392. return (string)$sValue;
  393. }
  394. public function GetAllowedValues($aArgs = array(), $sContains = '')
  395. {
  396. $oValSetDef = $this->GetValuesDef();
  397. if (!$oValSetDef) return null;
  398. return $oValSetDef->GetValues($aArgs, $sContains);
  399. }
  400. public function GetAsHTMLForHistory($sOldValue, $sNewValue, $sLabel = null)
  401. {
  402. if (is_null($sLabel))
  403. {
  404. $sLabel = $this->GetLabel();
  405. }
  406. if($this->IsExternalKey())
  407. {
  408. $sTargetClass = $this->GetTargetClass();
  409. $sOldValue = (int)$sOldValue ? MetaModel::GetHyperLink($sTargetClass, (int)$sOldValue) : null;
  410. $sNewValue = (int)$sNewValue ? MetaModel::GetHyperLink($sTargetClass, (int)$sNewValue) : null;
  411. }
  412. if ( (($this->GetType() == 'String') || ($this->GetType() == 'Text')) &&
  413. (strlen($sNewValue) > strlen($sOldValue)) )
  414. {
  415. // Check if some text was not appended to the field
  416. if (substr($sNewValue,0, strlen($sOldValue)) == $sOldValue) // Text added at the end
  417. {
  418. $sDelta = substr($sNewValue, strlen($sOldValue));
  419. $sResult = Dict::Format('Change:Text_AppendedTo_AttName', $sDelta, $sLabel);
  420. }
  421. else if (substr($sNewValue, -strlen($sOldValue)) == $sOldValue) // Text added at the beginning
  422. {
  423. $sDelta = substr($sNewValue, 0, strlen($sNewValue) - strlen($sOldValue));
  424. $sResult = Dict::Format('Change:Text_AppendedTo_AttName', $sDelta, $sLabel);
  425. }
  426. else
  427. {
  428. if (strlen($sOldValue) == 0)
  429. {
  430. $sResult = Dict::Format('Change:AttName_SetTo', $sLabel, $sNewValue);
  431. }
  432. else
  433. {
  434. if (is_null($sNewValue))
  435. {
  436. $sNewValue = Dict::S('UI:UndefinedObject');
  437. }
  438. $sResult = Dict::Format('Change:AttName_SetTo_NewValue_PreviousValue_OldValue', $sLabel, $sNewValue, $sOldValue);
  439. }
  440. }
  441. }
  442. else
  443. {
  444. if (strlen($sOldValue) == 0)
  445. {
  446. $sResult = Dict::Format('Change:AttName_SetTo', $sLabel, $sNewValue);
  447. }
  448. else
  449. {
  450. if (is_null($sNewValue))
  451. {
  452. $sNewValue = Dict::S('UI:UndefinedObject');
  453. }
  454. $sResult = Dict::Format('Change:AttName_SetTo_NewValue_PreviousValue_OldValue', $sLabel, $sNewValue, $sOldValue);
  455. }
  456. }
  457. return $sResult;
  458. }
  459. /**
  460. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  461. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  462. * does nothing special, and just calls the default (loose) operator
  463. * @param string $sSearchText The search string to analyze for smart patterns
  464. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  465. * @param Hash $aParams Values of the query parameters
  466. * @return Expression The search condition to be added (AND) to the current search
  467. */
  468. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  469. {
  470. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  471. $oRightExpr = new VariableExpression($sParamName);
  472. $sOperator = $this->GetBasicFilterLooseOperator();
  473. switch ($sOperator)
  474. {
  475. case 'Contains':
  476. $aParams[$sParamName] = "%$sSearchText%";
  477. $sSQLOperator = 'LIKE';
  478. break;
  479. default:
  480. $sSQLOperator = $sOperator;
  481. $aParams[$sParamName] = $sSearchText;
  482. }
  483. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  484. return $oNewCondition;
  485. }
  486. }
  487. /**
  488. * Set of objects directly linked to an object, and being part of its definition
  489. *
  490. * @package iTopORM
  491. */
  492. class AttributeLinkedSet extends AttributeDefinition
  493. {
  494. static public function ListExpectedParams()
  495. {
  496. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  497. }
  498. public function GetEditClass() {return "List";}
  499. public function IsWritable() {return true;}
  500. public function IsLinkSet() {return true;}
  501. public function IsIndirect() {return false;}
  502. public function GetValuesDef() {return $this->Get("allowed_values");}
  503. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  504. public function GetDefaultValue($aArgs = array())
  505. {
  506. // Note: so far, this feature is a prototype,
  507. // later, the argument 'this' should always be present in the arguments
  508. //
  509. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  510. {
  511. $aValues = $this->Get('default_value')->GetValues($aArgs);
  512. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  513. return $oSet;
  514. }
  515. else
  516. {
  517. return DBObjectSet::FromScratch($this->Get('linked_class'));
  518. }
  519. }
  520. public function GetTrackingLevel()
  521. {
  522. return $this->GetOptional('tracking_level', LINKSET_TRACKING_LIST);
  523. }
  524. public function GetLinkedClass() {return $this->Get('linked_class');}
  525. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  526. public function GetBasicFilterOperators() {return array();}
  527. public function GetBasicFilterLooseOperator() {return '';}
  528. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  529. public function GetAsHTML($sValue, $oHostObject = null)
  530. {
  531. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  532. {
  533. $sValue->Rewind();
  534. $aItems = array();
  535. while ($oObj = $sValue->Fetch())
  536. {
  537. // Show only relevant information (hide the external key to the current object)
  538. $aAttributes = array();
  539. foreach(MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef)
  540. {
  541. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  542. if ($oAttDef->IsExternalField()) continue;
  543. $sAttValue = $oObj->GetAsHTML($sAttCode);
  544. if (strlen($sAttValue) > 0)
  545. {
  546. $aAttributes[] = $sAttValue;
  547. }
  548. }
  549. $sAttributes = implode(', ', $aAttributes);
  550. $aItems[] = $sAttributes;
  551. }
  552. return implode('<br/>', $aItems);
  553. }
  554. return null;
  555. }
  556. public function GetAsXML($sValue, $oHostObject = null)
  557. {
  558. return "Sorry, no yet implemented";
  559. }
  560. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  561. {
  562. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  563. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  564. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  565. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  566. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  567. {
  568. $sValue->Rewind();
  569. $aItems = array();
  570. while ($oObj = $sValue->Fetch())
  571. {
  572. $sObjClass = get_class($oObj);
  573. // Show only relevant information (hide the external key to the current object)
  574. $aAttributes = array();
  575. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  576. {
  577. if ($sAttCode == 'finalclass')
  578. {
  579. if ($sObjClass == $this->GetLinkedClass())
  580. {
  581. // Simplify the output if the exact class could be determined implicitely
  582. continue;
  583. }
  584. }
  585. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  586. if ($oAttDef->IsExternalField()) continue;
  587. if (!$oAttDef->IsDirectField()) continue;
  588. if (!$oAttDef->IsScalar()) continue;
  589. $sAttValue = $oObj->GetAsCSV($sAttCode, $sSepValue, '');
  590. if (strlen($sAttValue) > 0)
  591. {
  592. $sAttributeData = str_replace($sAttributeQualifier, $sAttributeQualifier.$sAttributeQualifier, $sAttCode.$sSepValue.$sAttValue);
  593. $aAttributes[] = $sAttributeQualifier.$sAttributeData.$sAttributeQualifier;
  594. }
  595. }
  596. $sAttributes = implode($sSepAttribute, $aAttributes);
  597. $aItems[] = $sAttributes;
  598. }
  599. $sRes = implode($sSepItem, $aItems);
  600. }
  601. else
  602. {
  603. $sRes = '';
  604. }
  605. $sRes = str_replace($sTextQualifier, $sTextQualifier.$sTextQualifier, $sRes);
  606. $sRes = $sTextQualifier.$sRes.$sTextQualifier;
  607. return $sRes;
  608. }
  609. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  610. public function GetImportColumns()
  611. {
  612. $aColumns = array();
  613. $aColumns[$this->GetCode()] = 'TEXT';
  614. return $aColumns;
  615. }
  616. // Specific to this kind of attribute : transform a string into a value
  617. public function MakeValueFromString($sProposedValue, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  618. {
  619. if (is_null($sSepItem) || empty($sSepItem))
  620. {
  621. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  622. }
  623. if (is_null($sSepAttribute) || empty($sSepAttribute))
  624. {
  625. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  626. }
  627. if (is_null($sSepValue) || empty($sSepValue))
  628. {
  629. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  630. }
  631. if (is_null($sAttributeQualifier) || empty($sAttributeQualifier))
  632. {
  633. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  634. }
  635. $sTargetClass = $this->Get('linked_class');
  636. $sInput = str_replace($sSepItem, "\n", $sProposedValue);
  637. $oCSVParser = new CSVParser($sInput, $sSepAttribute, $sAttributeQualifier);
  638. $aInput = $oCSVParser->ToArray(0 /* do not skip lines */);
  639. $aLinks = array();
  640. foreach($aInput as $aRow)
  641. {
  642. // 1st - get the values, split the extkey->searchkey specs, and eventually get the finalclass value
  643. $aExtKeys = array();
  644. $aValues = array();
  645. foreach($aRow as $sCell)
  646. {
  647. $iSepPos = strpos($sCell, $sSepValue);
  648. if ($iSepPos === false)
  649. {
  650. // Houston...
  651. throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell));
  652. }
  653. $sAttCode = trim(substr($sCell, 0, $iSepPos));
  654. $sValue = substr($sCell, $iSepPos + strlen($sSepValue));
  655. if (preg_match('/^(.+)->(.+)$/', $sAttCode, $aMatches))
  656. {
  657. $sKeyAttCode = $aMatches[1];
  658. $sRemoteAttCode = $aMatches[2];
  659. $aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue;
  660. if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode))
  661. {
  662. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sKeyAttCode));
  663. }
  664. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  665. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  666. if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode))
  667. {
  668. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode));
  669. }
  670. }
  671. else
  672. {
  673. if(!MetaModel::IsValidAttCode($sTargetClass, $sAttCode))
  674. {
  675. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sAttCode));
  676. }
  677. $aValues[$sAttCode] = $sValue;
  678. }
  679. }
  680. // 2nd - Instanciate the object and set the value
  681. if (isset($aValues['finalclass']))
  682. {
  683. $sLinkClass = $aValues['finalclass'];
  684. if (!is_subclass_of($sLinkClass, $sTargetClass))
  685. {
  686. throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
  687. }
  688. }
  689. elseif (MetaModel::IsAbstract($sTargetClass))
  690. {
  691. throw new CoreException('Missing finalclass for link attribute specification');
  692. }
  693. else
  694. {
  695. $sLinkClass = $sTargetClass;
  696. }
  697. $oLink = MetaModel::NewObject($sLinkClass);
  698. foreach ($aValues as $sAttCode => $sValue)
  699. {
  700. $oLink->Set($sAttCode, $sValue);
  701. }
  702. // 3rd - Set external keys from search conditions
  703. foreach ($aExtKeys as $sKeyAttCode => $aReconciliation)
  704. {
  705. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  706. $sKeyClass = $oKeyAttDef->GetTargetClass();
  707. $oExtKeyFilter = new CMDBSearchFilter($sKeyClass);
  708. $aReconciliationDesc = array();
  709. foreach($aReconciliation as $sRemoteAttCode => $sValue)
  710. {
  711. $oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '=');
  712. $aReconciliationDesc[] = "$sRemoteAttCode=$sValue";
  713. }
  714. $oExtKeySet = new CMDBObjectSet($oExtKeyFilter);
  715. switch($oExtKeySet->Count())
  716. {
  717. case 0:
  718. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  719. throw new CoreException("Found no match", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  720. break;
  721. case 1:
  722. $oRemoteObj = $oExtKeySet->Fetch();
  723. $oLink->Set($sKeyAttCode, $oRemoteObj->GetKey());
  724. break;
  725. default:
  726. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  727. throw new CoreException("Found several matches", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  728. // Found several matches, ambiguous
  729. }
  730. }
  731. // Check (roughly) if such a link is valid
  732. $aErrors = array();
  733. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  734. {
  735. if ($oAttDef->IsExternalKey())
  736. {
  737. if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of($this->GetHostClass(), $oAttDef->GetTargetClass())))
  738. {
  739. continue; // Don't check the key to self
  740. }
  741. }
  742. if ($oAttDef->IsWritable() && $oAttDef->IsNull($oLink->Get($sAttCode)) && !$oAttDef->IsNullAllowed())
  743. {
  744. $aErrors[] = $sAttCode;
  745. }
  746. }
  747. if (count($aErrors) > 0)
  748. {
  749. throw new CoreException("Missing value for mandatory attribute(s): ".implode(', ', $aErrors));
  750. }
  751. $aLinks[] = $oLink;
  752. }
  753. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  754. return $oSet;
  755. }
  756. public function Equals($val1, $val2)
  757. {
  758. if ($val1 === $val2) return true;
  759. if (is_object($val1) != is_object($val2))
  760. {
  761. return false;
  762. }
  763. if (!is_object($val1))
  764. {
  765. // string ?
  766. // todo = implement this case ?
  767. return false;
  768. }
  769. // Both values are Object sets
  770. return $val1->HasSameContents($val2);
  771. }
  772. }
  773. /**
  774. * Set of objects linked to an object (n-n), and being part of its definition
  775. *
  776. * @package iTopORM
  777. */
  778. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  779. {
  780. static public function ListExpectedParams()
  781. {
  782. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  783. }
  784. public function IsIndirect() {return true;}
  785. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  786. public function GetEditClass() {return "LinkedSet";}
  787. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  788. public function GetTrackingLevel()
  789. {
  790. return $this->GetOptional('tracking_level', LINKSET_TRACKING_ALL);
  791. }
  792. }
  793. /**
  794. * Abstract class implementing default filters for a DB column
  795. *
  796. * @package iTopORM
  797. */
  798. class AttributeDBFieldVoid extends AttributeDefinition
  799. {
  800. static public function ListExpectedParams()
  801. {
  802. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  803. }
  804. // To be overriden, used in GetSQLColumns
  805. protected function GetSQLCol() {return "VARCHAR(255)";}
  806. public function GetEditClass() {return "String";}
  807. public function GetValuesDef() {return $this->Get("allowed_values");}
  808. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  809. public function IsDirectField() {return true;}
  810. public function IsScalar() {return true;}
  811. public function IsWritable() {return true;}
  812. public function GetSQLExpr() {return $this->Get("sql");}
  813. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  814. public function IsNullAllowed() {return false;}
  815. //
  816. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  817. public function GetSQLExpressions($sPrefix = '')
  818. {
  819. $aColumns = array();
  820. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  821. $aColumns[''] = $this->Get("sql");
  822. return $aColumns;
  823. }
  824. public function FromSQLToValue($aCols, $sPrefix = '')
  825. {
  826. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  827. return $value;
  828. }
  829. public function GetSQLValues($value)
  830. {
  831. $aValues = array();
  832. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  833. return $aValues;
  834. }
  835. public function GetSQLColumns()
  836. {
  837. $aColumns = array();
  838. $aColumns[$this->Get("sql")] = $this->GetSQLCol();
  839. return $aColumns;
  840. }
  841. public function GetFilterDefinitions()
  842. {
  843. return array($this->GetCode() => new FilterFromAttribute($this));
  844. }
  845. public function GetBasicFilterOperators()
  846. {
  847. return array("="=>"equals", "!="=>"differs from");
  848. }
  849. public function GetBasicFilterLooseOperator()
  850. {
  851. return "=";
  852. }
  853. public function GetBasicFilterSQLExpr($sOpCode, $value)
  854. {
  855. $sQValue = CMDBSource::Quote($value);
  856. switch ($sOpCode)
  857. {
  858. case '!=':
  859. return $this->GetSQLExpr()." != $sQValue";
  860. break;
  861. case '=':
  862. default:
  863. return $this->GetSQLExpr()." = $sQValue";
  864. }
  865. }
  866. }
  867. /**
  868. * Base class for all kind of DB attributes, with the exception of external keys
  869. *
  870. * @package iTopORM
  871. */
  872. class AttributeDBField extends AttributeDBFieldVoid
  873. {
  874. static public function ListExpectedParams()
  875. {
  876. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  877. }
  878. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"), null);}
  879. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  880. }
  881. /**
  882. * Map an integer column to an attribute
  883. *
  884. * @package iTopORM
  885. */
  886. class AttributeInteger extends AttributeDBField
  887. {
  888. static public function ListExpectedParams()
  889. {
  890. return parent::ListExpectedParams();
  891. //return array_merge(parent::ListExpectedParams(), array());
  892. }
  893. public function GetEditClass() {return "String";}
  894. protected function GetSQLCol() {return "INT(11)";}
  895. public function GetValidationPattern()
  896. {
  897. return "^[0-9]+$";
  898. }
  899. public function GetBasicFilterOperators()
  900. {
  901. return array(
  902. "!="=>"differs from",
  903. "="=>"equals",
  904. ">"=>"greater (strict) than",
  905. ">="=>"greater than",
  906. "<"=>"less (strict) than",
  907. "<="=>"less than",
  908. "in"=>"in"
  909. );
  910. }
  911. public function GetBasicFilterLooseOperator()
  912. {
  913. // Unless we implement an "equals approximately..." or "same order of magnitude"
  914. return "=";
  915. }
  916. public function GetBasicFilterSQLExpr($sOpCode, $value)
  917. {
  918. $sQValue = CMDBSource::Quote($value);
  919. switch ($sOpCode)
  920. {
  921. case '!=':
  922. return $this->GetSQLExpr()." != $sQValue";
  923. break;
  924. case '>':
  925. return $this->GetSQLExpr()." > $sQValue";
  926. break;
  927. case '>=':
  928. return $this->GetSQLExpr()." >= $sQValue";
  929. break;
  930. case '<':
  931. return $this->GetSQLExpr()." < $sQValue";
  932. break;
  933. case '<=':
  934. return $this->GetSQLExpr()." <= $sQValue";
  935. break;
  936. case 'in':
  937. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  938. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  939. break;
  940. case '=':
  941. default:
  942. return $this->GetSQLExpr()." = \"$value\"";
  943. }
  944. }
  945. public function GetNullValue()
  946. {
  947. return null;
  948. }
  949. public function IsNull($proposedValue)
  950. {
  951. return is_null($proposedValue);
  952. }
  953. public function MakeRealValue($proposedValue, $oHostObj)
  954. {
  955. if (is_null($proposedValue)) return null;
  956. if ($proposedValue === '') return null; // 0 is transformed into '' !
  957. return (int)$proposedValue;
  958. }
  959. public function ScalarToSQL($value)
  960. {
  961. assert(is_numeric($value) || is_null($value));
  962. return $value; // supposed to be an int
  963. }
  964. }
  965. /**
  966. * Display an integer between 0 and 100 as a percentage / horizontal bar graph
  967. *
  968. * @package iTopORM
  969. */
  970. class AttributePercentage extends AttributeInteger
  971. {
  972. public function GetAsHTML($sValue, $oHostObject = null)
  973. {
  974. $iWidth = 5; // Total width of the percentage bar graph, in em...
  975. $iValue = (int)$sValue;
  976. if ($iValue > 100)
  977. {
  978. $iValue = 100;
  979. }
  980. else if ($iValue < 0)
  981. {
  982. $iValue = 0;
  983. }
  984. if ($iValue > 90)
  985. {
  986. $sColor = "#cc3300";
  987. }
  988. else if ($iValue > 50)
  989. {
  990. $sColor = "#cccc00";
  991. }
  992. else
  993. {
  994. $sColor = "#33cc00";
  995. }
  996. $iPercentWidth = ($iWidth * $iValue) / 100;
  997. 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 %";
  998. }
  999. }
  1000. /**
  1001. * Map a decimal value column (suitable for financial computations) to an attribute
  1002. * internally in PHP such numbers are represented as string. Should you want to perform
  1003. * a calculation on them, it is recommended to use the BC Math functions in order to
  1004. * retain the precision
  1005. *
  1006. * @package iTopORM
  1007. */
  1008. class AttributeDecimal extends AttributeDBField
  1009. {
  1010. static public function ListExpectedParams()
  1011. {
  1012. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  1013. }
  1014. public function GetEditClass() {return "String";}
  1015. protected function GetSQLCol() {return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")";}
  1016. public function GetValidationPattern()
  1017. {
  1018. $iNbDigits = $this->Get('digits');
  1019. $iPrecision = $this->Get('decimals');
  1020. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  1021. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  1022. }
  1023. public function GetBasicFilterOperators()
  1024. {
  1025. return array(
  1026. "!="=>"differs from",
  1027. "="=>"equals",
  1028. ">"=>"greater (strict) than",
  1029. ">="=>"greater than",
  1030. "<"=>"less (strict) than",
  1031. "<="=>"less than",
  1032. "in"=>"in"
  1033. );
  1034. }
  1035. public function GetBasicFilterLooseOperator()
  1036. {
  1037. // Unless we implement an "equals approximately..." or "same order of magnitude"
  1038. return "=";
  1039. }
  1040. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1041. {
  1042. $sQValue = CMDBSource::Quote($value);
  1043. switch ($sOpCode)
  1044. {
  1045. case '!=':
  1046. return $this->GetSQLExpr()." != $sQValue";
  1047. break;
  1048. case '>':
  1049. return $this->GetSQLExpr()." > $sQValue";
  1050. break;
  1051. case '>=':
  1052. return $this->GetSQLExpr()." >= $sQValue";
  1053. break;
  1054. case '<':
  1055. return $this->GetSQLExpr()." < $sQValue";
  1056. break;
  1057. case '<=':
  1058. return $this->GetSQLExpr()." <= $sQValue";
  1059. break;
  1060. case 'in':
  1061. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  1062. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  1063. break;
  1064. case '=':
  1065. default:
  1066. return $this->GetSQLExpr()." = \"$value\"";
  1067. }
  1068. }
  1069. public function GetNullValue()
  1070. {
  1071. return null;
  1072. }
  1073. public function IsNull($proposedValue)
  1074. {
  1075. return is_null($proposedValue);
  1076. }
  1077. public function MakeRealValue($proposedValue, $oHostObj)
  1078. {
  1079. if (is_null($proposedValue)) return null;
  1080. if ($proposedValue == '') return null;
  1081. return (string)$proposedValue;
  1082. }
  1083. public function ScalarToSQL($value)
  1084. {
  1085. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  1086. return (string)$value; // treated as a string
  1087. }
  1088. }
  1089. /**
  1090. * Map a boolean column to an attribute
  1091. *
  1092. * @package iTopORM
  1093. */
  1094. class AttributeBoolean extends AttributeInteger
  1095. {
  1096. static public function ListExpectedParams()
  1097. {
  1098. return parent::ListExpectedParams();
  1099. //return array_merge(parent::ListExpectedParams(), array());
  1100. }
  1101. public function GetEditClass() {return "Integer";}
  1102. protected function GetSQLCol() {return "TINYINT(1)";}
  1103. public function MakeRealValue($proposedValue, $oHostObj)
  1104. {
  1105. if (is_null($proposedValue)) return null;
  1106. if ($proposedValue === '') return null;
  1107. if ((int)$proposedValue) return true;
  1108. return false;
  1109. }
  1110. public function ScalarToSQL($value)
  1111. {
  1112. if ($value) return 1;
  1113. return 0;
  1114. }
  1115. public function GetAsXML($sValue, $oHostObject = null)
  1116. {
  1117. return $sValue ? '1' : '0';
  1118. }
  1119. }
  1120. /**
  1121. * Map a varchar column (size < ?) to an attribute
  1122. *
  1123. * @package iTopORM
  1124. */
  1125. class AttributeString extends AttributeDBField
  1126. {
  1127. static public function ListExpectedParams()
  1128. {
  1129. return parent::ListExpectedParams();
  1130. //return array_merge(parent::ListExpectedParams(), array());
  1131. }
  1132. public function GetEditClass() {return "String";}
  1133. protected function GetSQLCol() {return "VARCHAR(255)";}
  1134. public function GetValidationPattern()
  1135. {
  1136. $sPattern = $this->GetOptional('validation_pattern', '');
  1137. if (empty($sPattern))
  1138. {
  1139. return parent::GetValidationPattern();
  1140. }
  1141. else
  1142. {
  1143. return $sPattern;
  1144. }
  1145. }
  1146. public function CheckFormat($value)
  1147. {
  1148. $sRegExp = $this->GetValidationPattern();
  1149. if (empty($sRegExp))
  1150. {
  1151. return true;
  1152. }
  1153. else
  1154. {
  1155. $sRegExp = str_replace('/', '\\/', $sRegExp);
  1156. return preg_match("/$sRegExp/", $value);
  1157. }
  1158. }
  1159. public function GetMaxSize()
  1160. {
  1161. return 255;
  1162. }
  1163. public function GetBasicFilterOperators()
  1164. {
  1165. return array(
  1166. "="=>"equals",
  1167. "!="=>"differs from",
  1168. "Like"=>"equals (no case)",
  1169. "NotLike"=>"differs from (no case)",
  1170. "Contains"=>"contains",
  1171. "Begins with"=>"begins with",
  1172. "Finishes with"=>"finishes with"
  1173. );
  1174. }
  1175. public function GetBasicFilterLooseOperator()
  1176. {
  1177. return "Contains";
  1178. }
  1179. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1180. {
  1181. $sQValue = CMDBSource::Quote($value);
  1182. switch ($sOpCode)
  1183. {
  1184. case '=':
  1185. case '!=':
  1186. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1187. case 'Begins with':
  1188. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  1189. case 'Finishes with':
  1190. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  1191. case 'Contains':
  1192. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  1193. case 'NotLike':
  1194. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  1195. case 'Like':
  1196. default:
  1197. return $this->GetSQLExpr()." LIKE $sQValue";
  1198. }
  1199. }
  1200. public function GetNullValue()
  1201. {
  1202. return '';
  1203. }
  1204. public function IsNull($proposedValue)
  1205. {
  1206. return ($proposedValue == '');
  1207. }
  1208. public function MakeRealValue($proposedValue, $oHostObj)
  1209. {
  1210. if (is_null($proposedValue)) return '';
  1211. return (string)$proposedValue;
  1212. }
  1213. public function ScalarToSQL($value)
  1214. {
  1215. if (!is_string($value) && !is_null($value))
  1216. {
  1217. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  1218. }
  1219. return $value;
  1220. }
  1221. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1222. {
  1223. $sFrom = array("\r\n", $sTextQualifier);
  1224. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1225. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1226. return $sTextQualifier.$sEscaped.$sTextQualifier;
  1227. }
  1228. public function GetDisplayStyle()
  1229. {
  1230. return $this->GetOptional('display_style', 'select');
  1231. }
  1232. }
  1233. /**
  1234. * An attibute that matches an object class
  1235. *
  1236. * @package iTopORM
  1237. */
  1238. class AttributeClass extends AttributeString
  1239. {
  1240. static public function ListExpectedParams()
  1241. {
  1242. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  1243. }
  1244. public function __construct($sCode, $aParams)
  1245. {
  1246. $this->m_sCode = $sCode;
  1247. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  1248. parent::__construct($sCode, $aParams);
  1249. }
  1250. public function GetDefaultValue()
  1251. {
  1252. $sDefault = parent::GetDefaultValue();
  1253. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  1254. {
  1255. // For this kind of attribute specifying null as default value
  1256. // is authorized even if null is not allowed
  1257. // Pick the first one...
  1258. $aClasses = $this->GetAllowedValues();
  1259. $sDefault = key($aClasses);
  1260. }
  1261. return $sDefault;
  1262. }
  1263. public function GetAsHTML($sValue, $oHostObject = null)
  1264. {
  1265. if (empty($sValue)) return '';
  1266. return MetaModel::GetName($sValue);
  1267. }
  1268. public function RequiresIndex()
  1269. {
  1270. return true;
  1271. }
  1272. public function GetBasicFilterLooseOperator()
  1273. {
  1274. return '=';
  1275. }
  1276. }
  1277. /**
  1278. * An attibute that matches one of the language codes availables in the dictionnary
  1279. *
  1280. * @package iTopORM
  1281. */
  1282. class AttributeApplicationLanguage extends AttributeString
  1283. {
  1284. static public function ListExpectedParams()
  1285. {
  1286. return parent::ListExpectedParams();
  1287. }
  1288. public function __construct($sCode, $aParams)
  1289. {
  1290. $this->m_sCode = $sCode;
  1291. $aAvailableLanguages = Dict::GetLanguages();
  1292. $aLanguageCodes = array();
  1293. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  1294. {
  1295. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  1296. }
  1297. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  1298. parent::__construct($sCode, $aParams);
  1299. }
  1300. public function RequiresIndex()
  1301. {
  1302. return true;
  1303. }
  1304. public function GetBasicFilterLooseOperator()
  1305. {
  1306. return '=';
  1307. }
  1308. }
  1309. /**
  1310. * The attribute dedicated to the finalclass automatic attribute
  1311. *
  1312. * @package iTopORM
  1313. */
  1314. class AttributeFinalClass extends AttributeString
  1315. {
  1316. public function __construct($sCode, $aParams)
  1317. {
  1318. $this->m_sCode = $sCode;
  1319. $aParams["allowed_values"] = null;
  1320. parent::__construct($sCode, $aParams);
  1321. $this->m_sValue = $this->Get("default_value");
  1322. }
  1323. public function IsWritable()
  1324. {
  1325. return false;
  1326. }
  1327. public function RequiresIndex()
  1328. {
  1329. return true;
  1330. }
  1331. public function SetFixedValue($sValue)
  1332. {
  1333. $this->m_sValue = $sValue;
  1334. }
  1335. public function GetDefaultValue()
  1336. {
  1337. return $this->m_sValue;
  1338. }
  1339. public function GetAsHTML($sValue, $oHostObject = null)
  1340. {
  1341. if (empty($sValue)) return '';
  1342. return MetaModel::GetName($sValue);
  1343. }
  1344. public function GetBasicFilterLooseOperator()
  1345. {
  1346. return '=';
  1347. }
  1348. public function GetValueLabel($sValue)
  1349. {
  1350. if (empty($sValue)) return '';
  1351. return MetaModel::GetName($sValue);
  1352. }
  1353. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1354. {
  1355. $aRawValues = MetaModel::EnumChildClasses($this->GetHostClass(), ENUM_CHILD_CLASSES_ALL);
  1356. $aLocalizedValues = array();
  1357. foreach ($aRawValues as $sClass)
  1358. {
  1359. $aLocalizedValues[$sClass] = MetaModel::GetName($sClass);
  1360. }
  1361. return $aLocalizedValues;
  1362. }
  1363. }
  1364. /**
  1365. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  1366. *
  1367. * @package iTopORM
  1368. */
  1369. class AttributePassword extends AttributeString
  1370. {
  1371. static public function ListExpectedParams()
  1372. {
  1373. return parent::ListExpectedParams();
  1374. //return array_merge(parent::ListExpectedParams(), array());
  1375. }
  1376. public function GetEditClass() {return "Password";}
  1377. protected function GetSQLCol() {return "VARCHAR(64)";}
  1378. public function GetMaxSize()
  1379. {
  1380. return 64;
  1381. }
  1382. public function GetFilterDefinitions()
  1383. {
  1384. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  1385. // not allowed to search on passwords!
  1386. return array();
  1387. }
  1388. public function GetAsHTML($sValue, $oHostObject = null)
  1389. {
  1390. if (strlen($sValue) == 0)
  1391. {
  1392. return '';
  1393. }
  1394. else
  1395. {
  1396. return '******';
  1397. }
  1398. }
  1399. }
  1400. /**
  1401. * Map a text column (size < 255) to an attribute that is encrypted in the database
  1402. * The encryption is based on a key set per iTop instance. Thus if you export your
  1403. * database (in SQL) to someone else without providing the key at the same time
  1404. * the encrypted fields will remain encrypted
  1405. *
  1406. * @package iTopORM
  1407. */
  1408. class AttributeEncryptedString extends AttributeString
  1409. {
  1410. static $sKey = null; // Encryption key used for all encrypted fields
  1411. public function __construct($sCode, $aParams)
  1412. {
  1413. parent::__construct($sCode, $aParams);
  1414. if (self::$sKey == null)
  1415. {
  1416. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1417. }
  1418. }
  1419. protected function GetSQLCol() {return "TINYBLOB";}
  1420. public function GetMaxSize()
  1421. {
  1422. return 255;
  1423. }
  1424. public function GetFilterDefinitions()
  1425. {
  1426. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  1427. // not allowed to search on encrypted fields !
  1428. return array();
  1429. }
  1430. public function MakeRealValue($proposedValue, $oHostObj)
  1431. {
  1432. if (is_null($proposedValue)) return null;
  1433. return (string)$proposedValue;
  1434. }
  1435. /**
  1436. * Decrypt the value when reading from the database
  1437. */
  1438. public function FromSQLToValue($aCols, $sPrefix = '')
  1439. {
  1440. $oSimpleCrypt = new SimpleCrypt();
  1441. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  1442. return $sValue;
  1443. }
  1444. /**
  1445. * Encrypt the value before storing it in the database
  1446. */
  1447. public function GetSQLValues($value)
  1448. {
  1449. $oSimpleCrypt = new SimpleCrypt();
  1450. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  1451. $aValues = array();
  1452. $aValues[$this->Get("sql")] = $encryptedValue;
  1453. return $aValues;
  1454. }
  1455. }
  1456. // Wiki formatting - experimental
  1457. //
  1458. // [[<objClass>:<objName>]]
  1459. // Example: [[Server:db1.tnut.com]]
  1460. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  1461. // <url>
  1462. // Example: http://romain:trustno1@127.0.0.1:8888/iTop-trunk/modules/itop-caches/itop-caches.php?agument=machin%20#monAncre
  1463. 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");
  1464. // SHEME............. USER.................... PASSWORD...................... HOST/IP......... PORT.......... PATH...................... GET................................... ANCHOR....................
  1465. // Origin of this regexp: http://www.php.net/manual/fr/function.preg-match.php#93824
  1466. /**
  1467. * Map a text column (size > ?) to an attribute
  1468. *
  1469. * @package iTopORM
  1470. */
  1471. class AttributeText extends AttributeString
  1472. {
  1473. public function GetEditClass() {return "Text";}
  1474. protected function GetSQLCol() {return "TEXT";}
  1475. public function GetMaxSize()
  1476. {
  1477. // Is there a way to know the current limitation for mysql?
  1478. // See mysql_field_len()
  1479. return 65535;
  1480. }
  1481. static public function RenderWikiHtml($sText)
  1482. {
  1483. if (preg_match_all(WIKI_URL, $sText, $aAllMatches, PREG_SET_ORDER /* important !*/ |PREG_OFFSET_CAPTURE /* important ! */))
  1484. {
  1485. $aUrls = array();
  1486. $i = count($aAllMatches);
  1487. // Replace the URLs by an actual hyperlink <a href="...">...</a>
  1488. // Let's do it backwards so that the initial positions are not modified by the replacement
  1489. // This works if the matches are captured: in the order they occur in the string AND
  1490. // with their offset (i.e. position) inside the string
  1491. while($i > 0)
  1492. {
  1493. $i--;
  1494. $sUrl = $aAllMatches[$i][0][0]; // String corresponding to the main pattern
  1495. $iPos = $aAllMatches[$i][0][1]; // Position of the main pattern
  1496. $sText = substr_replace($sText, "<a href=\"$sUrl\">$sUrl</a>", $iPos, strlen($sUrl));
  1497. }
  1498. }
  1499. if (preg_match_all(WIKI_OBJECT_REGEXP, $sText, $aAllMatches, PREG_SET_ORDER))
  1500. {
  1501. foreach($aAllMatches as $iPos => $aMatches)
  1502. {
  1503. $sClass = $aMatches[1];
  1504. $sName = $aMatches[2];
  1505. if (MetaModel::IsValidClass($sClass))
  1506. {
  1507. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  1508. if (is_object($oObj))
  1509. {
  1510. // Propose a std link to the object
  1511. $sText = str_replace($aMatches[0], $oObj->GetHyperlink(), $sText);
  1512. }
  1513. else
  1514. {
  1515. // Propose a std link to the object
  1516. $sClassLabel = MetaModel::GetName($sClass);
  1517. $sText = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sText);
  1518. // Later: propose a link to create a new object
  1519. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  1520. //$sText = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="'.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sText);
  1521. }
  1522. }
  1523. }
  1524. }
  1525. return $sText;
  1526. }
  1527. public function GetAsHTML($sValue, $oHostObject = null)
  1528. {
  1529. $sValue = parent::GetAsHTML($sValue);
  1530. $sValue = self::RenderWikiHtml($sValue);
  1531. $aStyles = array();
  1532. if ($this->GetWidth() != '')
  1533. {
  1534. $aStyles[] = 'width:'.$this->GetWidth();
  1535. }
  1536. if ($this->GetHeight() != '')
  1537. {
  1538. $aStyles[] = 'height:'.$this->GetHeight();
  1539. }
  1540. $sStyle = '';
  1541. if (count($aStyles) > 0)
  1542. {
  1543. $aStyles[] = 'overflow:auto';
  1544. $sStyle = 'style="'.implode(';', $aStyles).'"';
  1545. }
  1546. return "<div $sStyle>".str_replace("\n", "<br>\n", $sValue).'</div>';
  1547. }
  1548. public function GetEditValue($sValue, $oHostObj = null)
  1549. {
  1550. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1551. {
  1552. foreach($aAllMatches as $iPos => $aMatches)
  1553. {
  1554. $sClass = $aMatches[1];
  1555. $sName = $aMatches[2];
  1556. if (MetaModel::IsValidClass($sClass))
  1557. {
  1558. $sClassLabel = MetaModel::GetName($sClass);
  1559. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  1560. }
  1561. }
  1562. }
  1563. return $sValue;
  1564. }
  1565. public function MakeRealValue($proposedValue, $oHostObj)
  1566. {
  1567. $sValue = $proposedValue;
  1568. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1569. {
  1570. foreach($aAllMatches as $iPos => $aMatches)
  1571. {
  1572. $sClassLabel = $aMatches[1];
  1573. $sName = $aMatches[2];
  1574. if (!MetaModel::IsValidClass($sClassLabel))
  1575. {
  1576. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  1577. if ($sClass)
  1578. {
  1579. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  1580. }
  1581. }
  1582. }
  1583. }
  1584. return $sValue;
  1585. }
  1586. public function GetAsXML($value, $oHostObject = null)
  1587. {
  1588. return Str::pure2xml($value);
  1589. }
  1590. public function GetWidth()
  1591. {
  1592. return $this->GetOptional('width', '');
  1593. }
  1594. public function GetHeight()
  1595. {
  1596. return $this->GetOptional('height', '');
  1597. }
  1598. }
  1599. /**
  1600. * Map a log to an attribute
  1601. *
  1602. * @package iTopORM
  1603. */
  1604. class AttributeLongText extends AttributeText
  1605. {
  1606. protected function GetSQLCol() {return "LONGTEXT";}
  1607. public function GetMaxSize()
  1608. {
  1609. // Is there a way to know the current limitation for mysql?
  1610. // See mysql_field_len()
  1611. return 65535*1024; // Limited... still 64 Mb!
  1612. }
  1613. }
  1614. /**
  1615. * An attibute that stores a case log (i.e journal)
  1616. *
  1617. * @package iTopORM
  1618. */
  1619. class AttributeCaseLog extends AttributeLongText
  1620. {
  1621. public function GetNullValue()
  1622. {
  1623. return '';
  1624. }
  1625. public function IsNull($proposedValue)
  1626. {
  1627. if (!($proposedValue instanceof ormCaseLog))
  1628. {
  1629. return ($proposedValue == '');
  1630. }
  1631. return ($proposedValue->GetText() == '');
  1632. }
  1633. public function ScalarToSQL($value)
  1634. {
  1635. if (!is_string($value) && !is_null($value))
  1636. {
  1637. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  1638. }
  1639. return $value;
  1640. }
  1641. public function GetEditClass() {return "CaseLog";}
  1642. public function GetEditValue($sValue, $oHostObj = null)
  1643. {
  1644. if (!($sValue instanceOf ormCaseLog))
  1645. {
  1646. return '';
  1647. }
  1648. return $sValue->GetModifiedEntry();
  1649. }
  1650. public function GetDefaultValue() {return new ormCaseLog();}
  1651. public function Equals($val1, $val2) {return ($val1->GetText() == $val2->GetText());}
  1652. // Facilitate things: allow the user to Set the value from a string
  1653. public function MakeRealValue($proposedValue, $oHostObj)
  1654. {
  1655. if (!($proposedValue instanceof ormCaseLog))
  1656. {
  1657. // Append the new value if an instance of the object is supplied
  1658. //
  1659. $oPreviousLog = null;
  1660. if ($oHostObj != null)
  1661. {
  1662. $oPreviousLog = $oHostObj->Get($this->GetCode());
  1663. if (!is_object($oPreviousLog))
  1664. {
  1665. $oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
  1666. }
  1667. }
  1668. if (is_object($oPreviousLog))
  1669. {
  1670. $oCaseLog = clone($oPreviousLog);
  1671. }
  1672. else
  1673. {
  1674. $oCaseLog = new ormCaseLog();
  1675. }
  1676. if (strlen($proposedValue) > 0)
  1677. {
  1678. $oCaseLog->AddLogEntry(parent::MakeRealValue($proposedValue, $oHostObj));
  1679. }
  1680. return $oCaseLog;
  1681. }
  1682. return $proposedValue;
  1683. }
  1684. public function GetSQLExpressions($sPrefix = '')
  1685. {
  1686. if ($sPrefix == '')
  1687. {
  1688. $sPrefix = $this->GetCode();
  1689. }
  1690. $aColumns = array();
  1691. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1692. $aColumns[''] = $sPrefix;
  1693. $aColumns['_index'] = $sPrefix.'_index';
  1694. return $aColumns;
  1695. }
  1696. public function FromSQLToValue($aCols, $sPrefix = '')
  1697. {
  1698. if (!isset($aCols[$sPrefix]))
  1699. {
  1700. $sAvailable = implode(', ', array_keys($aCols));
  1701. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1702. }
  1703. $sLog = $aCols[$sPrefix];
  1704. if (isset($aCols[$sPrefix.'_index']))
  1705. {
  1706. $sIndex = $aCols[$sPrefix.'_index'];
  1707. }
  1708. else
  1709. {
  1710. // For backward compatibility, allow the current state to be: 1 log, no index
  1711. $sIndex = '';
  1712. }
  1713. if (strlen($sIndex) > 0)
  1714. {
  1715. $aIndex = unserialize($sIndex);
  1716. $value = new ormCaseLog($sLog, $aIndex);
  1717. }
  1718. else
  1719. {
  1720. $value = new ormCaseLog($sLog);
  1721. }
  1722. return $value;
  1723. }
  1724. public function GetSQLValues($value)
  1725. {
  1726. if (!($value instanceOf ormCaseLog))
  1727. {
  1728. $value = new ormCaseLog('');
  1729. }
  1730. $aValues = array();
  1731. $aValues[$this->GetCode()] = $value->GetText();
  1732. $aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
  1733. return $aValues;
  1734. }
  1735. public function GetSQLColumns()
  1736. {
  1737. $aColumns = array();
  1738. $aColumns[$this->GetCode()] = 'LONGTEXT'; // 2^32 (4 Gb)
  1739. $aColumns[$this->GetCode().'_index'] = 'BLOB';
  1740. return $aColumns;
  1741. }
  1742. public function GetAsHTML($value, $oHostObject = null)
  1743. {
  1744. if ($value instanceOf ormCaseLog)
  1745. {
  1746. $sContent = $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
  1747. }
  1748. else
  1749. {
  1750. $sContent = '';
  1751. }
  1752. $aStyles = array();
  1753. if ($this->GetWidth() != '')
  1754. {
  1755. $aStyles[] = 'width:'.$this->GetWidth();
  1756. }
  1757. if ($this->GetHeight() != '')
  1758. {
  1759. $aStyles[] = 'height:'.$this->GetHeight();
  1760. }
  1761. $sStyle = '';
  1762. if (count($aStyles) > 0)
  1763. {
  1764. $sStyle = 'style="'.implode(';', $aStyles).'"';
  1765. }
  1766. return "<div class=\"caselog\" $sStyle>".$sContent.'</div>'; }
  1767. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1768. {
  1769. if ($value instanceOf ormCaseLog)
  1770. {
  1771. return parent::GetAsCSV($value->GetText(), $sSeparator, $sTextQualifier, $oHostObject);
  1772. }
  1773. else
  1774. {
  1775. return '';
  1776. }
  1777. }
  1778. public function GetAsXML($value, $oHostObject = null)
  1779. {
  1780. if ($value instanceOf ormCaseLog)
  1781. {
  1782. return parent::GetAsXML($value->GetText(), $oHostObject);
  1783. }
  1784. else
  1785. {
  1786. return '';
  1787. }
  1788. }
  1789. }
  1790. /**
  1791. * Map a text column (size > ?), containing HTML code, to an attribute
  1792. *
  1793. * @package iTopORM
  1794. */
  1795. class AttributeHTML extends AttributeLongText
  1796. {
  1797. public function GetEditClass() {return "HTML";}
  1798. public function GetAsHTML($sValue, $oHostObject = null)
  1799. {
  1800. return $sValue;
  1801. }
  1802. }
  1803. /**
  1804. * Specialization of a string: email
  1805. *
  1806. * @package iTopORM
  1807. */
  1808. class AttributeEmailAddress extends AttributeString
  1809. {
  1810. public function GetValidationPattern()
  1811. {
  1812. // return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  1813. return "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$";
  1814. }
  1815. public function GetAsHTML($sValue, $oHostObject = null)
  1816. {
  1817. if (empty($sValue)) return '';
  1818. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  1819. }
  1820. }
  1821. /**
  1822. * Specialization of a string: IP address
  1823. *
  1824. * @package iTopORM
  1825. */
  1826. class AttributeIPAddress extends AttributeString
  1827. {
  1828. public function GetValidationPattern()
  1829. {
  1830. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  1831. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  1832. }
  1833. public function GetOrderBySQLExpressions($sClassAlias)
  1834. {
  1835. // Note: This is the responsibility of this function to place backticks around column aliases
  1836. return array('INET_ATON(`'.$sClassAlias.$this->GetCode().'`)');
  1837. }
  1838. }
  1839. /**
  1840. * Specialization of a string: OQL expression
  1841. *
  1842. * @package iTopORM
  1843. */
  1844. class AttributeOQL extends AttributeText
  1845. {
  1846. public function GetEditClass() {return "OQLExpression";}
  1847. }
  1848. /**
  1849. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1850. *
  1851. * @package iTopORM
  1852. */
  1853. class AttributeTemplateString extends AttributeString
  1854. {
  1855. }
  1856. /**
  1857. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1858. *
  1859. * @package iTopORM
  1860. */
  1861. class AttributeTemplateText extends AttributeText
  1862. {
  1863. }
  1864. /**
  1865. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1866. *
  1867. * @package iTopORM
  1868. */
  1869. class AttributeTemplateHTML extends AttributeText
  1870. {
  1871. public function GetEditClass() {return "HTML";}
  1872. public function GetAsHTML($sValue, $oHostObject = null)
  1873. {
  1874. return $sValue;
  1875. }
  1876. }
  1877. /**
  1878. * Map a enum column to an attribute
  1879. *
  1880. * @package iTopORM
  1881. */
  1882. class AttributeEnum extends AttributeString
  1883. {
  1884. static public function ListExpectedParams()
  1885. {
  1886. return parent::ListExpectedParams();
  1887. //return array_merge(parent::ListExpectedParams(), array());
  1888. }
  1889. public function GetEditClass() {return "String";}
  1890. protected function GetSQLCol()
  1891. {
  1892. $oValDef = $this->GetValuesDef();
  1893. if ($oValDef)
  1894. {
  1895. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  1896. }
  1897. else
  1898. {
  1899. $aValues = array();
  1900. }
  1901. if (count($aValues) > 0)
  1902. {
  1903. // The syntax used here do matters
  1904. // In particular, I had to remove unnecessary spaces to
  1905. // make sure that this string will match the field type returned by the DB
  1906. // (used to perform a comparison between the current DB format and the data model)
  1907. return "ENUM(".implode(",", $aValues).")";
  1908. }
  1909. else
  1910. {
  1911. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  1912. }
  1913. }
  1914. public function ScalarToSQL($value)
  1915. {
  1916. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  1917. // but that wasn't working for enums, because '' is NOT one of the allowed values
  1918. // that's why a null value must be forced to a real null
  1919. $value = parent::ScalarToSQL($value);
  1920. if ($this->IsNull($value))
  1921. {
  1922. return null;
  1923. }
  1924. else
  1925. {
  1926. return $value;
  1927. }
  1928. }
  1929. public function RequiresIndex()
  1930. {
  1931. return false;
  1932. }
  1933. public function GetBasicFilterOperators()
  1934. {
  1935. return parent::GetBasicFilterOperators();
  1936. }
  1937. public function GetBasicFilterLooseOperator()
  1938. {
  1939. return '=';
  1940. }
  1941. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1942. {
  1943. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1944. }
  1945. public function GetValueLabel($sValue)
  1946. {
  1947. if (is_null($sValue))
  1948. {
  1949. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1950. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  1951. }
  1952. else
  1953. {
  1954. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, '');
  1955. if (strlen($sLabel) == 0)
  1956. {
  1957. $sLabel = str_replace('_', ' ', $sValue);
  1958. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  1959. if ($sParentClass)
  1960. {
  1961. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  1962. {
  1963. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  1964. $sLabel = $oAttDef->GetValueLabel($sValue);
  1965. }
  1966. }
  1967. }
  1968. }
  1969. return $sLabel;
  1970. }
  1971. public function GetValueDescription($sValue)
  1972. {
  1973. if (is_null($sValue))
  1974. {
  1975. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1976. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', Dict::S('Enum:Undefined'));
  1977. }
  1978. else
  1979. {
  1980. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', '');
  1981. if (strlen($sDescription) == 0)
  1982. {
  1983. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  1984. if ($sParentClass)
  1985. {
  1986. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  1987. {
  1988. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  1989. $sDescription = $oAttDef->GetValueDescription($sValue);
  1990. }
  1991. }
  1992. }
  1993. }
  1994. return $sDescription;
  1995. }
  1996. public function GetAsHTML($sValue, $oHostObject = null)
  1997. {
  1998. $sLabel = $this->GetValueLabel($sValue);
  1999. $sDescription = $this->GetValueDescription($sValue);
  2000. // later, we could imagine a detailed description in the title
  2001. return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  2002. }
  2003. public function GetEditValue($sValue, $oHostObj = null)
  2004. {
  2005. return $this->GetValueLabel($sValue);
  2006. }
  2007. public function GetAsHTMLForHistory($sOldValue, $sNewValue, $sLabel = null)
  2008. {
  2009. $sOldValue = is_null($sOldValue) ? null : $this->GetAsHTML($sOldValue);
  2010. $sNewValue = is_null($sNewValue) ? null : $this->GetAsHTML($sNewValue);
  2011. $sResult = parent::GetAsHTMLForHistory($sOldValue, $sNewValue, $sLabel);
  2012. return $sResult;
  2013. }
  2014. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2015. {
  2016. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  2017. if (is_null($aRawValues)) return null;
  2018. $aLocalizedValues = array();
  2019. foreach ($aRawValues as $sKey => $sValue)
  2020. {
  2021. $aLocalizedValues[$sKey] = $this->GetValueLabel($sKey);
  2022. }
  2023. return $aLocalizedValues;
  2024. }
  2025. /**
  2026. * Processes the input value to align it with the values supported
  2027. * by this type of attribute. In this case: turns empty strings into nulls
  2028. * @param mixed $proposedValue The value to be set for the attribute
  2029. * @return mixed The actual value that will be set
  2030. */
  2031. public function MakeRealValue($proposedValue, $oHostObj)
  2032. {
  2033. if ($proposedValue == '') return null;
  2034. return parent::MakeRealValue($proposedValue, $oHostObj);
  2035. }
  2036. public function GetOrderByHint()
  2037. {
  2038. $aValues = $this->GetAllowedValues();
  2039. return Dict::Format('UI:OrderByHint_Values', implode(', ', $aValues));
  2040. }
  2041. }
  2042. /**
  2043. * Map a date+time column to an attribute
  2044. *
  2045. * @package iTopORM
  2046. */
  2047. class AttributeDateTime extends AttributeDBField
  2048. {
  2049. static protected function GetDateFormat()
  2050. {
  2051. return "Y-m-d H:i:s";
  2052. }
  2053. static public function ListExpectedParams()
  2054. {
  2055. return parent::ListExpectedParams();
  2056. //return array_merge(parent::ListExpectedParams(), array());
  2057. }
  2058. public function GetEditClass() {return "DateTime";}
  2059. protected function GetSQLCol() {return "TIMESTAMP";}
  2060. public static function GetAsUnixSeconds($value)
  2061. {
  2062. $oDeadlineDateTime = new DateTime($value);
  2063. $iUnixSeconds = $oDeadlineDateTime->format('U');
  2064. return $iUnixSeconds;
  2065. }
  2066. // #@# THIS HAS TO REVISED
  2067. // Having null not allowed was interpreted by mySQL
  2068. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  2069. // Then, on each update of the record, the field was modified.
  2070. // We will have to specify the default value if we want to restore this option
  2071. // In fact, we could also have more verbs dedicated to the DB:
  2072. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  2073. public function IsNullAllowed() {return true;}
  2074. public function GetDefaultValue()
  2075. {
  2076. $default = parent::GetDefaultValue();
  2077. if (!parent::IsNullAllowed())
  2078. {
  2079. if (empty($default))
  2080. {
  2081. $default = date($this->GetDateFormat());
  2082. }
  2083. }
  2084. return $default;
  2085. }
  2086. // END OF THE WORKAROUND
  2087. ///////////////////////////////////////////////////////////////
  2088. public function GetValidationPattern()
  2089. {
  2090. 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$";
  2091. }
  2092. public function GetBasicFilterOperators()
  2093. {
  2094. return array(
  2095. "="=>"equals",
  2096. "!="=>"differs from",
  2097. "<"=>"before",
  2098. "<="=>"before",
  2099. ">"=>"after (strictly)",
  2100. ">="=>"after",
  2101. "SameDay"=>"same day (strip time)",
  2102. "SameMonth"=>"same year/month",
  2103. "SameYear"=>"same year",
  2104. "Today"=>"today",
  2105. ">|"=>"after today + N days",
  2106. "<|"=>"before today + N days",
  2107. "=|"=>"equals today + N days",
  2108. );
  2109. }
  2110. public function GetBasicFilterLooseOperator()
  2111. {
  2112. // Unless we implement a "same xxx, depending on given precision" !
  2113. return "=";
  2114. }
  2115. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2116. {
  2117. $sQValue = CMDBSource::Quote($value);
  2118. switch ($sOpCode)
  2119. {
  2120. case '=':
  2121. case '!=':
  2122. case '<':
  2123. case '<=':
  2124. case '>':
  2125. case '>=':
  2126. return $this->GetSQLExpr()." $sOpCode $sQValue";
  2127. case 'SameDay':
  2128. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  2129. case 'SameMonth':
  2130. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  2131. case 'SameYear':
  2132. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  2133. case 'Today':
  2134. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  2135. case '>|':
  2136. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2137. case '<|':
  2138. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2139. case '=|':
  2140. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2141. default:
  2142. return $this->GetSQLExpr()." = $sQValue";
  2143. }
  2144. }
  2145. public function MakeRealValue($proposedValue, $oHostObj)
  2146. {
  2147. if (is_null($proposedValue))
  2148. {
  2149. return null;
  2150. }
  2151. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  2152. {
  2153. return null;
  2154. }
  2155. if (!is_numeric($proposedValue))
  2156. {
  2157. return $proposedValue;
  2158. }
  2159. return date(self::GetDateFormat(), $proposedValue);
  2160. }
  2161. public function ScalarToSQL($value)
  2162. {
  2163. if (is_null($value))
  2164. {
  2165. return null;
  2166. }
  2167. elseif (empty($value))
  2168. {
  2169. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  2170. return '0000-00-00 00:00:00';
  2171. }
  2172. return $value;
  2173. }
  2174. public function GetAsHTML($value, $oHostObject = null)
  2175. {
  2176. return Str::pure2html($value);
  2177. }
  2178. public function GetAsXML($value, $oHostObject = null)
  2179. {
  2180. return Str::pure2xml($value);
  2181. }
  2182. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2183. {
  2184. $sFrom = array("\r\n", $sTextQualifier);
  2185. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  2186. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  2187. return '"'.$sEscaped.'"';
  2188. }
  2189. /**
  2190. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  2191. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  2192. * does nothing special, and just calls the default (loose) operator
  2193. * @param string $sSearchText The search string to analyze for smart patterns
  2194. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  2195. * @param Hash $aParams Values of the query parameters
  2196. * @return Expression The search condition to be added (AND) to the current search
  2197. */
  2198. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  2199. {
  2200. // Possible smart patterns
  2201. $aPatterns = array(
  2202. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  2203. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  2204. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  2205. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  2206. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  2207. );
  2208. $sPatternFound = '';
  2209. $aMatches = array();
  2210. foreach($aPatterns as $sPatName => $sPattern)
  2211. {
  2212. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  2213. {
  2214. $sPatternFound = $sPatName;
  2215. break;
  2216. }
  2217. }
  2218. switch($sPatternFound)
  2219. {
  2220. case 'between':
  2221. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  2222. $oRightExpr = new VariableExpression($sParamName1);
  2223. $aParams[$sParamName1] = $aMatches[1];
  2224. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  2225. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  2226. $oRightExpr = new VariableExpression($sParamName2);
  2227. $sOperator = $this->GetBasicFilterLooseOperator();
  2228. $aParams[$sParamName2] = $aMatches[2];
  2229. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  2230. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  2231. break;
  2232. case 'greater than':
  2233. case 'greater than or equal':
  2234. case 'less than':
  2235. case 'less than or equal':
  2236. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  2237. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  2238. $oRightExpr = new VariableExpression($sParamName);
  2239. $aParams[$sParamName] = $aMatches[1];
  2240. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  2241. break;
  2242. default:
  2243. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  2244. }
  2245. return $oNewCondition;
  2246. }
  2247. }
  2248. /**
  2249. * Store a duration as a number of seconds
  2250. *
  2251. * @package iTopORM
  2252. */
  2253. class AttributeDuration extends AttributeInteger
  2254. {
  2255. public function GetEditClass() {return "Duration";}
  2256. protected function GetSQLCol() {return "INT(11) UNSIGNED";}
  2257. public function GetNullValue() {return '0';}
  2258. public function GetDefaultValue()
  2259. {
  2260. return 0;
  2261. }
  2262. public function MakeRealValue($proposedValue, $oHostObj)
  2263. {
  2264. if (is_null($proposedValue)) return null;
  2265. if (!is_numeric($proposedValue)) return null;
  2266. if ( ((int)$proposedValue) < 0) return null;
  2267. return (int)$proposedValue;
  2268. }
  2269. public function ScalarToSQL($value)
  2270. {
  2271. if (is_null($value))
  2272. {
  2273. return null;
  2274. }
  2275. return $value;
  2276. }
  2277. public function GetAsHTML($value, $oHostObject = null)
  2278. {
  2279. return Str::pure2html(self::FormatDuration($value));
  2280. }
  2281. public static function FormatDuration($duration)
  2282. {
  2283. $aDuration = self::SplitDuration($duration);
  2284. $sResult = '';
  2285. if ($duration < 60)
  2286. {
  2287. // Less than 1 min
  2288. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  2289. }
  2290. else if ($duration < 3600)
  2291. {
  2292. // less than 1 hour, display it in minutes/seconds
  2293. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  2294. }
  2295. else if ($duration < 86400)
  2296. {
  2297. // Less than 1 day, display it in hours/minutes/seconds
  2298. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2299. }
  2300. else
  2301. {
  2302. // more than 1 day, display it in days/hours/minutes/seconds
  2303. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2304. }
  2305. return $sResult;
  2306. }
  2307. static function SplitDuration($duration)
  2308. {
  2309. $duration = (int) $duration;
  2310. $days = floor($duration / 86400);
  2311. $hours = floor(($duration - (86400*$days)) / 3600);
  2312. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2313. $seconds = ($duration % 60); // modulo
  2314. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  2315. }
  2316. }
  2317. /**
  2318. * Map a date+time column to an attribute
  2319. *
  2320. * @package iTopORM
  2321. */
  2322. class AttributeDate extends AttributeDateTime
  2323. {
  2324. const MYDATEFORMAT = "Y-m-d";
  2325. static protected function GetDateFormat()
  2326. {
  2327. return "Y-m-d";
  2328. }
  2329. static public function ListExpectedParams()
  2330. {
  2331. return parent::ListExpectedParams();
  2332. //return array_merge(parent::ListExpectedParams(), array());
  2333. }
  2334. public function GetEditClass() {return "Date";}
  2335. protected function GetSQLCol() {return "DATE";}
  2336. public function GetValidationPattern()
  2337. {
  2338. 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)))$";
  2339. }
  2340. }
  2341. /**
  2342. * A dead line stored as a date & time
  2343. * The only difference with the DateTime attribute is the display:
  2344. * relative to the current time
  2345. */
  2346. class AttributeDeadline extends AttributeDateTime
  2347. {
  2348. public function GetAsHTML($value, $oHostObject = null)
  2349. {
  2350. $sResult = self::FormatDeadline($value);
  2351. return $sResult;
  2352. }
  2353. public static function FormatDeadline($value)
  2354. {
  2355. $sResult = '';
  2356. if ($value !== null)
  2357. {
  2358. $iValue = AttributeDateTime::GetAsUnixSeconds($value);
  2359. $sDate = $value;
  2360. $difference = $iValue - time();
  2361. if ($difference >= 0)
  2362. {
  2363. $sDifference = self::FormatDuration($difference);
  2364. }
  2365. else
  2366. {
  2367. $sDifference = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  2368. }
  2369. $sFormat = MetaModel::GetConfig()->Get('deadline_format', '$difference$');
  2370. $sResult = str_replace(array('$date$', '$difference$'), array($sDate, $sDifference), $sFormat);
  2371. }
  2372. return $sResult;
  2373. }
  2374. static function FormatDuration($duration)
  2375. {
  2376. $days = floor($duration / 86400);
  2377. $hours = floor(($duration - (86400*$days)) / 3600);
  2378. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2379. $sResult = '';
  2380. if ($duration < 60)
  2381. {
  2382. // Less than 1 min
  2383. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  2384. }
  2385. else if ($duration < 3600)
  2386. {
  2387. // less than 1 hour, display it in minutes
  2388. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  2389. }
  2390. else if ($duration < 86400)
  2391. {
  2392. // Less that 1 day, display it in hours/minutes
  2393. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  2394. }
  2395. else
  2396. {
  2397. // Less that 1 day, display it in hours/minutes
  2398. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  2399. }
  2400. return $sResult;
  2401. }
  2402. }
  2403. /**
  2404. * Map a foreign key to an attribute
  2405. * AttributeExternalKey and AttributeExternalField may be an external key
  2406. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  2407. * where an AttributeExternalField corresponds to a column into another table (class)
  2408. *
  2409. * @package iTopORM
  2410. */
  2411. class AttributeExternalKey extends AttributeDBFieldVoid
  2412. {
  2413. static public function ListExpectedParams()
  2414. {
  2415. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  2416. }
  2417. public function GetEditClass() {return "ExtKey";}
  2418. protected function GetSQLCol() {return "INT(11)";}
  2419. public function RequiresIndex()
  2420. {
  2421. return true;
  2422. }
  2423. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  2424. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  2425. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2426. public function GetKeyAttCode() {return $this->GetCode();}
  2427. public function GetDisplayStyle() { return $this->GetOptional('display_style', 'select'); }
  2428. public function GetDefaultValue() {return 0;}
  2429. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  2430. public function GetBasicFilterOperators()
  2431. {
  2432. return parent::GetBasicFilterOperators();
  2433. }
  2434. public function GetBasicFilterLooseOperator()
  2435. {
  2436. return parent::GetBasicFilterLooseOperator();
  2437. }
  2438. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2439. {
  2440. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2441. }
  2442. // overloaded here so that an ext key always have the answer to
  2443. // "what are your possible values?"
  2444. public function GetValuesDef()
  2445. {
  2446. $oValSetDef = $this->Get("allowed_values");
  2447. if (!$oValSetDef)
  2448. {
  2449. // Let's propose every existing value
  2450. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2451. }
  2452. return $oValSetDef;
  2453. }
  2454. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2455. {
  2456. //throw new Exception("GetAllowedValues on ext key has been deprecated");
  2457. try
  2458. {
  2459. return parent::GetAllowedValues($aArgs, $sContains);
  2460. }
  2461. catch (MissingQueryArgument $e)
  2462. {
  2463. // Some required arguments could not be found, enlarge to any existing value
  2464. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2465. return $oValSetDef->GetValues($aArgs, $sContains);
  2466. }
  2467. }
  2468. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  2469. {
  2470. $oValSetDef = $this->GetValuesDef();
  2471. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  2472. return $oSet;
  2473. }
  2474. public function GetDeletionPropagationOption()
  2475. {
  2476. return $this->Get("on_target_delete");
  2477. }
  2478. public function GetNullValue()
  2479. {
  2480. return 0;
  2481. }
  2482. public function IsNull($proposedValue)
  2483. {
  2484. return ($proposedValue == 0);
  2485. }
  2486. public function MakeRealValue($proposedValue, $oHostObj)
  2487. {
  2488. if (is_null($proposedValue)) return 0;
  2489. if ($proposedValue === '') return 0;
  2490. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  2491. return (int)$proposedValue;
  2492. }
  2493. public function GetMaximumComboLength()
  2494. {
  2495. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  2496. }
  2497. public function GetMinAutoCompleteChars()
  2498. {
  2499. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  2500. }
  2501. public function AllowTargetCreation()
  2502. {
  2503. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  2504. }
  2505. }
  2506. /**
  2507. * Special kind of External Key to manage a hierarchy of objects
  2508. */
  2509. class AttributeHierarchicalKey extends AttributeExternalKey
  2510. {
  2511. protected $m_sTargetClass;
  2512. static public function ListExpectedParams()
  2513. {
  2514. $aParams = parent::ListExpectedParams();
  2515. $idx = array_search('targetclass', $aParams);
  2516. unset($aParams[$idx]);
  2517. $idx = array_search('jointype', $aParams);
  2518. unset($aParams[$idx]);
  2519. return $aParams; // TODO: mettre les bons parametres ici !!
  2520. }
  2521. public function GetEditClass() {return "ExtKey";}
  2522. public function RequiresIndex()
  2523. {
  2524. return true;
  2525. }
  2526. /*
  2527. * The target class is the class for which the attribute has been defined first
  2528. */
  2529. public function SetHostClass($sHostClass)
  2530. {
  2531. if (!isset($this->m_sTargetClass))
  2532. {
  2533. $this->m_sTargetClass = $sHostClass;
  2534. }
  2535. parent::SetHostClass($sHostClass);
  2536. }
  2537. public function IsHierarchicalKey() {return true;}
  2538. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->m_sTargetClass;}
  2539. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2540. public function GetKeyAttCode() {return $this->GetCode();}
  2541. public function GetBasicFilterOperators()
  2542. {
  2543. return parent::GetBasicFilterOperators();
  2544. }
  2545. public function GetBasicFilterLooseOperator()
  2546. {
  2547. return parent::GetBasicFilterLooseOperator();
  2548. }
  2549. public function GetSQLColumns()
  2550. {
  2551. $aColumns = array();
  2552. $aColumns[$this->GetCode()] = 'INT(11)';
  2553. $aColumns[$this->GetSQLLeft()] = 'INT(11)';
  2554. $aColumns[$this->GetSQLRight()] = 'INT(11)';
  2555. return $aColumns;
  2556. }
  2557. public function GetSQLRight()
  2558. {
  2559. return $this->GetCode().'_right';
  2560. }
  2561. public function GetSQLLeft()
  2562. {
  2563. return $this->GetCode().'_left';
  2564. }
  2565. public function GetSQLValues($value)
  2566. {
  2567. if (!is_array($value))
  2568. {
  2569. $aValues[$this->GetCode()] = $value;
  2570. }
  2571. else
  2572. {
  2573. $aValues = array();
  2574. $aValues[$this->GetCode()] = $value[$this->GetCode()];
  2575. $aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
  2576. $aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
  2577. }
  2578. return $aValues;
  2579. }
  2580. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2581. {
  2582. if (array_key_exists('this', $aArgs))
  2583. {
  2584. // Hierarchical keys have one more constraint: the "parent value" cannot be
  2585. // "under" themselves
  2586. $iRootId = $aArgs['this']->GetKey();
  2587. if ($iRootId > 0) // ignore objects that do no exist in the database...
  2588. {
  2589. $oValSetDef = $this->GetValuesDef();
  2590. $sClass = $this->m_sTargetClass;
  2591. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  2592. $oValSetDef->AddCondition($oFilter);
  2593. }
  2594. }
  2595. else
  2596. {
  2597. return parent::GetAllowedValues($aArgs, $sContains);
  2598. }
  2599. }
  2600. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  2601. {
  2602. $oValSetDef = $this->GetValuesDef();
  2603. if (array_key_exists('this', $aArgs))
  2604. {
  2605. // Hierarchical keys have one more constraint: the "parent value" cannot be
  2606. // "under" themselves
  2607. $iRootId = $aArgs['this']->GetKey();
  2608. if ($iRootId > 0) // ignore objects that do no exist in the database...
  2609. {
  2610. $aValuesSetDef = $this->GetValuesDef();
  2611. $sClass = $this->m_sTargetClass;
  2612. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  2613. $oValSetDef->AddCondition($oFilter);
  2614. }
  2615. }
  2616. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  2617. return $oSet;
  2618. }
  2619. }
  2620. /**
  2621. * An attribute which corresponds to an external key (direct or indirect)
  2622. *
  2623. * @package iTopORM
  2624. */
  2625. class AttributeExternalField extends AttributeDefinition
  2626. {
  2627. static public function ListExpectedParams()
  2628. {
  2629. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  2630. }
  2631. public function GetEditClass() {return "ExtField";}
  2632. public function GetFinalAttDef()
  2633. {
  2634. $oExtAttDef = $this->GetExtAttDef();
  2635. return $oExtAttDef->GetFinalAttDef();
  2636. }
  2637. protected function GetSQLCol()
  2638. {
  2639. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  2640. $oExtAttDef = $this->GetExtAttDef();
  2641. return $oExtAttDef->GetSQLCol();
  2642. }
  2643. public function GetSQLExpressions($sPrefix = '')
  2644. {
  2645. if ($sPrefix == '')
  2646. {
  2647. return array('' => $this->GetCode());
  2648. }
  2649. else
  2650. {
  2651. return $sPrefix;
  2652. }
  2653. }
  2654. public function GetLabel($sDefault = null)
  2655. {
  2656. $sLabel = parent::GetLabel('');
  2657. if (strlen($sLabel) == 0)
  2658. {
  2659. $oRemoteAtt = $this->GetExtAttDef();
  2660. $sLabel = $oRemoteAtt->GetLabel($this->m_sCode);
  2661. }
  2662. return $sLabel;
  2663. }
  2664. public function GetDescription($sDefault = null)
  2665. {
  2666. $sLabel = parent::GetDescription('');
  2667. if (strlen($sLabel) == 0)
  2668. {
  2669. $oRemoteAtt = $this->GetExtAttDef();
  2670. $sLabel = $oRemoteAtt->GetDescription('');
  2671. }
  2672. return $sLabel;
  2673. }
  2674. public function GetHelpOnEdition($sDefault = null)
  2675. {
  2676. $sLabel = parent::GetHelpOnEdition('');
  2677. if (strlen($sLabel) == 0)
  2678. {
  2679. $oRemoteAtt = $this->GetExtAttDef();
  2680. $sLabel = $oRemoteAtt->GetHelpOnEdition('');
  2681. }
  2682. return $sLabel;
  2683. }
  2684. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  2685. {
  2686. switch($iType)
  2687. {
  2688. case EXTKEY_ABSOLUTE:
  2689. // see further
  2690. $oRemoteAtt = $this->GetExtAttDef();
  2691. return $oRemoteAtt->IsExternalKey($iType);
  2692. case EXTKEY_RELATIVE:
  2693. return false;
  2694. default:
  2695. throw new CoreException("Unexpected value for argument iType: '$iType'");
  2696. }
  2697. }
  2698. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  2699. {
  2700. return $this->GetKeyAttDef($iType)->GetTargetClass();
  2701. }
  2702. public function IsExternalField() {return true;}
  2703. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  2704. public function GetExtAttCode() {return $this->Get("target_attcode");}
  2705. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  2706. {
  2707. switch($iType)
  2708. {
  2709. case EXTKEY_ABSOLUTE:
  2710. // see further
  2711. $oRemoteAtt = $this->GetExtAttDef();
  2712. if ($oRemoteAtt->IsExternalField())
  2713. {
  2714. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  2715. }
  2716. else if ($oRemoteAtt->IsExternalKey())
  2717. {
  2718. return $oRemoteAtt;
  2719. }
  2720. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  2721. case EXTKEY_RELATIVE:
  2722. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  2723. default:
  2724. throw new CoreException("Unexpected value for argument iType: '$iType'");
  2725. }
  2726. }
  2727. public function GetExtAttDef()
  2728. {
  2729. $oKeyAttDef = $this->GetKeyAttDef();
  2730. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $this->Get("target_attcode"));
  2731. 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"));
  2732. return $oExtAttDef;
  2733. }
  2734. public function GetSQLExpr()
  2735. {
  2736. $oExtAttDef = $this->GetExtAttDef();
  2737. return $oExtAttDef->GetSQLExpr();
  2738. }
  2739. public function GetDefaultValue()
  2740. {
  2741. $oExtAttDef = $this->GetExtAttDef();
  2742. return $oExtAttDef->GetDefaultValue();
  2743. }
  2744. public function IsNullAllowed()
  2745. {
  2746. $oExtAttDef = $this->GetExtAttDef();
  2747. return $oExtAttDef->IsNullAllowed();
  2748. }
  2749. public function IsScalar()
  2750. {
  2751. $oExtAttDef = $this->GetExtAttDef();
  2752. return $oExtAttDef->IsScalar();
  2753. }
  2754. public function GetFilterDefinitions()
  2755. {
  2756. return array($this->GetCode() => new FilterFromAttribute($this));
  2757. }
  2758. public function GetBasicFilterOperators()
  2759. {
  2760. $oExtAttDef = $this->GetExtAttDef();
  2761. return $oExtAttDef->GetBasicFilterOperators();
  2762. }
  2763. public function GetBasicFilterLooseOperator()
  2764. {
  2765. $oExtAttDef = $this->GetExtAttDef();
  2766. return $oExtAttDef->GetBasicFilterLooseOperator();
  2767. }
  2768. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2769. {
  2770. $oExtAttDef = $this->GetExtAttDef();
  2771. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  2772. }
  2773. public function GetNullValue()
  2774. {
  2775. $oExtAttDef = $this->GetExtAttDef();
  2776. return $oExtAttDef->GetNullValue();
  2777. }
  2778. public function IsNull($proposedValue)
  2779. {
  2780. $oExtAttDef = $this->GetExtAttDef();
  2781. return $oExtAttDef->IsNull($proposedValue);
  2782. }
  2783. public function MakeRealValue($proposedValue, $oHostObj)
  2784. {
  2785. $oExtAttDef = $this->GetExtAttDef();
  2786. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  2787. }
  2788. public function ScalarToSQL($value)
  2789. {
  2790. // This one could be used in case of filtering only
  2791. $oExtAttDef = $this->GetExtAttDef();
  2792. return $oExtAttDef->ScalarToSQL($value);
  2793. }
  2794. // Do not overload GetSQLExpression here because this is handled in the joins
  2795. //public function GetSQLExpressions($sPrefix = '') {return array();}
  2796. // Here, we get the data...
  2797. public function FromSQLToValue($aCols, $sPrefix = '')
  2798. {
  2799. $oExtAttDef = $this->GetExtAttDef();
  2800. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  2801. }
  2802. public function GetAsHTML($value, $oHostObject = null)
  2803. {
  2804. $oExtAttDef = $this->GetExtAttDef();
  2805. return $oExtAttDef->GetAsHTML($value);
  2806. }
  2807. public function GetAsXML($value, $oHostObject = null)
  2808. {
  2809. $oExtAttDef = $this->GetExtAttDef();
  2810. return $oExtAttDef->GetAsXML($value);
  2811. }
  2812. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null)
  2813. {
  2814. $oExtAttDef = $this->GetExtAttDef();
  2815. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  2816. }
  2817. }
  2818. /**
  2819. * Map a varchar column to an URL (formats the ouput in HMTL)
  2820. *
  2821. * @package iTopORM
  2822. */
  2823. class AttributeURL extends AttributeString
  2824. {
  2825. static public function ListExpectedParams()
  2826. {
  2827. //return parent::ListExpectedParams();
  2828. return array_merge(parent::ListExpectedParams(), array("target"));
  2829. }
  2830. public function GetEditClass() {return "String";}
  2831. public function GetAsHTML($sValue, $oHostObject = null)
  2832. {
  2833. $sTarget = $this->Get("target");
  2834. if (empty($sTarget)) $sTarget = "_blank";
  2835. $sLabel = Str::pure2html($sValue);
  2836. if (strlen($sLabel) > 40)
  2837. {
  2838. // Truncate the length to about 40 characters, by removing the middle
  2839. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  2840. }
  2841. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  2842. }
  2843. public function GetValidationPattern()
  2844. {
  2845. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  2846. }
  2847. }
  2848. /**
  2849. * A blob is an ormDocument, it is stored as several columns in the database
  2850. *
  2851. * @package iTopORM
  2852. */
  2853. class AttributeBlob extends AttributeDefinition
  2854. {
  2855. static public function ListExpectedParams()
  2856. {
  2857. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  2858. }
  2859. public function GetEditClass() {return "Document";}
  2860. public function IsDirectField() {return true;}
  2861. public function IsScalar() {return true;}
  2862. public function IsWritable() {return true;}
  2863. public function GetDefaultValue() {return "";}
  2864. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2865. // Facilitate things: allow the user to Set the value from a string
  2866. public function MakeRealValue($proposedValue, $oHostObj)
  2867. {
  2868. if (!is_object($proposedValue))
  2869. {
  2870. return new ormDocument($proposedValue, 'text/plain');
  2871. }
  2872. return $proposedValue;
  2873. }
  2874. public function GetSQLExpressions($sPrefix = '')
  2875. {
  2876. if ($sPrefix == '')
  2877. {
  2878. $sPrefix = $this->GetCode();
  2879. }
  2880. $aColumns = array();
  2881. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2882. $aColumns[''] = $sPrefix.'_mimetype';
  2883. $aColumns['_data'] = $sPrefix.'_data';
  2884. $aColumns['_filename'] = $sPrefix.'_filename';
  2885. return $aColumns;
  2886. }
  2887. public function FromSQLToValue($aCols, $sPrefix = '')
  2888. {
  2889. if (!isset($aCols[$sPrefix]))
  2890. {
  2891. $sAvailable = implode(', ', array_keys($aCols));
  2892. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2893. }
  2894. $sMimeType = $aCols[$sPrefix];
  2895. if (!isset($aCols[$sPrefix.'_data']))
  2896. {
  2897. $sAvailable = implode(', ', array_keys($aCols));
  2898. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  2899. }
  2900. $data = $aCols[$sPrefix.'_data'];
  2901. if (!isset($aCols[$sPrefix.'_filename']))
  2902. {
  2903. $sAvailable = implode(', ', array_keys($aCols));
  2904. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  2905. }
  2906. $sFileName = $aCols[$sPrefix.'_filename'];
  2907. $value = new ormDocument($data, $sMimeType, $sFileName);
  2908. return $value;
  2909. }
  2910. public function GetSQLValues($value)
  2911. {
  2912. // #@# Optimization: do not load blobs anytime
  2913. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2914. // using memory in case a temporary table has to be created
  2915. // (temporary tables created on disk)
  2916. // We will have to remove the blobs from the list of attributes when doing the select
  2917. // then the use of Get() should finalize the load
  2918. if ($value instanceOf ormDocument)
  2919. {
  2920. $aValues = array();
  2921. $aValues[$this->GetCode().'_data'] = $value->GetData();
  2922. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  2923. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  2924. }
  2925. else
  2926. {
  2927. $aValues = array();
  2928. $aValues[$this->GetCode().'_data'] = '';
  2929. $aValues[$this->GetCode().'_mimetype'] = '';
  2930. $aValues[$this->GetCode().'_filename'] = '';
  2931. }
  2932. return $aValues;
  2933. }
  2934. public function GetSQLColumns()
  2935. {
  2936. $aColumns = array();
  2937. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  2938. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  2939. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  2940. return $aColumns;
  2941. }
  2942. public function GetFilterDefinitions()
  2943. {
  2944. return array();
  2945. // still not working... see later...
  2946. return array(
  2947. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  2948. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  2949. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  2950. );
  2951. }
  2952. public function GetBasicFilterOperators()
  2953. {
  2954. return array();
  2955. }
  2956. public function GetBasicFilterLooseOperator()
  2957. {
  2958. return '=';
  2959. }
  2960. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2961. {
  2962. return 'true';
  2963. }
  2964. public function GetAsHTML($value, $oHostObject = null)
  2965. {
  2966. if (is_object($value))
  2967. {
  2968. return $value->GetAsHTML();
  2969. }
  2970. }
  2971. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2972. {
  2973. return ''; // Not exportable in CSV !
  2974. }
  2975. public function GetAsXML($value, $oHostObject = null)
  2976. {
  2977. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  2978. }
  2979. }
  2980. /**
  2981. * A stop watch is an ormStopWatch object, it is stored as several columns in the database
  2982. *
  2983. * @package iTopORM
  2984. */
  2985. class AttributeStopWatch extends AttributeDefinition
  2986. {
  2987. static public function ListExpectedParams()
  2988. {
  2989. // The list of thresholds must be an array of iPercent => array of 'option' => value
  2990. return array_merge(parent::ListExpectedParams(), array("states", "goal_computing", "working_time_computing", "thresholds"));
  2991. }
  2992. public function GetEditClass() {return "StopWatch";}
  2993. public function IsDirectField() {return true;}
  2994. public function IsScalar() {return true;}
  2995. public function IsWritable() {return false;}
  2996. public function GetDefaultValue() {return $this->NewStopWatch();}
  2997. public function GetEditValue($value, $oHostObj = null)
  2998. {
  2999. return $value->GetTimeSpent();
  3000. }
  3001. public function GetStates()
  3002. {
  3003. return $this->Get('states');
  3004. }
  3005. /**
  3006. * Construct a brand new (but configured) stop watch
  3007. */
  3008. public function NewStopWatch()
  3009. {
  3010. $oSW = new ormStopWatch();
  3011. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3012. {
  3013. $oSW->DefineThreshold($iThreshold);
  3014. }
  3015. return $oSW;
  3016. }
  3017. // Facilitate things: allow the user to Set the value from a string
  3018. public function MakeRealValue($proposedValue, $oHostObj)
  3019. {
  3020. if (!$proposedValue instanceof ormStopWatch)
  3021. {
  3022. return $this->NewStopWatch();
  3023. }
  3024. return $proposedValue;
  3025. }
  3026. public function GetSQLExpressions($sPrefix = '')
  3027. {
  3028. if ($sPrefix == '')
  3029. {
  3030. $sPrefix = $this->GetCode();
  3031. }
  3032. $aColumns = array();
  3033. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  3034. $aColumns[''] = $sPrefix.'_timespent';
  3035. $aColumns['_started'] = $sPrefix.'_started';
  3036. $aColumns['_laststart'] = $sPrefix.'_laststart';
  3037. $aColumns['_stopped'] = $sPrefix.'_stopped';
  3038. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3039. {
  3040. $sThPrefix = '_'.$iThreshold;
  3041. $aColumns[$sThPrefix.'_deadline'] = $sPrefix.$sThPrefix.'_deadline';
  3042. $aColumns[$sThPrefix.'_passed'] = $sPrefix.$sThPrefix.'_passed';
  3043. $aColumns[$sThPrefix.'_triggered'] = $sPrefix.$sThPrefix.'_triggered';
  3044. $aColumns[$sThPrefix.'_overrun'] = $sPrefix.$sThPrefix.'_overrun';
  3045. }
  3046. return $aColumns;
  3047. }
  3048. public static function DateToSeconds($sDate)
  3049. {
  3050. if (is_null($sDate))
  3051. {
  3052. return null;
  3053. }
  3054. $oDateTime = new DateTime($sDate);
  3055. $iSeconds = $oDateTime->format('U');
  3056. return $iSeconds;
  3057. }
  3058. public static function SecondsToDate($iSeconds)
  3059. {
  3060. if (is_null($iSeconds))
  3061. {
  3062. return null;
  3063. }
  3064. return date("Y-m-d H:i:s", $iSeconds);
  3065. }
  3066. public function FromSQLToValue($aCols, $sPrefix = '')
  3067. {
  3068. $aExpectedCols = array($sPrefix, $sPrefix.'_started', $sPrefix.'_laststart', $sPrefix.'_stopped');
  3069. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3070. {
  3071. $sThPrefix = '_'.$iThreshold;
  3072. $aExpectedCols[] = $sPrefix.$sThPrefix.'_deadline';
  3073. $aExpectedCols[] = $sPrefix.$sThPrefix.'_passed';
  3074. $aExpectedCols[] = $sPrefix.$sThPrefix.'_triggered';
  3075. $aExpectedCols[] = $sPrefix.$sThPrefix.'_overrun';
  3076. }
  3077. foreach ($aExpectedCols as $sExpectedCol)
  3078. {
  3079. if (!array_key_exists($sExpectedCol, $aCols))
  3080. {
  3081. $sAvailable = implode(', ', array_keys($aCols));
  3082. throw new MissingColumnException("Missing column '$sExpectedCol' from {$sAvailable}");
  3083. }
  3084. }
  3085. $value = new ormStopWatch(
  3086. $aCols[$sPrefix],
  3087. self::DateToSeconds($aCols[$sPrefix.'_started']),
  3088. self::DateToSeconds($aCols[$sPrefix.'_laststart']),
  3089. self::DateToSeconds($aCols[$sPrefix.'_stopped'])
  3090. );
  3091. $aThresholds = array();
  3092. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3093. {
  3094. $sThPrefix = '_'.$iThreshold;
  3095. $value->DefineThreshold(
  3096. $iThreshold,
  3097. self::DateToSeconds($aCols[$sPrefix.$sThPrefix.'_deadline']),
  3098. (bool)($aCols[$sPrefix.$sThPrefix.'_passed'] == 1),
  3099. (bool)($aCols[$sPrefix.$sThPrefix.'_triggered'] == 1),
  3100. $aCols[$sPrefix.$sThPrefix.'_overrun']
  3101. );
  3102. }
  3103. return $value;
  3104. }
  3105. public function GetSQLValues($value)
  3106. {
  3107. if ($value instanceOf ormStopWatch)
  3108. {
  3109. $aValues = array();
  3110. $aValues[$this->GetCode().'_timespent'] = $value->GetTimeSpent();
  3111. $aValues[$this->GetCode().'_started'] = self::SecondsToDate($value->GetStartDate());
  3112. $aValues[$this->GetCode().'_laststart'] = self::SecondsToDate($value->GetLastStartDate());
  3113. $aValues[$this->GetCode().'_stopped'] = self::SecondsToDate($value->GetStopDate());
  3114. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3115. {
  3116. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3117. $aValues[$sPrefix.'_deadline'] = self::SecondsToDate($value->GetThresholdDate($iThreshold));
  3118. $aValues[$sPrefix.'_passed'] = $value->IsThresholdPassed($iThreshold) ? '1' : '0';
  3119. $aValues[$sPrefix.'_triggered'] = $value->IsThresholdTriggered($iThreshold) ? '1' : '0';
  3120. $aValues[$sPrefix.'_overrun'] = $value->GetOverrun($iThreshold);
  3121. }
  3122. }
  3123. else
  3124. {
  3125. $aValues = array();
  3126. $aValues[$this->GetCode().'_timespent'] = '';
  3127. $aValues[$this->GetCode().'_started'] = '';
  3128. $aValues[$this->GetCode().'_laststart'] = '';
  3129. $aValues[$this->GetCode().'_stopped'] = '';
  3130. }
  3131. return $aValues;
  3132. }
  3133. public function GetSQLColumns()
  3134. {
  3135. $aColumns = array();
  3136. $aColumns[$this->GetCode().'_timespent'] = 'INT(11) UNSIGNED';
  3137. $aColumns[$this->GetCode().'_started'] = 'DATETIME';
  3138. $aColumns[$this->GetCode().'_laststart'] = 'DATETIME';
  3139. $aColumns[$this->GetCode().'_stopped'] = 'DATETIME';
  3140. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3141. {
  3142. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3143. $aColumns[$sPrefix.'_deadline'] = 'DATETIME';
  3144. $aColumns[$sPrefix.'_passed'] = 'TINYINT(1) UNSIGNED';
  3145. $aColumns[$sPrefix.'_triggered'] = 'TINYINT(1)';
  3146. $aColumns[$sPrefix.'_overrun'] = 'INT(11) UNSIGNED';
  3147. }
  3148. return $aColumns;
  3149. }
  3150. public function GetFilterDefinitions()
  3151. {
  3152. $aRes = array(
  3153. $this->GetCode() => new FilterFromAttribute($this),
  3154. $this->GetCode().'_started' => new FilterFromAttribute($this, '_started'),
  3155. $this->GetCode().'_laststart' => new FilterFromAttribute($this, '_laststart'),
  3156. $this->GetCode().'_stopped' => new FilterFromAttribute($this, '_stopped')
  3157. );
  3158. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3159. {
  3160. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3161. $aRes[$sPrefix.'_deadline'] = new FilterFromAttribute($this, '_deadline');
  3162. $aRes[$sPrefix.'_passed'] = new FilterFromAttribute($this, '_passed');
  3163. $aRes[$sPrefix.'_triggered'] = new FilterFromAttribute($this, '_triggered');
  3164. $aRes[$sPrefix.'_overrun'] = new FilterFromAttribute($this, '_overrun');
  3165. }
  3166. return $aRes;
  3167. }
  3168. public function GetBasicFilterOperators()
  3169. {
  3170. return array();
  3171. }
  3172. public function GetBasicFilterLooseOperator()
  3173. {
  3174. return '=';
  3175. }
  3176. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3177. {
  3178. return 'true';
  3179. }
  3180. public function GetAsHTML($value, $oHostObject = null)
  3181. {
  3182. if (is_object($value))
  3183. {
  3184. return $value->GetAsHTML($this, $oHostObject);
  3185. }
  3186. }
  3187. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  3188. {
  3189. return $value->GetTimeSpent();
  3190. }
  3191. public function GetAsXML($value, $oHostObject = null)
  3192. {
  3193. return $value->GetTimeSpent();
  3194. }
  3195. public function ListThresholds()
  3196. {
  3197. return $this->Get('thresholds');
  3198. }
  3199. /**
  3200. * To expose internal values: Declare an attribute AttributeSubItem
  3201. * and implement the GetSubItemXXXX verbs
  3202. */
  3203. public function GetSubItemSQLExpression($sItemCode)
  3204. {
  3205. $sPrefix = $this->GetCode();
  3206. switch($sItemCode)
  3207. {
  3208. case 'timespent':
  3209. return array('' => $sPrefix.'_timespent');
  3210. case 'started':
  3211. return array('' => $sPrefix.'_started');
  3212. case 'laststart':
  3213. return array('' => $sPrefix.'_laststart');
  3214. case 'stopped':
  3215. return array('' => $sPrefix.'_stopped');
  3216. }
  3217. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3218. {
  3219. $sThPrefix = $iThreshold.'_';
  3220. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3221. {
  3222. // The current threshold is concerned
  3223. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3224. switch($sThresholdCode)
  3225. {
  3226. case 'deadline':
  3227. return array('' => $sPrefix.'_'.$iThreshold.'_deadline');
  3228. case 'passed':
  3229. return array('' => $sPrefix.'_'.$iThreshold.'_passed');
  3230. case 'triggered':
  3231. return array('' => $sPrefix.'_'.$iThreshold.'_triggered');
  3232. case 'overrun':
  3233. return array('' => $sPrefix.'_'.$iThreshold.'_overrun');
  3234. }
  3235. }
  3236. }
  3237. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  3238. }
  3239. public function GetSubItemValue($sItemCode, $value, $oHostObject = null)
  3240. {
  3241. $oStopWatch = $value;
  3242. switch($sItemCode)
  3243. {
  3244. case 'timespent':
  3245. return $oStopWatch->GetTimeSpent();
  3246. case 'started':
  3247. return $oStopWatch->GetStartDate();
  3248. case 'laststart':
  3249. return $oStopWatch->GetLastStartDate();
  3250. case 'stopped':
  3251. return $oStopWatch->GetStopDate();
  3252. }
  3253. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3254. {
  3255. $sThPrefix = $iThreshold.'_';
  3256. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3257. {
  3258. // The current threshold is concerned
  3259. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3260. switch($sThresholdCode)
  3261. {
  3262. case 'deadline':
  3263. return $oStopWatch->GetThresholdDate($iThreshold);
  3264. case 'passed':
  3265. return $oStopWatch->IsThresholdPassed($iThreshold);
  3266. case 'triggered':
  3267. return $oStopWatch->IsThresholdTriggered($iThreshold);
  3268. case 'overrun':
  3269. return $oStopWatch->GetOverrun($iThreshold);
  3270. }
  3271. }
  3272. }
  3273. throw new CoreException("Unknown item code '$sItemCode' for attribute ".$this->GetHostClass().'::'.$this->GetCode());
  3274. }
  3275. public function GetSubItemAsHTMLForHistory($sItemCode, $sOldValue, $sNewValue, $sLabel)
  3276. {
  3277. switch($sItemCode)
  3278. {
  3279. case 'timespent':
  3280. $sHtmlOld = (int)$sOldValue ? AttributeDuration::FormatDuration($sOldValue) : null;
  3281. $sHtmlNew = (int)$sNewValue ? AttributeDuration::FormatDuration($sNewValue) : null;
  3282. break;
  3283. case 'started':
  3284. case 'laststart':
  3285. case 'stopped':
  3286. $sHtmlOld = (int)$sOldValue ? date(self::GetDateFormat(), (int)$sOldValue) : null;
  3287. $sHtmlNew = (int)$sNewValue ? date(self::GetDateFormat(), (int)$sNewValue) : null;
  3288. break;
  3289. default:
  3290. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3291. {
  3292. $sThPrefix = $iThreshold.'_';
  3293. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3294. {
  3295. // The current threshold is concerned
  3296. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3297. switch($sThresholdCode)
  3298. {
  3299. case 'deadline':
  3300. $sHtmlOld = (int)$sOldValue ? date(self::GetDateFormat(true /*full*/), (int)$sOldValue) : null;
  3301. $sHtmlNew = (int)$sNewValue ? date(self::GetDateFormat(true /*full*/), (int)$sNewValue) : null;
  3302. break;
  3303. case 'passed':
  3304. $sHtmlOld = (int)$sOldValue ? '1' : '0';
  3305. $sHtmlNew = (int)$sNewValue ? '1' : '0';
  3306. break;
  3307. case 'triggered':
  3308. $sHtmlOld = (int)$sOldValue ? '1' : '0';
  3309. $sHtmlNew = (int)$sNewValue ? '1' : '0';
  3310. break;
  3311. case 'overrun':
  3312. $sHtmlOld = (int)$sOldValue > 0 ? AttributeDuration::FormatDuration((int)$sOldValue) : '';
  3313. $sHtmlNew = (int)$sNewValue > 0 ? AttributeDuration::FormatDuration((int)$sNewValue) : '';
  3314. }
  3315. }
  3316. }
  3317. }
  3318. $sRes = parent::GetAsHTMLForHistory($sHtmlOld, $sHtmlNew, $sLabel);
  3319. return $sRes;
  3320. }
  3321. static protected function GetDateFormat($bFull = false)
  3322. {
  3323. if ($bFull)
  3324. {
  3325. return "Y-m-d H:i:s";
  3326. }
  3327. else
  3328. {
  3329. return "Y-m-d H:i";
  3330. }
  3331. }
  3332. public function GetSubItemAsHTML($sItemCode, $value)
  3333. {
  3334. $sHtml = $value;
  3335. switch($sItemCode)
  3336. {
  3337. case 'timespent':
  3338. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  3339. break;
  3340. case 'started':
  3341. case 'laststart':
  3342. case 'stopped':
  3343. if (is_null($value))
  3344. {
  3345. $sHtml = ''; // Undefined
  3346. }
  3347. else
  3348. {
  3349. $sHtml = date(self::GetDateFormat(), $value);
  3350. }
  3351. break;
  3352. default:
  3353. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3354. {
  3355. $sThPrefix = $iThreshold.'_';
  3356. if (substr($sItemCode, 0, strlen($sThPrefix)) == $sThPrefix)
  3357. {
  3358. // The current threshold is concerned
  3359. $sThresholdCode = substr($sItemCode, strlen($sThPrefix));
  3360. switch($sThresholdCode)
  3361. {
  3362. case 'deadline':
  3363. if ($value)
  3364. {
  3365. $sDate = date(self::GetDateFormat(true /*full*/), $value);
  3366. $sHtml = Str::pure2html(AttributeDeadline::FormatDeadline($sDate));
  3367. }
  3368. else
  3369. {
  3370. $sHtml = '';
  3371. }
  3372. break;
  3373. case 'passed':
  3374. $sHtml = $value ? '1' : '0';
  3375. break;
  3376. case 'triggered':
  3377. $sHtml = $value ? '1' : '0';
  3378. break;
  3379. case 'overrun':
  3380. $sHtml = Str::pure2html(AttributeDuration::FormatDuration($value));
  3381. break;
  3382. }
  3383. }
  3384. }
  3385. }
  3386. return $sHtml;
  3387. }
  3388. public function GetSubItemAsCSV($sItemCode, $value, $sSeparator = ',', $sTextQualifier = '"')
  3389. {
  3390. return $value;
  3391. }
  3392. public function GetSubItemAsXML($sItemCode, $value)
  3393. {
  3394. return Str::pure2xml((string)$value);
  3395. }
  3396. }
  3397. /**
  3398. * View of a subvalue of another attribute
  3399. * If an attribute implements the verbs GetSubItem.... then it can expose
  3400. * internal values, each of them being an attribute and therefore they
  3401. * can be displayed at different times in the object lifecycle, and used for
  3402. * reporting (as a condition in OQL, or as an additional column in an export)
  3403. * Known usages: Stop Watches can expose threshold statuses
  3404. */
  3405. class AttributeSubItem extends AttributeDefinition
  3406. {
  3407. static public function ListExpectedParams()
  3408. {
  3409. return array_merge(parent::ListExpectedParams(), array('target_attcode', 'item_code'));
  3410. }
  3411. public function GetParentAttCode() {return $this->Get("target_attcode");}
  3412. /**
  3413. * Helper : get the attribute definition to which the execution will be forwarded
  3414. */
  3415. protected function GetTargetAttDef()
  3416. {
  3417. $sClass = $this->GetHostClass();
  3418. $oParentAttDef = MetaModel::GetAttributeDef($sClass, $this->Get('target_attcode'));
  3419. return $oParentAttDef;
  3420. }
  3421. public function GetEditClass() {return "";}
  3422. public function GetValuesDef() {return null;}
  3423. //public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  3424. public function IsDirectField() {return true;}
  3425. public function IsScalar() {return true;}
  3426. public function IsWritable() {return false;}
  3427. public function GetDefaultValue() {return null;}
  3428. // public function IsNullAllowed() {return false;}
  3429. public function LoadInObject() {return false;} // if this verb returns true, then GetValue must be implemented
  3430. //
  3431. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  3432. public function FromSQLToValue($aCols, $sPrefix = '')
  3433. {
  3434. }
  3435. public function GetSQLColumns()
  3436. {
  3437. return array();
  3438. }
  3439. public function GetFilterDefinitions()
  3440. {
  3441. return array($this->GetCode() => new FilterFromAttribute($this));
  3442. }
  3443. public function GetBasicFilterOperators()
  3444. {
  3445. return array();
  3446. }
  3447. public function GetBasicFilterLooseOperator()
  3448. {
  3449. return "=";
  3450. }
  3451. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3452. {
  3453. $sQValue = CMDBSource::Quote($value);
  3454. switch ($sOpCode)
  3455. {
  3456. case '!=':
  3457. return $this->GetSQLExpr()." != $sQValue";
  3458. break;
  3459. case '=':
  3460. default:
  3461. return $this->GetSQLExpr()." = $sQValue";
  3462. }
  3463. }
  3464. public function GetSQLExpressions($sPrefix = '')
  3465. {
  3466. $oParent = $this->GetTargetAttDef();
  3467. $res = $oParent->GetSubItemSQLExpression($this->Get('item_code'));
  3468. return $res;
  3469. }
  3470. /**
  3471. * Used by DBOBject::Get()
  3472. */
  3473. public function GetValue($parentValue, $oHostObject = null)
  3474. {
  3475. $oParent = $this->GetTargetAttDef();
  3476. $res = $oParent->GetSubItemValue($this->Get('item_code'), $parentValue, $oHostObject);
  3477. return $res;
  3478. }
  3479. public function GetAsHTML($value, $oHostObject = null)
  3480. {
  3481. $oParent = $this->GetTargetAttDef();
  3482. $res = $oParent->GetSubItemAsHTML($this->Get('item_code'), $value);
  3483. return $res;
  3484. }
  3485. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  3486. {
  3487. $oParent = $this->GetTargetAttDef();
  3488. $res = $oParent->GetSubItemAsCSV($this->Get('item_code'), $value, $sSeparator = ',', $sTextQualifier = '"');
  3489. return $res;
  3490. }
  3491. public function GetAsXML($value, $oHostObject = null)
  3492. {
  3493. $oParent = $this->GetTargetAttDef();
  3494. $res = $oParent->GetSubItemAsXML($this->Get('item_code'), $value);
  3495. return $res;
  3496. }
  3497. public function GetAsHTMLForHistory($sOldValue, $sNewValue, $sLabel = null)
  3498. {
  3499. $sLabel = $this->GetLabel();
  3500. $oParent = $this->GetTargetAttDef();
  3501. $sValue = $oParent->GetSubItemAsHTMLForHistory($this->Get('item_code'), $sOldValue, $sNewValue, $sLabel);
  3502. return $sValue;
  3503. }
  3504. }
  3505. /**
  3506. * One way encrypted (hashed) password
  3507. */
  3508. class AttributeOneWayPassword extends AttributeDefinition
  3509. {
  3510. static public function ListExpectedParams()
  3511. {
  3512. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  3513. }
  3514. public function GetEditClass() {return "One Way Password";}
  3515. public function IsDirectField() {return true;}
  3516. public function IsScalar() {return true;}
  3517. public function IsWritable() {return true;}
  3518. public function GetDefaultValue() {return "";}
  3519. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  3520. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  3521. public function MakeRealValue($proposedValue, $oHostObj)
  3522. {
  3523. $oPassword = $proposedValue;
  3524. if (!is_object($oPassword))
  3525. {
  3526. $oPassword = new ormPassword('', '');
  3527. $oPassword->SetPassword($proposedValue);
  3528. }
  3529. return $oPassword;
  3530. }
  3531. public function GetSQLExpressions($sPrefix = '')
  3532. {
  3533. if ($sPrefix == '')
  3534. {
  3535. $sPrefix = $this->GetCode();
  3536. }
  3537. $aColumns = array();
  3538. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  3539. $aColumns[''] = $sPrefix.'_hash';
  3540. $aColumns['_salt'] = $sPrefix.'_salt';
  3541. return $aColumns;
  3542. }
  3543. public function FromSQLToValue($aCols, $sPrefix = '')
  3544. {
  3545. if (!isset($aCols[$sPrefix]))
  3546. {
  3547. $sAvailable = implode(', ', array_keys($aCols));
  3548. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  3549. }
  3550. $hashed = $aCols[$sPrefix];
  3551. if (!isset($aCols[$sPrefix.'_salt']))
  3552. {
  3553. $sAvailable = implode(', ', array_keys($aCols));
  3554. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  3555. }
  3556. $sSalt = $aCols[$sPrefix.'_salt'];
  3557. $value = new ormPassword($hashed, $sSalt);
  3558. return $value;
  3559. }
  3560. public function GetSQLValues($value)
  3561. {
  3562. // #@# Optimization: do not load blobs anytime
  3563. // As per mySQL doc, selecting blob columns will prevent mySQL from
  3564. // using memory in case a temporary table has to be created
  3565. // (temporary tables created on disk)
  3566. // We will have to remove the blobs from the list of attributes when doing the select
  3567. // then the use of Get() should finalize the load
  3568. if ($value instanceOf ormPassword)
  3569. {
  3570. $aValues = array();
  3571. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  3572. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  3573. }
  3574. else
  3575. {
  3576. $aValues = array();
  3577. $aValues[$this->GetCode().'_hash'] = '';
  3578. $aValues[$this->GetCode().'_salt'] = '';
  3579. }
  3580. return $aValues;
  3581. }
  3582. public function GetSQLColumns()
  3583. {
  3584. $aColumns = array();
  3585. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  3586. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  3587. return $aColumns;
  3588. }
  3589. public function GetImportColumns()
  3590. {
  3591. $aColumns = array();
  3592. $aColumns[$this->GetCode()] = 'TINYTEXT';
  3593. return $aColumns;
  3594. }
  3595. public function FromImportToValue($aCols, $sPrefix = '')
  3596. {
  3597. if (!isset($aCols[$sPrefix]))
  3598. {
  3599. $sAvailable = implode(', ', array_keys($aCols));
  3600. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  3601. }
  3602. $sClearPwd = $aCols[$sPrefix];
  3603. $oPassword = new ormPassword('', '');
  3604. $oPassword->SetPassword($sClearPwd);
  3605. return $oPassword;
  3606. }
  3607. public function GetFilterDefinitions()
  3608. {
  3609. return array();
  3610. // still not working... see later...
  3611. }
  3612. public function GetBasicFilterOperators()
  3613. {
  3614. return array();
  3615. }
  3616. public function GetBasicFilterLooseOperator()
  3617. {
  3618. return '=';
  3619. }
  3620. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3621. {
  3622. return 'true';
  3623. }
  3624. public function GetAsHTML($value, $oHostObject = null)
  3625. {
  3626. if (is_object($value))
  3627. {
  3628. return $value->GetAsHTML();
  3629. }
  3630. }
  3631. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  3632. {
  3633. return ''; // Not exportable in CSV
  3634. }
  3635. public function GetAsXML($value, $oHostObject = null)
  3636. {
  3637. return ''; // Not exportable in XML
  3638. }
  3639. }
  3640. // Indexed array having two dimensions
  3641. class AttributeTable extends AttributeDBField
  3642. {
  3643. public function GetEditClass() {return "Table";}
  3644. protected function GetSQLCol() {return "LONGTEXT";}
  3645. public function GetMaxSize()
  3646. {
  3647. return null;
  3648. }
  3649. public function GetNullValue()
  3650. {
  3651. return array();
  3652. }
  3653. public function IsNull($proposedValue)
  3654. {
  3655. return (count($proposedValue) == 0);
  3656. }
  3657. // Facilitate things: allow the user to Set the value from a string
  3658. public function MakeRealValue($proposedValue, $oHostObj)
  3659. {
  3660. if (!is_array($proposedValue))
  3661. {
  3662. return array(0 => array(0 => $proposedValue));
  3663. }
  3664. return $proposedValue;
  3665. }
  3666. public function FromSQLToValue($aCols, $sPrefix = '')
  3667. {
  3668. try
  3669. {
  3670. $value = @unserialize($aCols[$sPrefix.'']);
  3671. if ($value === false)
  3672. {
  3673. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  3674. }
  3675. }
  3676. catch(Exception $e)
  3677. {
  3678. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  3679. }
  3680. return $value;
  3681. }
  3682. public function GetSQLValues($value)
  3683. {
  3684. $aValues = array();
  3685. $aValues[$this->Get("sql")] = serialize($value);
  3686. return $aValues;
  3687. }
  3688. public function GetAsHTML($value, $oHostObject = null)
  3689. {
  3690. if (!is_array($value))
  3691. {
  3692. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  3693. }
  3694. if (count($value) == 0)
  3695. {
  3696. return "";
  3697. }
  3698. $sRes = "<TABLE class=\"listResults\">";
  3699. $sRes .= "<TBODY>";
  3700. foreach($value as $iRow => $aRawData)
  3701. {
  3702. $sRes .= "<TR>";
  3703. foreach ($aRawData as $iCol => $cell)
  3704. {
  3705. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  3706. $sRes .= "<TD>$sCell</TD>";
  3707. }
  3708. $sRes .= "</TR>";
  3709. }
  3710. $sRes .= "</TBODY>";
  3711. $sRes .= "</TABLE>";
  3712. return $sRes;
  3713. }
  3714. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  3715. {
  3716. // Not implemented
  3717. return '';
  3718. }
  3719. public function GetAsXML($value, $oHostObject = null)
  3720. {
  3721. if (count($value) == 0)
  3722. {
  3723. return "";
  3724. }
  3725. $sRes = "";
  3726. foreach($value as $iRow => $aRawData)
  3727. {
  3728. $sRes .= "<row>";
  3729. foreach ($aRawData as $iCol => $cell)
  3730. {
  3731. $sCell = Str::pure2xml((string)$cell);
  3732. $sRes .= "<cell icol=\"$iCol\">$sCell</cell>";
  3733. }
  3734. $sRes .= "</row>";
  3735. }
  3736. return $sRes;
  3737. }
  3738. }
  3739. // The PHP value is a hash array, it is stored as a TEXT column
  3740. class AttributePropertySet extends AttributeTable
  3741. {
  3742. public function GetEditClass() {return "PropertySet";}
  3743. // Facilitate things: allow the user to Set the value from a string
  3744. public function MakeRealValue($proposedValue, $oHostObj)
  3745. {
  3746. if (!is_array($proposedValue))
  3747. {
  3748. return array('?' => (string)$proposedValue);
  3749. }
  3750. return $proposedValue;
  3751. }
  3752. public function GetAsHTML($value, $oHostObject = null)
  3753. {
  3754. if (!is_array($value))
  3755. {
  3756. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  3757. }
  3758. if (count($value) == 0)
  3759. {
  3760. return "";
  3761. }
  3762. $sRes = "<TABLE class=\"listResults\">";
  3763. $sRes .= "<TBODY>";
  3764. foreach($value as $sProperty => $sValue)
  3765. {
  3766. if ($sProperty == 'auth_pwd')
  3767. {
  3768. $sValue = '*****';
  3769. }
  3770. $sRes .= "<TR>";
  3771. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  3772. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  3773. $sRes .= "</TR>";
  3774. }
  3775. $sRes .= "</TBODY>";
  3776. $sRes .= "</TABLE>";
  3777. return $sRes;
  3778. }
  3779. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  3780. {
  3781. if (count($value) == 0)
  3782. {
  3783. return "";
  3784. }
  3785. $aRes = array();
  3786. foreach($value as $sProperty => $sValue)
  3787. {
  3788. if ($sProperty == 'auth_pwd')
  3789. {
  3790. $sValue = '*****';
  3791. }
  3792. $sFrom = array(',', '=');
  3793. $sTo = array('\,', '\=');
  3794. $aRes[] = $sProperty.'='.str_replace($sFrom, $sTo, (string)$sValue);
  3795. }
  3796. $sRaw = implode(',', $aRes);
  3797. $sFrom = array("\r\n", $sTextQualifier);
  3798. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  3799. $sEscaped = str_replace($sFrom, $sTo, $sRaw);
  3800. return $sTextQualifier.$sEscaped.$sTextQualifier;
  3801. }
  3802. public function GetAsXML($value, $oHostObject = null)
  3803. {
  3804. if (count($value) == 0)
  3805. {
  3806. return "";
  3807. }
  3808. $sRes = "";
  3809. foreach($value as $sProperty => $sValue)
  3810. {
  3811. if ($sProperty == 'auth_pwd')
  3812. {
  3813. $sValue = '*****';
  3814. }
  3815. $sRes .= "<property id=\"$sProperty\">";
  3816. $sRes .= Str::pure2xml((string)$sValue);
  3817. $sRes .= "</property>";
  3818. }
  3819. return $sRes;
  3820. }
  3821. }
  3822. /**
  3823. * The attribute dedicated to the friendly name automatic attribute (not written)
  3824. *
  3825. * @package iTopORM
  3826. */
  3827. class AttributeComputedFieldVoid extends AttributeDefinition
  3828. {
  3829. static public function ListExpectedParams()
  3830. {
  3831. return array_merge(parent::ListExpectedParams(), array());
  3832. }
  3833. public function GetEditClass() {return "";}
  3834. public function GetValuesDef() {return null;}
  3835. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  3836. public function IsDirectField() {return true;}
  3837. public function IsScalar() {return true;}
  3838. public function IsWritable() {return false;}
  3839. public function GetSQLExpr() {return null;}
  3840. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  3841. public function IsNullAllowed() {return false;}
  3842. //
  3843. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  3844. public function GetSQLExpressions($sPrefix = '')
  3845. {
  3846. if ($sPrefix == '')
  3847. {
  3848. $sPrefix = $this->GetCode();
  3849. }
  3850. return array('' => $sPrefix);
  3851. }
  3852. public function FromSQLToValue($aCols, $sPrefix = '')
  3853. {
  3854. return null;
  3855. }
  3856. public function GetSQLValues($value)
  3857. {
  3858. return array();
  3859. }
  3860. public function GetSQLColumns()
  3861. {
  3862. return array();
  3863. }
  3864. public function GetFilterDefinitions()
  3865. {
  3866. return array($this->GetCode() => new FilterFromAttribute($this));
  3867. }
  3868. public function GetBasicFilterOperators()
  3869. {
  3870. return array();
  3871. }
  3872. public function GetBasicFilterLooseOperator()
  3873. {
  3874. return "=";
  3875. }
  3876. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3877. {
  3878. $sQValue = CMDBSource::Quote($value);
  3879. switch ($sOpCode)
  3880. {
  3881. case '!=':
  3882. return $this->GetSQLExpr()." != $sQValue";
  3883. break;
  3884. case '=':
  3885. default:
  3886. return $this->GetSQLExpr()." = $sQValue";
  3887. }
  3888. }
  3889. }
  3890. /**
  3891. * The attribute dedicated to the friendly name automatic attribute (not written)
  3892. *
  3893. * @package iTopORM
  3894. */
  3895. class AttributeFriendlyName extends AttributeComputedFieldVoid
  3896. {
  3897. public function __construct($sCode, $sExtKeyAttCode)
  3898. {
  3899. $this->m_sCode = $sCode;
  3900. $aParams = array();
  3901. // $aParams["is_null_allowed"] = false,
  3902. $aParams["default_value"] = '';
  3903. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  3904. parent::__construct($sCode, $aParams);
  3905. $this->m_sValue = $this->Get("default_value");
  3906. }
  3907. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  3908. public function GetExtAttCode() {return 'friendlyname';}
  3909. public function GetLabel($sDefault = null)
  3910. {
  3911. $sLabel = parent::GetLabel('');
  3912. if (strlen($sLabel) == 0)
  3913. {
  3914. $sKeyAttCode = $this->Get("extkey_attcode");
  3915. if ($sKeyAttCode == 'id')
  3916. {
  3917. return Dict::S('Core:FriendlyName-Label');
  3918. }
  3919. else
  3920. {
  3921. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  3922. $sLabel = $oExtKeyAttDef->GetLabel($this->m_sCode);
  3923. }
  3924. }
  3925. return $sLabel;
  3926. }
  3927. public function GetDescription($sDefault = null)
  3928. {
  3929. $sLabel = parent::GetDescription('');
  3930. if (strlen($sLabel) == 0)
  3931. {
  3932. $sKeyAttCode = $this->Get("extkey_attcode");
  3933. if ($sKeyAttCode == 'id')
  3934. {
  3935. return Dict::S('Core:FriendlyName-Description');
  3936. }
  3937. else
  3938. {
  3939. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  3940. $sLabel = $oExtKeyAttDef->GetDescription('');
  3941. }
  3942. }
  3943. return $sLabel;
  3944. }
  3945. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  3946. protected function GetSQLCol() {return "";}
  3947. public function FromSQLToValue($aCols, $sPrefix = '')
  3948. {
  3949. $sValue = $aCols[$sPrefix];
  3950. return $sValue;
  3951. }
  3952. /**
  3953. * Encrypt the value before storing it in the database
  3954. */
  3955. public function GetSQLValues($value)
  3956. {
  3957. return array();
  3958. }
  3959. public function IsWritable()
  3960. {
  3961. return false;
  3962. }
  3963. public function IsDirectField()
  3964. {
  3965. return false;
  3966. }
  3967. public function SetFixedValue($sValue)
  3968. {
  3969. $this->m_sValue = $sValue;
  3970. }
  3971. public function GetDefaultValue()
  3972. {
  3973. return $this->m_sValue;
  3974. }
  3975. public function GetAsHTML($sValue, $oHostObject = null)
  3976. {
  3977. return Str::pure2html((string)$sValue);
  3978. }
  3979. // Do not display friendly names in the history of change
  3980. public function GetAsHTMLForHistory($sOldValue, $sNewValue, $sLabel = null)
  3981. {
  3982. return '';
  3983. }
  3984. public function GetBasicFilterLooseOperator()
  3985. {
  3986. return "Contains";
  3987. }
  3988. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3989. {
  3990. $sQValue = CMDBSource::Quote($value);
  3991. switch ($sOpCode)
  3992. {
  3993. case '=':
  3994. case '!=':
  3995. return $this->GetSQLExpr()." $sOpCode $sQValue";
  3996. case 'Contains':
  3997. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  3998. case 'NotLike':
  3999. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  4000. case 'Like':
  4001. default:
  4002. return $this->GetSQLExpr()." LIKE $sQValue";
  4003. }
  4004. }
  4005. }
  4006. ?>