attributedef.class.inc.php 131 KB

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