MySQLManager.cs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Data;
  31. using System.IO;
  32. using System.Reflection;
  33. using log4net;
  34. using MySql.Data.MySqlClient;
  35. using OpenMetaverse;
  36. using OpenSim.Framework;
  37. namespace OpenSim.Data.MySQL
  38. {
  39. /// <summary>
  40. /// A MySQL Database manager
  41. /// </summary>
  42. public class MySQLManager
  43. {
  44. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  45. /// <summary>
  46. /// The database connection object
  47. /// </summary>
  48. private MySqlConnection dbcon;
  49. /// <summary>
  50. /// Connection string for ADO.net
  51. /// </summary>
  52. private string connectionString;
  53. private const string m_waitTimeoutSelect = "select @@wait_timeout";
  54. /// <summary>
  55. /// Wait timeout for our connection in ticks.
  56. /// </summary>
  57. private long m_waitTimeout;
  58. /// <summary>
  59. /// Make our storage of the timeout this amount smaller than it actually is, to give us a margin on long
  60. /// running database operations.
  61. /// </summary>
  62. private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond;
  63. /// <summary>
  64. /// Holds the last tick time that the connection was used.
  65. /// </summary>
  66. private long m_lastConnectionUse;
  67. /// <summary>
  68. /// Initialises and creates a new MySQL connection and maintains it.
  69. /// </summary>
  70. /// <param name="hostname">The MySQL server being connected to</param>
  71. /// <param name="database">The name of the MySQL database being used</param>
  72. /// <param name="username">The username logging into the database</param>
  73. /// <param name="password">The password for the user logging in</param>
  74. /// <param name="cpooling">Whether to use connection pooling or not, can be one of the following: 'yes', 'true', 'no' or 'false', if unsure use 'false'.</param>
  75. /// <param name="port">The MySQL server port</param>
  76. public MySQLManager(string hostname, string database, string username, string password, string cpooling,
  77. string port)
  78. {
  79. string s = "Server=" + hostname + ";Port=" + port + ";Database=" + database + ";User ID=" +
  80. username + ";Password=" + password + ";Pooling=" + cpooling + ";";
  81. Initialise(s);
  82. }
  83. /// <summary>
  84. /// Initialises and creates a new MySQL connection and maintains it.
  85. /// </summary>
  86. /// <param name="connect">connectionString</param>
  87. public MySQLManager(String connect)
  88. {
  89. Initialise(connect);
  90. }
  91. /// <summary>
  92. /// Initialises and creates a new MySQL connection and maintains it.
  93. /// </summary>
  94. /// <param name="connect">connectionString</param>
  95. public void Initialise(String connect)
  96. {
  97. try
  98. {
  99. connectionString = connect;
  100. dbcon = new MySqlConnection(connectionString);
  101. try
  102. {
  103. dbcon.Open();
  104. }
  105. catch(Exception e)
  106. {
  107. throw new Exception("Connection error while using connection string ["+connectionString+"]", e);
  108. }
  109. m_log.Info("[MYSQL]: Connection established");
  110. GetWaitTimeout();
  111. }
  112. catch (Exception e)
  113. {
  114. throw new Exception("Error initialising MySql Database: " + e.ToString());
  115. }
  116. }
  117. /// <summary>
  118. /// Get the wait_timeout value for our connection
  119. /// </summary>
  120. protected void GetWaitTimeout()
  121. {
  122. MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon);
  123. using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
  124. {
  125. if (dbReader.Read())
  126. {
  127. m_waitTimeout
  128. = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
  129. }
  130. dbReader.Close();
  131. cmd.Dispose();
  132. }
  133. m_lastConnectionUse = DateTime.Now.Ticks;
  134. m_log.DebugFormat(
  135. "[REGION DB]: Connection wait timeout {0} seconds", m_waitTimeout / TimeSpan.TicksPerSecond);
  136. }
  137. /// <summary>
  138. /// Should be called before any db operation. This checks to see if the connection has not timed out
  139. /// </summary>
  140. public void CheckConnection()
  141. {
  142. //m_log.Debug("[REGION DB]: Checking connection");
  143. long timeNow = DateTime.Now.Ticks;
  144. if (timeNow - m_lastConnectionUse > m_waitTimeout || dbcon.State != ConnectionState.Open)
  145. {
  146. m_log.DebugFormat("[REGION DB]: Database connection has gone away - reconnecting");
  147. Reconnect();
  148. }
  149. // Strictly, we should set this after the actual db operation. But it's more convenient to set here rather
  150. // than require the code to call another method - the timeout leeway should be large enough to cover the
  151. // inaccuracy.
  152. m_lastConnectionUse = timeNow;
  153. }
  154. /// <summary>
  155. /// Get the connection being used
  156. /// </summary>
  157. /// <returns>MySqlConnection Object</returns>
  158. public MySqlConnection Connection
  159. {
  160. get { return dbcon; }
  161. }
  162. /// <summary>
  163. /// Shuts down the database connection
  164. /// </summary>
  165. public void Close()
  166. {
  167. dbcon.Close();
  168. dbcon = null;
  169. }
  170. /// <summary>
  171. /// Reconnects to the database
  172. /// </summary>
  173. public void Reconnect()
  174. {
  175. m_log.Info("[REGION DB] Reconnecting database");
  176. lock (dbcon)
  177. {
  178. try
  179. {
  180. // Close the DB connection
  181. dbcon.Close();
  182. // Try reopen it
  183. dbcon = new MySqlConnection(connectionString);
  184. dbcon.Open();
  185. }
  186. catch (Exception e)
  187. {
  188. m_log.Error("Unable to reconnect to database " + e.ToString());
  189. }
  190. }
  191. }
  192. /// <summary>
  193. /// Returns the version of this DB provider
  194. /// </summary>
  195. /// <returns>A string containing the DB provider</returns>
  196. public string getVersion()
  197. {
  198. Module module = GetType().Module;
  199. // string dllName = module.Assembly.ManifestModule.Name;
  200. Version dllVersion = module.Assembly.GetName().Version;
  201. return
  202. string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
  203. dllVersion.Revision);
  204. }
  205. /// <summary>
  206. /// Extract a named string resource from the embedded resources
  207. /// </summary>
  208. /// <param name="name">name of embedded resource</param>
  209. /// <returns>string contained within the embedded resource</returns>
  210. private string getResourceString(string name)
  211. {
  212. Assembly assem = GetType().Assembly;
  213. string[] names = assem.GetManifestResourceNames();
  214. foreach (string s in names)
  215. {
  216. if (s.EndsWith(name))
  217. {
  218. using (Stream resource = assem.GetManifestResourceStream(s))
  219. {
  220. using (StreamReader resourceReader = new StreamReader(resource))
  221. {
  222. string resourceString = resourceReader.ReadToEnd();
  223. return resourceString;
  224. }
  225. }
  226. }
  227. }
  228. throw new Exception(string.Format("Resource '{0}' was not found", name));
  229. }
  230. /// <summary>
  231. /// Execute a SQL statement stored in a resource, as a string
  232. /// </summary>
  233. /// <param name="name">name of embedded resource</param>
  234. public void ExecuteResourceSql(string name)
  235. {
  236. CheckConnection();
  237. MySqlCommand cmd = new MySqlCommand(getResourceString(name), dbcon);
  238. cmd.ExecuteNonQuery();
  239. }
  240. /// <summary>
  241. /// Execute a MySqlCommand
  242. /// </summary>
  243. /// <param name="sql">sql string to execute</param>
  244. public void ExecuteSql(string sql)
  245. {
  246. CheckConnection();
  247. MySqlCommand cmd = new MySqlCommand(sql, dbcon);
  248. cmd.ExecuteNonQuery();
  249. }
  250. public void ExecuteParameterizedSql(string sql, Dictionary<string, string> parameters)
  251. {
  252. CheckConnection();
  253. MySqlCommand cmd = (MySqlCommand)dbcon.CreateCommand();
  254. cmd.CommandText = sql;
  255. foreach (KeyValuePair<string, string> param in parameters)
  256. {
  257. cmd.Parameters.AddWithValue(param.Key, param.Value);
  258. }
  259. cmd.ExecuteNonQuery();
  260. }
  261. /// <summary>
  262. /// Given a list of tables, return the version of the tables, as seen in the database
  263. /// </summary>
  264. /// <param name="tableList"></param>
  265. public void GetTableVersion(Dictionary<string, string> tableList)
  266. {
  267. lock (dbcon)
  268. {
  269. CheckConnection();
  270. MySqlCommand tablesCmd =
  271. new MySqlCommand(
  272. "SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname",
  273. dbcon);
  274. tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);
  275. using (MySqlDataReader tables = tablesCmd.ExecuteReader())
  276. {
  277. while (tables.Read())
  278. {
  279. try
  280. {
  281. string tableName = (string) tables["TABLE_NAME"];
  282. string comment = (string) tables["TABLE_COMMENT"];
  283. if (tableList.ContainsKey(tableName))
  284. {
  285. tableList[tableName] = comment;
  286. }
  287. }
  288. catch (Exception e)
  289. {
  290. m_log.Error(e.ToString());
  291. }
  292. }
  293. tables.Close();
  294. }
  295. }
  296. }
  297. // TODO: at some time this code should be cleaned up
  298. /// <summary>
  299. /// Runs a query with protection against SQL Injection by using parameterised input.
  300. /// </summary>
  301. /// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
  302. /// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param>
  303. /// <returns>A MySQL DB Command</returns>
  304. public IDbCommand Query(string sql, Dictionary<string, object> parameters)
  305. {
  306. try
  307. {
  308. CheckConnection(); // Not sure if this one is necessary
  309. MySqlCommand dbcommand = (MySqlCommand) dbcon.CreateCommand();
  310. dbcommand.CommandText = sql;
  311. foreach (KeyValuePair<string, object> param in parameters)
  312. {
  313. dbcommand.Parameters.AddWithValue(param.Key, param.Value);
  314. }
  315. return (IDbCommand) dbcommand;
  316. }
  317. catch (Exception e)
  318. {
  319. // Return null if it fails.
  320. m_log.Error("Failed during Query generation: " + e.ToString());
  321. return null;
  322. }
  323. }
  324. /// <summary>
  325. /// Reads a region row from a database reader
  326. /// </summary>
  327. /// <param name="reader">An active database reader</param>
  328. /// <returns>A region profile</returns>
  329. public RegionProfileData readSimRow(IDataReader reader)
  330. {
  331. RegionProfileData retval = new RegionProfileData();
  332. if (reader.Read())
  333. {
  334. // Region Main gotta-have-or-we-return-null parts
  335. UInt64 tmp64;
  336. if (!UInt64.TryParse(reader["regionHandle"].ToString(), out tmp64))
  337. {
  338. return null;
  339. }
  340. else
  341. {
  342. retval.regionHandle = tmp64;
  343. }
  344. UUID tmp_uuid;
  345. if (!UUID.TryParse((string)reader["uuid"], out tmp_uuid))
  346. {
  347. return null;
  348. }
  349. else
  350. {
  351. retval.UUID = tmp_uuid;
  352. }
  353. // non-critical parts
  354. retval.regionName = (string)reader["regionName"];
  355. retval.originUUID = new UUID((string) reader["originUUID"]);
  356. // Secrets
  357. retval.regionRecvKey = (string) reader["regionRecvKey"];
  358. retval.regionSecret = (string) reader["regionSecret"];
  359. retval.regionSendKey = (string) reader["regionSendKey"];
  360. // Region Server
  361. retval.regionDataURI = (string) reader["regionDataURI"];
  362. retval.regionOnline = false; // Needs to be pinged before this can be set.
  363. retval.serverIP = (string) reader["serverIP"];
  364. retval.serverPort = (uint) reader["serverPort"];
  365. retval.serverURI = (string) reader["serverURI"];
  366. retval.httpPort = Convert.ToUInt32(reader["serverHttpPort"].ToString());
  367. retval.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"].ToString());
  368. // Location
  369. retval.regionLocX = Convert.ToUInt32(reader["locX"].ToString());
  370. retval.regionLocY = Convert.ToUInt32(reader["locY"].ToString());
  371. retval.regionLocZ = Convert.ToUInt32(reader["locZ"].ToString());
  372. // Neighbours - 0 = No Override
  373. retval.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"].ToString());
  374. retval.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"].ToString());
  375. retval.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"].ToString());
  376. retval.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"].ToString());
  377. // Assets
  378. retval.regionAssetURI = (string) reader["regionAssetURI"];
  379. retval.regionAssetRecvKey = (string) reader["regionAssetRecvKey"];
  380. retval.regionAssetSendKey = (string) reader["regionAssetSendKey"];
  381. // Userserver
  382. retval.regionUserURI = (string) reader["regionUserURI"];
  383. retval.regionUserRecvKey = (string) reader["regionUserRecvKey"];
  384. retval.regionUserSendKey = (string) reader["regionUserSendKey"];
  385. // World Map Addition
  386. UUID.TryParse((string)reader["regionMapTexture"], out retval.regionMapTextureID);
  387. UUID.TryParse((string)reader["owner_uuid"], out retval.owner_uuid);
  388. retval.maturity = Convert.ToUInt32(reader["access"]);
  389. }
  390. else
  391. {
  392. return null;
  393. }
  394. return retval;
  395. }
  396. /// <summary>
  397. /// Reads a reservation row from a database reader
  398. /// </summary>
  399. /// <param name="reader">An active database reader</param>
  400. /// <returns>A reservation data object</returns>
  401. public ReservationData readReservationRow(IDataReader reader)
  402. {
  403. ReservationData retval = new ReservationData();
  404. if (reader.Read())
  405. {
  406. retval.gridRecvKey = (string) reader["gridRecvKey"];
  407. retval.gridSendKey = (string) reader["gridSendKey"];
  408. retval.reservationCompany = (string) reader["resCompany"];
  409. retval.reservationMaxX = Convert.ToInt32(reader["resXMax"].ToString());
  410. retval.reservationMaxY = Convert.ToInt32(reader["resYMax"].ToString());
  411. retval.reservationMinX = Convert.ToInt32(reader["resXMin"].ToString());
  412. retval.reservationMinY = Convert.ToInt32(reader["resYMin"].ToString());
  413. retval.reservationName = (string) reader["resName"];
  414. retval.status = Convert.ToInt32(reader["status"].ToString()) == 1;
  415. UUID tmp;
  416. UUID.TryParse((string) reader["userUUID"], out tmp);
  417. retval.userUUID = tmp;
  418. }
  419. else
  420. {
  421. return null;
  422. }
  423. return retval;
  424. }
  425. /// <summary>
  426. /// Reads an agent row from a database reader
  427. /// </summary>
  428. /// <param name="reader">An active database reader</param>
  429. /// <returns>A user session agent</returns>
  430. public UserAgentData readAgentRow(IDataReader reader)
  431. {
  432. UserAgentData retval = new UserAgentData();
  433. if (reader.Read())
  434. {
  435. // Agent IDs
  436. UUID tmp;
  437. if (!UUID.TryParse((string)reader["UUID"], out tmp))
  438. return null;
  439. retval.ProfileID = tmp;
  440. UUID.TryParse((string) reader["sessionID"], out tmp);
  441. retval.SessionID = tmp;
  442. UUID.TryParse((string)reader["secureSessionID"], out tmp);
  443. retval.SecureSessionID = tmp;
  444. // Agent Who?
  445. retval.AgentIP = (string) reader["agentIP"];
  446. retval.AgentPort = Convert.ToUInt32(reader["agentPort"].ToString());
  447. retval.AgentOnline = Convert.ToBoolean(Convert.ToInt16(reader["agentOnline"].ToString()));
  448. // Login/Logout times (UNIX Epoch)
  449. retval.LoginTime = Convert.ToInt32(reader["loginTime"].ToString());
  450. retval.LogoutTime = Convert.ToInt32(reader["logoutTime"].ToString());
  451. // Current position
  452. retval.Region = new UUID((string)reader["currentRegion"]);
  453. retval.Handle = Convert.ToUInt64(reader["currentHandle"].ToString());
  454. Vector3 tmp_v;
  455. Vector3.TryParse((string) reader["currentPos"], out tmp_v);
  456. retval.Position = tmp_v;
  457. Vector3.TryParse((string)reader["currentLookAt"], out tmp_v);
  458. retval.LookAt = tmp_v;
  459. }
  460. else
  461. {
  462. return null;
  463. }
  464. return retval;
  465. }
  466. /// <summary>
  467. /// Reads a user profile from an active data reader
  468. /// </summary>
  469. /// <param name="reader">An active database reader</param>
  470. /// <returns>A user profile</returns>
  471. public UserProfileData readUserRow(IDataReader reader)
  472. {
  473. UserProfileData retval = new UserProfileData();
  474. if (reader.Read())
  475. {
  476. UUID id;
  477. if (!UUID.TryParse((string)reader["UUID"], out id))
  478. return null;
  479. retval.ID = id;
  480. retval.FirstName = (string) reader["username"];
  481. retval.SurName = (string) reader["lastname"];
  482. retval.Email = (reader.IsDBNull(reader.GetOrdinal("email"))) ? "" : (string) reader["email"];
  483. retval.PasswordHash = (string) reader["passwordHash"];
  484. retval.PasswordSalt = (string) reader["passwordSalt"];
  485. retval.HomeRegion = Convert.ToUInt64(reader["homeRegion"].ToString());
  486. retval.HomeLocation = new Vector3(
  487. Convert.ToSingle(reader["homeLocationX"].ToString()),
  488. Convert.ToSingle(reader["homeLocationY"].ToString()),
  489. Convert.ToSingle(reader["homeLocationZ"].ToString()));
  490. retval.HomeLookAt = new Vector3(
  491. Convert.ToSingle(reader["homeLookAtX"].ToString()),
  492. Convert.ToSingle(reader["homeLookAtY"].ToString()),
  493. Convert.ToSingle(reader["homeLookAtZ"].ToString()));
  494. UUID regionID = UUID.Zero;
  495. UUID.TryParse(reader["homeRegionID"].ToString(), out regionID); // it's ok if it doesn't work; just use UUID.Zero
  496. retval.HomeRegionID = regionID;
  497. retval.Created = Convert.ToInt32(reader["created"].ToString());
  498. retval.LastLogin = Convert.ToInt32(reader["lastLogin"].ToString());
  499. retval.UserInventoryURI = (string) reader["userInventoryURI"];
  500. retval.UserAssetURI = (string) reader["userAssetURI"];
  501. retval.CanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString());
  502. retval.WantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString());
  503. if (reader.IsDBNull(reader.GetOrdinal("profileAboutText")))
  504. retval.AboutText = "";
  505. else
  506. retval.AboutText = (string) reader["profileAboutText"];
  507. if (reader.IsDBNull(reader.GetOrdinal("profileFirstText")))
  508. retval.FirstLifeAboutText = "";
  509. else
  510. retval.FirstLifeAboutText = (string)reader["profileFirstText"];
  511. if (reader.IsDBNull(reader.GetOrdinal("profileImage")))
  512. retval.Image = UUID.Zero;
  513. else {
  514. UUID tmp;
  515. UUID.TryParse((string)reader["profileImage"], out tmp);
  516. retval.Image = tmp;
  517. }
  518. if (reader.IsDBNull(reader.GetOrdinal("profileFirstImage")))
  519. retval.FirstLifeImage = UUID.Zero;
  520. else {
  521. UUID tmp;
  522. UUID.TryParse((string)reader["profileFirstImage"], out tmp);
  523. retval.FirstLifeImage = tmp;
  524. }
  525. if (reader.IsDBNull(reader.GetOrdinal("webLoginKey")))
  526. {
  527. retval.WebLoginKey = UUID.Zero;
  528. }
  529. else
  530. {
  531. UUID tmp;
  532. UUID.TryParse((string)reader["webLoginKey"], out tmp);
  533. retval.WebLoginKey = tmp;
  534. }
  535. retval.UserFlags = Convert.ToInt32(reader["userFlags"].ToString());
  536. retval.GodLevel = Convert.ToInt32(reader["godLevel"].ToString());
  537. if (reader.IsDBNull(reader.GetOrdinal("customType")))
  538. retval.CustomType = "";
  539. else
  540. retval.CustomType = reader["customType"].ToString();
  541. if (reader.IsDBNull(reader.GetOrdinal("partner")))
  542. {
  543. retval.Partner = UUID.Zero;
  544. }
  545. else
  546. {
  547. UUID tmp;
  548. UUID.TryParse((string)reader["partner"], out tmp);
  549. retval.Partner = tmp;
  550. }
  551. }
  552. else
  553. {
  554. return null;
  555. }
  556. return retval;
  557. }
  558. /// <summary>
  559. /// Reads an avatar appearence from an active data reader
  560. /// </summary>
  561. /// <param name="reader">An active database reader</param>
  562. /// <returns>An avatar appearence</returns>
  563. public AvatarAppearance readAppearanceRow(IDataReader reader)
  564. {
  565. AvatarAppearance appearance = null;
  566. if (reader.Read())
  567. {
  568. appearance = new AvatarAppearance();
  569. appearance.Owner = new UUID((string)reader["owner"]);
  570. appearance.Serial = Convert.ToInt32(reader["serial"]);
  571. appearance.VisualParams = (byte[])reader["visual_params"];
  572. appearance.Texture = new Primitive.TextureEntry((byte[])reader["texture"], 0, ((byte[])reader["texture"]).Length);
  573. appearance.AvatarHeight = (float)Convert.ToDouble(reader["avatar_height"]);
  574. appearance.BodyItem = new UUID((string)reader["body_item"]);
  575. appearance.BodyAsset = new UUID((string)reader["body_asset"]);
  576. appearance.SkinItem = new UUID((string)reader["skin_item"]);
  577. appearance.SkinAsset = new UUID((string)reader["skin_asset"]);
  578. appearance.HairItem = new UUID((string)reader["hair_item"]);
  579. appearance.HairAsset = new UUID((string)reader["hair_asset"]);
  580. appearance.EyesItem = new UUID((string)reader["eyes_item"]);
  581. appearance.EyesAsset = new UUID((string)reader["eyes_asset"]);
  582. appearance.ShirtItem = new UUID((string)reader["shirt_item"]);
  583. appearance.ShirtAsset = new UUID((string)reader["shirt_asset"]);
  584. appearance.PantsItem = new UUID((string)reader["pants_item"]);
  585. appearance.PantsAsset = new UUID((string)reader["pants_asset"]);
  586. appearance.ShoesItem = new UUID((string)reader["shoes_item"]);
  587. appearance.ShoesAsset = new UUID((string)reader["shoes_asset"]);
  588. appearance.SocksItem = new UUID((string)reader["socks_item"]);
  589. appearance.SocksAsset = new UUID((string)reader["socks_asset"]);
  590. appearance.JacketItem = new UUID((string)reader["jacket_item"]);
  591. appearance.JacketAsset = new UUID((string)reader["jacket_asset"]);
  592. appearance.GlovesItem = new UUID((string)reader["gloves_item"]);
  593. appearance.GlovesAsset = new UUID((string)reader["gloves_asset"]);
  594. appearance.UnderShirtItem = new UUID((string)reader["undershirt_item"]);
  595. appearance.UnderShirtAsset = new UUID((string)reader["undershirt_asset"]);
  596. appearance.UnderPantsItem = new UUID((string)reader["underpants_item"]);
  597. appearance.UnderPantsAsset = new UUID((string)reader["underpants_asset"]);
  598. appearance.SkirtItem = new UUID((string)reader["skirt_item"]);
  599. appearance.SkirtAsset = new UUID((string)reader["skirt_asset"]);
  600. }
  601. return appearance;
  602. }
  603. // Read attachment list from data reader
  604. public Hashtable readAttachments(IDataReader r)
  605. {
  606. Hashtable ret = new Hashtable();
  607. while (r.Read())
  608. {
  609. int attachpoint = Convert.ToInt32(r["attachpoint"]);
  610. if (ret.ContainsKey(attachpoint))
  611. continue;
  612. Hashtable item = new Hashtable();
  613. item.Add("item", r["item"].ToString());
  614. item.Add("asset", r["asset"].ToString());
  615. ret.Add(attachpoint, item);
  616. }
  617. r.Close();
  618. return ret;
  619. }
  620. /// <summary>
  621. /// Inserts a new row into the log database
  622. /// </summary>
  623. /// <param name="serverDaemon">The daemon which triggered this event</param>
  624. /// <param name="target">Who were we operating on when this occured (region UUID, user UUID, etc)</param>
  625. /// <param name="methodCall">The method call where the problem occured</param>
  626. /// <param name="arguments">The arguments passed to the method</param>
  627. /// <param name="priority">How critical is this?</param>
  628. /// <param name="logMessage">Extra message info</param>
  629. /// <returns>Saved successfully?</returns>
  630. public bool insertLogRow(string serverDaemon, string target, string methodCall, string arguments, int priority,
  631. string logMessage)
  632. {
  633. string sql = "INSERT INTO logs (`target`, `server`, `method`, `arguments`, `priority`, `message`) VALUES ";
  634. sql += "(?target, ?server, ?method, ?arguments, ?priority, ?message)";
  635. Dictionary<string, object> parameters = new Dictionary<string, object>();
  636. parameters["?server"] = serverDaemon;
  637. parameters["?target"] = target;
  638. parameters["?method"] = methodCall;
  639. parameters["?arguments"] = arguments;
  640. parameters["?priority"] = priority.ToString();
  641. parameters["?message"] = logMessage;
  642. bool returnval = false;
  643. try
  644. {
  645. IDbCommand result = Query(sql, parameters);
  646. if (result.ExecuteNonQuery() == 1)
  647. returnval = true;
  648. result.Dispose();
  649. }
  650. catch (Exception e)
  651. {
  652. m_log.Error(e.ToString());
  653. return false;
  654. }
  655. return returnval;
  656. }
  657. /// <summary>
  658. /// Creates a new user and inserts it into the database
  659. /// </summary>
  660. /// <param name="uuid">User ID</param>
  661. /// <param name="username">First part of the login</param>
  662. /// <param name="lastname">Second part of the login</param>
  663. /// <param name="passwordHash">A salted hash of the users password</param>
  664. /// <param name="passwordSalt">The salt used for the password hash</param>
  665. /// <param name="homeRegion">A regionHandle of the users home region</param>
  666. /// <param name="homeRegionID"> The UUID of the user's home region</param>
  667. /// <param name="homeLocX">Home region position vector</param>
  668. /// <param name="homeLocY">Home region position vector</param>
  669. /// <param name="homeLocZ">Home region position vector</param>
  670. /// <param name="homeLookAtX">Home region 'look at' vector</param>
  671. /// <param name="homeLookAtY">Home region 'look at' vector</param>
  672. /// <param name="homeLookAtZ">Home region 'look at' vector</param>
  673. /// <param name="created">Account created (unix timestamp)</param>
  674. /// <param name="lastlogin">Last login (unix timestamp)</param>
  675. /// <param name="inventoryURI">Users inventory URI</param>
  676. /// <param name="assetURI">Users asset URI</param>
  677. /// <param name="canDoMask">I can do mask</param>
  678. /// <param name="wantDoMask">I want to do mask</param>
  679. /// <param name="aboutText">Profile text</param>
  680. /// <param name="firstText">Firstlife text</param>
  681. /// <param name="profileImage">UUID for profile image</param>
  682. /// <param name="firstImage">UUID for firstlife image</param>
  683. /// <param name="webLoginKey">Ignored</param>
  684. /// <returns>Success?</returns>
  685. public bool insertUserRow(UUID uuid, string username, string lastname, string email, string passwordHash,
  686. string passwordSalt, UInt64 homeRegion, UUID homeRegionID, float homeLocX, float homeLocY, float homeLocZ,
  687. float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin,
  688. string inventoryURI, string assetURI, uint canDoMask, uint wantDoMask,
  689. string aboutText, string firstText,
  690. UUID profileImage, UUID firstImage, UUID webLoginKey, int userFlags, int godLevel, string customType, UUID partner)
  691. {
  692. m_log.Debug("[MySQLManager]: Fetching profile for " + uuid.ToString());
  693. string sql =
  694. "INSERT INTO users (`UUID`, `username`, `lastname`, `email`, `passwordHash`, `passwordSalt`, `homeRegion`, `homeRegionID`, ";
  695. sql +=
  696. "`homeLocationX`, `homeLocationY`, `homeLocationZ`, `homeLookAtX`, `homeLookAtY`, `homeLookAtZ`, `created`, ";
  697. sql +=
  698. "`lastLogin`, `userInventoryURI`, `userAssetURI`, `profileCanDoMask`, `profileWantDoMask`, `profileAboutText`, ";
  699. sql += "`profileFirstText`, `profileImage`, `profileFirstImage`, `webLoginKey`, `userFlags`, `godLevel`, `customType`, `partner`) VALUES ";
  700. sql += "(?UUID, ?username, ?lastname, ?email, ?passwordHash, ?passwordSalt, ?homeRegion, ?homeRegionID, ";
  701. sql +=
  702. "?homeLocationX, ?homeLocationY, ?homeLocationZ, ?homeLookAtX, ?homeLookAtY, ?homeLookAtZ, ?created, ";
  703. sql +=
  704. "?lastLogin, ?userInventoryURI, ?userAssetURI, ?profileCanDoMask, ?profileWantDoMask, ?profileAboutText, ";
  705. sql += "?profileFirstText, ?profileImage, ?profileFirstImage, ?webLoginKey, ?userFlags, ?godLevel, ?customType, ?partner)";
  706. Dictionary<string, object> parameters = new Dictionary<string, object>();
  707. parameters["?UUID"] = uuid.ToString();
  708. parameters["?username"] = username;
  709. parameters["?lastname"] = lastname;
  710. parameters["?email"] = email;
  711. parameters["?passwordHash"] = passwordHash;
  712. parameters["?passwordSalt"] = passwordSalt;
  713. parameters["?homeRegion"] = homeRegion;
  714. parameters["?homeRegionID"] = homeRegionID.ToString();
  715. parameters["?homeLocationX"] = homeLocX;
  716. parameters["?homeLocationY"] = homeLocY;
  717. parameters["?homeLocationZ"] = homeLocZ;
  718. parameters["?homeLookAtX"] = homeLookAtX;
  719. parameters["?homeLookAtY"] = homeLookAtY;
  720. parameters["?homeLookAtZ"] = homeLookAtZ;
  721. parameters["?created"] = created;
  722. parameters["?lastLogin"] = lastlogin;
  723. parameters["?userInventoryURI"] = inventoryURI;
  724. parameters["?userAssetURI"] = assetURI;
  725. parameters["?profileCanDoMask"] = canDoMask;
  726. parameters["?profileWantDoMask"] = wantDoMask;
  727. parameters["?profileAboutText"] = aboutText;
  728. parameters["?profileFirstText"] = firstText;
  729. parameters["?profileImage"] = profileImage.ToString();
  730. parameters["?profileFirstImage"] = firstImage.ToString();
  731. parameters["?webLoginKey"] = webLoginKey.ToString();
  732. parameters["?userFlags"] = userFlags;
  733. parameters["?godLevel"] = godLevel;
  734. parameters["?customType"] = customType == null ? "" : customType;
  735. parameters["?partner"] = partner.ToString();
  736. bool returnval = false;
  737. try
  738. {
  739. IDbCommand result = Query(sql, parameters);
  740. if (result.ExecuteNonQuery() == 1)
  741. returnval = true;
  742. result.Dispose();
  743. }
  744. catch (Exception e)
  745. {
  746. m_log.Error(e.ToString());
  747. return false;
  748. }
  749. //m_log.Debug("[MySQLManager]: Fetch user retval == " + returnval.ToString());
  750. return returnval;
  751. }
  752. /// <summary>
  753. /// Update user data into the database where User ID = uuid
  754. /// </summary>
  755. /// <param name="uuid">User ID</param>
  756. /// <param name="username">First part of the login</param>
  757. /// <param name="lastname">Second part of the login</param>
  758. /// <param name="passwordHash">A salted hash of the users password</param>
  759. /// <param name="passwordSalt">The salt used for the password hash</param>
  760. /// <param name="homeRegion">A regionHandle of the users home region</param>
  761. /// <param name="homeLocX">Home region position vector</param>
  762. /// <param name="homeLocY">Home region position vector</param>
  763. /// <param name="homeLocZ">Home region position vector</param>
  764. /// <param name="homeLookAtX">Home region 'look at' vector</param>
  765. /// <param name="homeLookAtY">Home region 'look at' vector</param>
  766. /// <param name="homeLookAtZ">Home region 'look at' vector</param>
  767. /// <param name="created">Account created (unix timestamp)</param>
  768. /// <param name="lastlogin">Last login (unix timestamp)</param>
  769. /// <param name="inventoryURI">Users inventory URI</param>
  770. /// <param name="assetURI">Users asset URI</param>
  771. /// <param name="canDoMask">I can do mask</param>
  772. /// <param name="wantDoMask">I want to do mask</param>
  773. /// <param name="aboutText">Profile text</param>
  774. /// <param name="firstText">Firstlife text</param>
  775. /// <param name="profileImage">UUID for profile image</param>
  776. /// <param name="firstImage">UUID for firstlife image</param>
  777. /// <param name="webLoginKey">UUID for weblogin Key</param>
  778. /// <returns>Success?</returns>
  779. public bool updateUserRow(UUID uuid, string username, string lastname, string email, string passwordHash,
  780. string passwordSalt, UInt64 homeRegion, UUID homeRegionID, float homeLocX, float homeLocY, float homeLocZ,
  781. float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin,
  782. string inventoryURI, string assetURI, uint canDoMask, uint wantDoMask,
  783. string aboutText, string firstText,
  784. UUID profileImage, UUID firstImage, UUID webLoginKey, int userFlags, int godLevel, string customType, UUID partner)
  785. {
  786. string sql = "UPDATE users SET `username` = ?username , `lastname` = ?lastname, `email` = ?email ";
  787. sql += ", `passwordHash` = ?passwordHash , `passwordSalt` = ?passwordSalt , ";
  788. sql += "`homeRegion` = ?homeRegion , `homeRegionID` = ?homeRegionID, `homeLocationX` = ?homeLocationX , ";
  789. sql += "`homeLocationY` = ?homeLocationY , `homeLocationZ` = ?homeLocationZ , ";
  790. sql += "`homeLookAtX` = ?homeLookAtX , `homeLookAtY` = ?homeLookAtY , ";
  791. sql += "`homeLookAtZ` = ?homeLookAtZ , `created` = ?created , `lastLogin` = ?lastLogin , ";
  792. sql += "`userInventoryURI` = ?userInventoryURI , `userAssetURI` = ?userAssetURI , ";
  793. sql += "`profileCanDoMask` = ?profileCanDoMask , `profileWantDoMask` = ?profileWantDoMask , ";
  794. sql += "`profileAboutText` = ?profileAboutText , `profileFirstText` = ?profileFirstText, ";
  795. sql += "`profileImage` = ?profileImage , `profileFirstImage` = ?profileFirstImage , ";
  796. sql += "`userFlags` = ?userFlags , `godLevel` = ?godLevel , ";
  797. sql += "`customType` = ?customType , `partner` = ?partner , ";
  798. sql += "`webLoginKey` = ?webLoginKey WHERE UUID = ?UUID";
  799. Dictionary<string, object> parameters = new Dictionary<string, object>();
  800. parameters["?UUID"] = uuid.ToString();
  801. parameters["?username"] = username;
  802. parameters["?lastname"] = lastname;
  803. parameters["?email"] = email;
  804. parameters["?passwordHash"] = passwordHash;
  805. parameters["?passwordSalt"] = passwordSalt;
  806. parameters["?homeRegion"] = homeRegion;
  807. parameters["?homeRegionID"] = homeRegionID.ToString();
  808. parameters["?homeLocationX"] = homeLocX;
  809. parameters["?homeLocationY"] = homeLocY;
  810. parameters["?homeLocationZ"] = homeLocZ;
  811. parameters["?homeLookAtX"] = homeLookAtX;
  812. parameters["?homeLookAtY"] = homeLookAtY;
  813. parameters["?homeLookAtZ"] = homeLookAtZ;
  814. parameters["?created"] = created;
  815. parameters["?lastLogin"] = lastlogin;
  816. parameters["?userInventoryURI"] = inventoryURI;
  817. parameters["?userAssetURI"] = assetURI;
  818. parameters["?profileCanDoMask"] = canDoMask;
  819. parameters["?profileWantDoMask"] = wantDoMask;
  820. parameters["?profileAboutText"] = aboutText;
  821. parameters["?profileFirstText"] = firstText;
  822. parameters["?profileImage"] = profileImage.ToString();
  823. parameters["?profileFirstImage"] = firstImage.ToString();
  824. parameters["?webLoginKey"] = webLoginKey.ToString();
  825. parameters["?userFlags"] = userFlags;
  826. parameters["?godLevel"] = godLevel;
  827. parameters["?customType"] = customType == null ? "" : customType;
  828. parameters["?partner"] = partner.ToString();
  829. bool returnval = false;
  830. try
  831. {
  832. IDbCommand result = Query(sql, parameters);
  833. if (result.ExecuteNonQuery() == 1)
  834. returnval = true;
  835. result.Dispose();
  836. }
  837. catch (Exception e)
  838. {
  839. m_log.Error(e.ToString());
  840. return false;
  841. }
  842. //m_log.Debug("[MySQLManager]: update user retval == " + returnval.ToString());
  843. return returnval;
  844. }
  845. /// <summary>
  846. /// Inserts a new region into the database
  847. /// </summary>
  848. /// <param name="regiondata">The region to insert</param>
  849. /// <returns>Success?</returns>
  850. public bool insertRegion(RegionProfileData regiondata)
  851. {
  852. bool GRID_ONLY_UPDATE_NECESSARY_DATA = false;
  853. string sql = String.Empty;
  854. if (GRID_ONLY_UPDATE_NECESSARY_DATA)
  855. {
  856. sql += "INSERT INTO ";
  857. }
  858. else
  859. {
  860. sql += "REPLACE INTO ";
  861. }
  862. sql += "regions (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, ";
  863. sql +=
  864. "serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, ";
  865. // part of an initial brutish effort to provide accurate information (as per the xml region spec)
  866. // wrt the ownership of a given region
  867. // the (very bad) assumption is that this value is being read and handled inconsistently or
  868. // not at all. Current strategy is to put the code in place to support the validity of this information
  869. // and to roll forward debugging any issues from that point
  870. //
  871. // this particular section of the mod attempts to implement the commit of a supplied value
  872. // server for the UUID of the region's owner (master avatar). It consists of the addition of the column and value to the relevant sql,
  873. // as well as the related parameterization
  874. sql +=
  875. "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid, originUUID, access) VALUES ";
  876. sql += "(?regionHandle, ?regionName, ?uuid, ?regionRecvKey, ?regionSecret, ?regionSendKey, ?regionDataURI, ";
  877. sql +=
  878. "?serverIP, ?serverPort, ?serverURI, ?locX, ?locY, ?locZ, ?eastOverrideHandle, ?westOverrideHandle, ?southOverrideHandle, ?northOverrideHandle, ?regionAssetURI, ?regionAssetRecvKey, ";
  879. sql +=
  880. "?regionAssetSendKey, ?regionUserURI, ?regionUserRecvKey, ?regionUserSendKey, ?regionMapTexture, ?serverHttpPort, ?serverRemotingPort, ?owner_uuid, ?originUUID, ?access)";
  881. if (GRID_ONLY_UPDATE_NECESSARY_DATA)
  882. {
  883. sql += "ON DUPLICATE KEY UPDATE serverIP = ?serverIP, serverPort = ?serverPort, serverURI = ?serverURI, owner_uuid - ?owner_uuid;";
  884. }
  885. else
  886. {
  887. sql += ";";
  888. }
  889. Dictionary<string, object> parameters = new Dictionary<string, object>();
  890. parameters["?regionHandle"] = regiondata.regionHandle.ToString();
  891. parameters["?regionName"] = regiondata.regionName.ToString();
  892. parameters["?uuid"] = regiondata.UUID.ToString();
  893. parameters["?regionRecvKey"] = regiondata.regionRecvKey.ToString();
  894. parameters["?regionSecret"] = regiondata.regionSecret.ToString();
  895. parameters["?regionSendKey"] = regiondata.regionSendKey.ToString();
  896. parameters["?regionDataURI"] = regiondata.regionDataURI.ToString();
  897. parameters["?serverIP"] = regiondata.serverIP.ToString();
  898. parameters["?serverPort"] = regiondata.serverPort.ToString();
  899. parameters["?serverURI"] = regiondata.serverURI.ToString();
  900. parameters["?locX"] = regiondata.regionLocX.ToString();
  901. parameters["?locY"] = regiondata.regionLocY.ToString();
  902. parameters["?locZ"] = regiondata.regionLocZ.ToString();
  903. parameters["?eastOverrideHandle"] = regiondata.regionEastOverrideHandle.ToString();
  904. parameters["?westOverrideHandle"] = regiondata.regionWestOverrideHandle.ToString();
  905. parameters["?northOverrideHandle"] = regiondata.regionNorthOverrideHandle.ToString();
  906. parameters["?southOverrideHandle"] = regiondata.regionSouthOverrideHandle.ToString();
  907. parameters["?regionAssetURI"] = regiondata.regionAssetURI.ToString();
  908. parameters["?regionAssetRecvKey"] = regiondata.regionAssetRecvKey.ToString();
  909. parameters["?regionAssetSendKey"] = regiondata.regionAssetSendKey.ToString();
  910. parameters["?regionUserURI"] = regiondata.regionUserURI.ToString();
  911. parameters["?regionUserRecvKey"] = regiondata.regionUserRecvKey.ToString();
  912. parameters["?regionUserSendKey"] = regiondata.regionUserSendKey.ToString();
  913. parameters["?regionMapTexture"] = regiondata.regionMapTextureID.ToString();
  914. parameters["?serverHttpPort"] = regiondata.httpPort.ToString();
  915. parameters["?serverRemotingPort"] = regiondata.remotingPort.ToString();
  916. parameters["?owner_uuid"] = regiondata.owner_uuid.ToString();
  917. parameters["?originUUID"] = regiondata.originUUID.ToString();
  918. parameters["?access"] = regiondata.maturity.ToString();
  919. bool returnval = false;
  920. try
  921. {
  922. IDbCommand result = Query(sql, parameters);
  923. // int x;
  924. // if ((x = result.ExecuteNonQuery()) > 0)
  925. // {
  926. // returnval = true;
  927. // }
  928. if (result.ExecuteNonQuery() > 0)
  929. {
  930. returnval = true;
  931. }
  932. result.Dispose();
  933. }
  934. catch (Exception e)
  935. {
  936. m_log.Error(e.ToString());
  937. return false;
  938. }
  939. return returnval;
  940. }
  941. /// <summary>
  942. /// Delete a region from the database
  943. /// </summary>
  944. /// <param name="uuid">The region to delete</param>
  945. /// <returns>Success?</returns>
  946. //public bool deleteRegion(RegionProfileData regiondata)
  947. public bool deleteRegion(string uuid)
  948. {
  949. bool returnval = false;
  950. string sql = "DELETE FROM regions WHERE uuid = ?uuid;";
  951. Dictionary<string, object> parameters = new Dictionary<string, object>();
  952. try
  953. {
  954. parameters["?uuid"] = uuid;
  955. IDbCommand result = Query(sql, parameters);
  956. // int x;
  957. // if ((x = result.ExecuteNonQuery()) > 0)
  958. // {
  959. // returnval = true;
  960. // }
  961. if (result.ExecuteNonQuery() > 0)
  962. {
  963. returnval = true;
  964. }
  965. result.Dispose();
  966. }
  967. catch (Exception e)
  968. {
  969. m_log.Error(e.ToString());
  970. return false;
  971. }
  972. return returnval;
  973. }
  974. /// <summary>
  975. /// Creates a new agent and inserts it into the database
  976. /// </summary>
  977. /// <param name="agentdata">The agent data to be inserted</param>
  978. /// <returns>Success?</returns>
  979. public bool insertAgentRow(UserAgentData agentdata)
  980. {
  981. string sql = String.Empty;
  982. sql += "REPLACE INTO ";
  983. sql += "agents (UUID, sessionID, secureSessionID, agentIP, agentPort, agentOnline, loginTime, logoutTime, currentRegion, currentHandle, currentPos, currentLookAt) VALUES ";
  984. sql += "(?UUID, ?sessionID, ?secureSessionID, ?agentIP, ?agentPort, ?agentOnline, ?loginTime, ?logoutTime, ?currentRegion, ?currentHandle, ?currentPos, ?currentLookAt);";
  985. Dictionary<string, object> parameters = new Dictionary<string, object>();
  986. parameters["?UUID"] = agentdata.ProfileID.ToString();
  987. parameters["?sessionID"] = agentdata.SessionID.ToString();
  988. parameters["?secureSessionID"] = agentdata.SecureSessionID.ToString();
  989. parameters["?agentIP"] = agentdata.AgentIP.ToString();
  990. parameters["?agentPort"] = agentdata.AgentPort.ToString();
  991. parameters["?agentOnline"] = (agentdata.AgentOnline == true) ? "1" : "0";
  992. parameters["?loginTime"] = agentdata.LoginTime.ToString();
  993. parameters["?logoutTime"] = agentdata.LogoutTime.ToString();
  994. parameters["?currentRegion"] = agentdata.Region.ToString();
  995. parameters["?currentHandle"] = agentdata.Handle.ToString();
  996. parameters["?currentPos"] = "<" + (agentdata.Position.X).ToString().Replace(",", ".") + "," + (agentdata.Position.Y).ToString().Replace(",", ".") + "," + (agentdata.Position.Z).ToString().Replace(",", ".") + ">";
  997. parameters["?currentLookAt"] = "<" + (agentdata.LookAt.X).ToString().Replace(",", ".") + "," + (agentdata.LookAt.Y).ToString().Replace(",", ".") + "," + (agentdata.LookAt.Z).ToString().Replace(",", ".") + ">";
  998. bool returnval = false;
  999. try
  1000. {
  1001. IDbCommand result = Query(sql, parameters);
  1002. // int x;
  1003. // if ((x = result.ExecuteNonQuery()) > 0)
  1004. // {
  1005. // returnval = true;
  1006. // }
  1007. if (result.ExecuteNonQuery() > 0)
  1008. {
  1009. returnval = true;
  1010. }
  1011. result.Dispose();
  1012. }
  1013. catch (Exception e)
  1014. {
  1015. m_log.Error(e.ToString());
  1016. return false;
  1017. }
  1018. return returnval;
  1019. }
  1020. /// <summary>
  1021. /// Create (or replace if existing) an avatar appearence
  1022. /// </summary>
  1023. /// <param name="appearance"></param>
  1024. /// <returns>Succes?</returns>
  1025. public bool insertAppearanceRow(AvatarAppearance appearance)
  1026. {
  1027. string sql = String.Empty;
  1028. sql += "REPLACE INTO ";
  1029. sql += "avatarappearance (owner, serial, visual_params, texture, avatar_height, ";
  1030. sql += "body_item, body_asset, skin_item, skin_asset, hair_item, hair_asset, eyes_item, eyes_asset, ";
  1031. sql += "shirt_item, shirt_asset, pants_item, pants_asset, shoes_item, shoes_asset, socks_item, socks_asset, ";
  1032. sql += "jacket_item, jacket_asset, gloves_item, gloves_asset, undershirt_item, undershirt_asset, underpants_item, underpants_asset, ";
  1033. sql += "skirt_item, skirt_asset) values (";
  1034. sql += "?owner, ?serial, ?visual_params, ?texture, ?avatar_height, ";
  1035. sql += "?body_item, ?body_asset, ?skin_item, ?skin_asset, ?hair_item, ?hair_asset, ?eyes_item, ?eyes_asset, ";
  1036. sql += "?shirt_item, ?shirt_asset, ?pants_item, ?pants_asset, ?shoes_item, ?shoes_asset, ?socks_item, ?socks_asset, ";
  1037. sql += "?jacket_item, ?jacket_asset, ?gloves_item, ?gloves_asset, ?undershirt_item, ?undershirt_asset, ?underpants_item, ?underpants_asset, ";
  1038. sql += "?skirt_item, ?skirt_asset)";
  1039. bool returnval = false;
  1040. // we want to send in byte data, which means we can't just pass down strings
  1041. try {
  1042. MySqlCommand cmd = (MySqlCommand) dbcon.CreateCommand();
  1043. cmd.CommandText = sql;
  1044. cmd.Parameters.AddWithValue("?owner", appearance.Owner.ToString());
  1045. cmd.Parameters.AddWithValue("?serial", appearance.Serial);
  1046. cmd.Parameters.AddWithValue("?visual_params", appearance.VisualParams);
  1047. cmd.Parameters.AddWithValue("?texture", appearance.Texture.GetBytes());
  1048. cmd.Parameters.AddWithValue("?avatar_height", appearance.AvatarHeight);
  1049. cmd.Parameters.AddWithValue("?body_item", appearance.BodyItem.ToString());
  1050. cmd.Parameters.AddWithValue("?body_asset", appearance.BodyAsset.ToString());
  1051. cmd.Parameters.AddWithValue("?skin_item", appearance.SkinItem.ToString());
  1052. cmd.Parameters.AddWithValue("?skin_asset", appearance.SkinAsset.ToString());
  1053. cmd.Parameters.AddWithValue("?hair_item", appearance.HairItem.ToString());
  1054. cmd.Parameters.AddWithValue("?hair_asset", appearance.HairAsset.ToString());
  1055. cmd.Parameters.AddWithValue("?eyes_item", appearance.EyesItem.ToString());
  1056. cmd.Parameters.AddWithValue("?eyes_asset", appearance.EyesAsset.ToString());
  1057. cmd.Parameters.AddWithValue("?shirt_item", appearance.ShirtItem.ToString());
  1058. cmd.Parameters.AddWithValue("?shirt_asset", appearance.ShirtAsset.ToString());
  1059. cmd.Parameters.AddWithValue("?pants_item", appearance.PantsItem.ToString());
  1060. cmd.Parameters.AddWithValue("?pants_asset", appearance.PantsAsset.ToString());
  1061. cmd.Parameters.AddWithValue("?shoes_item", appearance.ShoesItem.ToString());
  1062. cmd.Parameters.AddWithValue("?shoes_asset", appearance.ShoesAsset.ToString());
  1063. cmd.Parameters.AddWithValue("?socks_item", appearance.SocksItem.ToString());
  1064. cmd.Parameters.AddWithValue("?socks_asset", appearance.SocksAsset.ToString());
  1065. cmd.Parameters.AddWithValue("?jacket_item", appearance.JacketItem.ToString());
  1066. cmd.Parameters.AddWithValue("?jacket_asset", appearance.JacketAsset.ToString());
  1067. cmd.Parameters.AddWithValue("?gloves_item", appearance.GlovesItem.ToString());
  1068. cmd.Parameters.AddWithValue("?gloves_asset", appearance.GlovesAsset.ToString());
  1069. cmd.Parameters.AddWithValue("?undershirt_item", appearance.UnderShirtItem.ToString());
  1070. cmd.Parameters.AddWithValue("?undershirt_asset", appearance.UnderShirtAsset.ToString());
  1071. cmd.Parameters.AddWithValue("?underpants_item", appearance.UnderPantsItem.ToString());
  1072. cmd.Parameters.AddWithValue("?underpants_asset", appearance.UnderPantsAsset.ToString());
  1073. cmd.Parameters.AddWithValue("?skirt_item", appearance.SkirtItem.ToString());
  1074. cmd.Parameters.AddWithValue("?skirt_asset", appearance.SkirtAsset.ToString());
  1075. if (cmd.ExecuteNonQuery() > 0)
  1076. returnval = true;
  1077. cmd.Dispose();
  1078. }
  1079. catch (Exception e)
  1080. {
  1081. m_log.Error(e.ToString());
  1082. return false;
  1083. }
  1084. return returnval;
  1085. }
  1086. public void writeAttachments(UUID agentID, Hashtable data)
  1087. {
  1088. string sql = "delete from avatarattachments where UUID = ?uuid";
  1089. MySqlCommand cmd = (MySqlCommand) dbcon.CreateCommand();
  1090. cmd.CommandText = sql;
  1091. cmd.Parameters.AddWithValue("?uuid", agentID.ToString());
  1092. cmd.ExecuteNonQuery();
  1093. if (data == null)
  1094. return;
  1095. sql = "insert into avatarattachments (UUID, attachpoint, item, asset) values (?uuid, ?attachpoint, ?item, ?asset)";
  1096. cmd = (MySqlCommand) dbcon.CreateCommand();
  1097. cmd.CommandText = sql;
  1098. foreach (DictionaryEntry e in data)
  1099. {
  1100. int attachpoint = Convert.ToInt32(e.Key);
  1101. Hashtable item = (Hashtable)e.Value;
  1102. cmd.Parameters.Clear();
  1103. cmd.Parameters.AddWithValue("?uuid", agentID.ToString());
  1104. cmd.Parameters.AddWithValue("?attachpoint", attachpoint);
  1105. cmd.Parameters.AddWithValue("?item", item["item"]);
  1106. cmd.Parameters.AddWithValue("?asset", item["asset"]);
  1107. cmd.ExecuteNonQuery();
  1108. }
  1109. }
  1110. }
  1111. }