attributedef.class.inc.php 128 KB

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