attributedef.class.inc.php 126 KB

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