attributedef.class.inc.php 128 KB

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