attributedef.class.inc.php 132 KB

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