MySQLInventoryData.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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.IO;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using log4net;
  32. using MySql.Data.MySqlClient;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. namespace OpenSim.Data.MySQL
  36. {
  37. /// <summary>
  38. /// A MySQL interface for the inventory server
  39. /// </summary>
  40. public class MySQLInventoryData : IInventoryDataPlugin
  41. {
  42. private static readonly ILog m_log
  43. = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  44. /// <summary>
  45. /// The database manager
  46. /// </summary>
  47. private MySQLManager database;
  48. private bool rollbackStore = false;
  49. private bool opengridmode = false;
  50. private string rollbackDir = "";
  51. public void Initialise()
  52. {
  53. m_log.Info("[MySQLInventoryData]: " + Name + " cannot be default-initialized!");
  54. throw new PluginNotInitialisedException (Name);
  55. }
  56. /// <summary>
  57. /// <para>Initialises Inventory interface</para>
  58. /// <para>
  59. /// <list type="bullet">
  60. /// <item>Loads and initialises the MySQL storage plugin</item>
  61. /// <item>warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
  62. /// <item>Check for migration</item>
  63. /// </list>
  64. /// </para>
  65. /// </summary>
  66. /// <param name="connect">connect string</param>
  67. public void Initialise(string connect)
  68. {
  69. if (connect != String.Empty)
  70. {
  71. database = new MySQLManager(connect);
  72. }
  73. else
  74. {
  75. m_log.Warn("Reverting to deprecated mysql_connection.ini file for connection info");
  76. IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini");
  77. string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname");
  78. string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database");
  79. string settingUsername = GridDataMySqlFile.ParseFileReadValue("username");
  80. string settingPassword = GridDataMySqlFile.ParseFileReadValue("password");
  81. string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling");
  82. string settingPort = GridDataMySqlFile.ParseFileReadValue("port");
  83. rollbackDir = GridDataMySqlFile.ParseFileReadValue("rollbackdir");
  84. rollbackStore = GridDataMySqlFile.ParseFileReadValue("rollback") == "true";
  85. opengridmode = GridDataMySqlFile.ParseFileReadValue("opengridmode") == "true";
  86. if (rollbackStore)
  87. m_log.Warn("[MysqlInventory] Enabling rollback mode in: " + rollbackDir);
  88. database =
  89. new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling,
  90. settingPort);
  91. }
  92. // This actually does the roll forward assembly stuff
  93. Assembly assem = GetType().Assembly;
  94. Migration m = new Migration(database.Connection, assem, "InventoryStore");
  95. m.Update();
  96. }
  97. /// <summary>
  98. /// The name of this DB provider
  99. /// </summary>
  100. /// <returns>Name of DB provider</returns>
  101. public string Name
  102. {
  103. get { return "MySQL Inventory Data Interface"; }
  104. }
  105. /// <summary>
  106. /// Closes this DB provider
  107. /// </summary>
  108. /// <remarks>do nothing</remarks>
  109. public void Dispose()
  110. {
  111. // Do nothing.
  112. }
  113. /// <summary>
  114. /// Returns the version of this DB provider
  115. /// </summary>
  116. /// <returns>A string containing the DB provider version</returns>
  117. public string Version
  118. {
  119. get { return database.getVersion(); }
  120. }
  121. /// <summary>
  122. /// Returns a list of items in a specified folder
  123. /// </summary>
  124. /// <param name="folderID">The folder to search</param>
  125. /// <returns>A list containing inventory items</returns>
  126. public List<InventoryItemBase> getInventoryInFolder(UUID folderID)
  127. {
  128. try
  129. {
  130. lock (database)
  131. {
  132. List<InventoryItemBase> items = new List<InventoryItemBase>();
  133. database.CheckConnection();
  134. MySqlCommand result =
  135. new MySqlCommand("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid",
  136. database.Connection);
  137. result.Parameters.AddWithValue("?uuid", folderID.ToString());
  138. MySqlDataReader reader = result.ExecuteReader();
  139. while (reader.Read())
  140. {
  141. // A null item (because something went wrong) breaks everything in the folder
  142. InventoryItemBase item = readInventoryItem(reader);
  143. if (item != null)
  144. items.Add(item);
  145. }
  146. reader.Close();
  147. result.Dispose();
  148. return items;
  149. }
  150. }
  151. catch (Exception e)
  152. {
  153. database.Reconnect();
  154. m_log.Error(e.ToString());
  155. return null;
  156. }
  157. }
  158. /// <summary>
  159. /// Returns a list of the root folders within a users inventory
  160. /// </summary>
  161. /// <param name="user">The user whos inventory is to be searched</param>
  162. /// <returns>A list of folder objects</returns>
  163. public List<InventoryFolderBase> getUserRootFolders(UUID user)
  164. {
  165. try
  166. {
  167. lock (database)
  168. {
  169. database.CheckConnection();
  170. MySqlCommand result =
  171. new MySqlCommand(
  172. "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
  173. database.Connection);
  174. result.Parameters.AddWithValue("?uuid", user.ToString());
  175. result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
  176. MySqlDataReader reader = result.ExecuteReader();
  177. List<InventoryFolderBase> items = new List<InventoryFolderBase>();
  178. while (reader.Read())
  179. items.Add(readInventoryFolder(reader));
  180. reader.Close();
  181. result.Dispose();
  182. return items;
  183. }
  184. }
  185. catch (Exception e)
  186. {
  187. database.Reconnect();
  188. m_log.Error(e.ToString());
  189. return null;
  190. }
  191. }
  192. /// <summary>
  193. /// see <see cref="InventoryItemBase.getUserRootFolder"/>
  194. /// </summary>
  195. /// <param name="user">The user UUID</param>
  196. /// <returns></returns>
  197. public InventoryFolderBase getUserRootFolder(UUID user)
  198. {
  199. try
  200. {
  201. lock (database)
  202. {
  203. database.CheckConnection();
  204. MySqlCommand result =
  205. new MySqlCommand(
  206. "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
  207. database.Connection);
  208. result.Parameters.AddWithValue("?uuid", user.ToString());
  209. result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
  210. MySqlDataReader reader = result.ExecuteReader();
  211. List<InventoryFolderBase> items = new List<InventoryFolderBase>();
  212. while (reader.Read())
  213. items.Add(readInventoryFolder(reader));
  214. InventoryFolderBase rootFolder = null;
  215. // There should only ever be one root folder for a user. However, if there's more
  216. // than one we'll simply use the first one rather than failing. It would be even
  217. // nicer to print some message to this effect, but this feels like it's too low a
  218. // to put such a message out, and it's too minor right now to spare the time to
  219. // suitably refactor.
  220. if (items.Count > 0)
  221. {
  222. rootFolder = items[0];
  223. }
  224. reader.Close();
  225. result.Dispose();
  226. return rootFolder;
  227. }
  228. }
  229. catch (Exception e)
  230. {
  231. database.Reconnect();
  232. m_log.Error(e.ToString());
  233. throw;
  234. }
  235. }
  236. /// <summary>
  237. /// Return a list of folders in a users inventory contained within the specified folder.
  238. /// This method is only used in tests - in normal operation the user always have one,
  239. /// and only one, root folder.
  240. /// </summary>
  241. /// <param name="parentID">The folder to search</param>
  242. /// <returns>A list of inventory folders</returns>
  243. public List<InventoryFolderBase> getInventoryFolders(UUID parentID)
  244. {
  245. try
  246. {
  247. lock (database)
  248. {
  249. database.CheckConnection();
  250. MySqlCommand result =
  251. new MySqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid",
  252. database.Connection);
  253. result.Parameters.AddWithValue("?uuid", parentID.ToString());
  254. MySqlDataReader reader = result.ExecuteReader();
  255. List<InventoryFolderBase> items = new List<InventoryFolderBase>();
  256. while (reader.Read())
  257. items.Add(readInventoryFolder(reader));
  258. reader.Close();
  259. result.Dispose();
  260. return items;
  261. }
  262. }
  263. catch (Exception e)
  264. {
  265. database.Reconnect();
  266. m_log.Error(e.ToString());
  267. return null;
  268. }
  269. }
  270. /// <summary>
  271. /// Reads a one item from an SQL result
  272. /// </summary>
  273. /// <param name="reader">The SQL Result</param>
  274. /// <returns>the item read</returns>
  275. private static InventoryItemBase readInventoryItem(MySqlDataReader reader)
  276. {
  277. try
  278. {
  279. InventoryItemBase item = new InventoryItemBase();
  280. // TODO: this is to handle a case where NULLs creep in there, which we are not sure is indemic to the system, or legacy. It would be nice to live fix these.
  281. if (reader["creatorID"] == null)
  282. {
  283. item.CreatorId = UUID.Zero.ToString();
  284. }
  285. else
  286. {
  287. item.CreatorId = (string)reader["creatorID"];
  288. }
  289. // Be a bit safer in parsing these because the
  290. // database doesn't enforce them to be not null, and
  291. // the inventory still works if these are weird in the
  292. // db
  293. UUID Owner = UUID.Zero;
  294. UUID GroupID = UUID.Zero;
  295. UUID.TryParse((string)reader["avatarID"], out Owner);
  296. UUID.TryParse((string)reader["groupID"], out GroupID);
  297. item.Owner = Owner;
  298. item.GroupID = GroupID;
  299. // Rest of the parsing. If these UUID's fail, we're dead anyway
  300. item.ID = new UUID((string) reader["inventoryID"]);
  301. item.AssetID = new UUID((string) reader["assetID"]);
  302. item.AssetType = (int) reader["assetType"];
  303. item.Folder = new UUID((string) reader["parentFolderID"]);
  304. item.Name = (string) reader["inventoryName"];
  305. item.Description = (string) reader["inventoryDescription"];
  306. item.NextPermissions = (uint) reader["inventoryNextPermissions"];
  307. item.CurrentPermissions = (uint) reader["inventoryCurrentPermissions"];
  308. item.InvType = (int) reader["invType"];
  309. item.BasePermissions = (uint) reader["inventoryBasePermissions"];
  310. item.EveryOnePermissions = (uint) reader["inventoryEveryOnePermissions"];
  311. item.GroupPermissions = (uint) reader["inventoryGroupPermissions"];
  312. item.SalePrice = (int) reader["salePrice"];
  313. item.SaleType = unchecked((byte)(Convert.ToSByte(reader["saleType"])));
  314. item.CreationDate = (int) reader["creationDate"];
  315. item.GroupOwned = Convert.ToBoolean(reader["groupOwned"]);
  316. item.Flags = (uint) reader["flags"];
  317. return item;
  318. }
  319. catch (MySqlException e)
  320. {
  321. m_log.Error(e.ToString());
  322. }
  323. return null;
  324. }
  325. /// <summary>
  326. /// Returns a specified inventory item
  327. /// </summary>
  328. /// <param name="item">The item to return</param>
  329. /// <returns>An inventory item</returns>
  330. public InventoryItemBase getInventoryItem(UUID itemID)
  331. {
  332. try
  333. {
  334. lock (database)
  335. {
  336. database.CheckConnection();
  337. MySqlCommand result =
  338. new MySqlCommand("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", database.Connection);
  339. result.Parameters.AddWithValue("?uuid", itemID.ToString());
  340. MySqlDataReader reader = result.ExecuteReader();
  341. InventoryItemBase item = null;
  342. if (reader.Read())
  343. item = readInventoryItem(reader);
  344. reader.Close();
  345. result.Dispose();
  346. return item;
  347. }
  348. }
  349. catch (Exception e)
  350. {
  351. database.Reconnect();
  352. m_log.Error(e.ToString());
  353. }
  354. return null;
  355. }
  356. /// <summary>
  357. /// Reads a list of inventory folders returned by a query.
  358. /// </summary>
  359. /// <param name="reader">A MySQL Data Reader</param>
  360. /// <returns>A List containing inventory folders</returns>
  361. protected static InventoryFolderBase readInventoryFolder(MySqlDataReader reader)
  362. {
  363. try
  364. {
  365. InventoryFolderBase folder = new InventoryFolderBase();
  366. folder.Owner = new UUID((string) reader["agentID"]);
  367. folder.ParentID = new UUID((string) reader["parentFolderID"]);
  368. folder.ID = new UUID((string) reader["folderID"]);
  369. folder.Name = (string) reader["folderName"];
  370. folder.Type = (short) reader["type"];
  371. folder.Version = (ushort) ((int) reader["version"]);
  372. return folder;
  373. }
  374. catch (Exception e)
  375. {
  376. m_log.Error(e.ToString());
  377. }
  378. return null;
  379. }
  380. /// <summary>
  381. /// Returns a specified inventory folder
  382. /// </summary>
  383. /// <param name="folderID">The folder to return</param>
  384. /// <returns>A folder class</returns>
  385. public InventoryFolderBase getInventoryFolder(UUID folderID)
  386. {
  387. try
  388. {
  389. lock (database)
  390. {
  391. database.CheckConnection();
  392. MySqlCommand result =
  393. new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection);
  394. result.Parameters.AddWithValue("?uuid", folderID.ToString());
  395. MySqlDataReader reader = result.ExecuteReader();
  396. InventoryFolderBase folder = null;
  397. if (reader.Read())
  398. folder = readInventoryFolder(reader);
  399. reader.Close();
  400. result.Dispose();
  401. return folder;
  402. }
  403. }
  404. catch (Exception e)
  405. {
  406. database.Reconnect();
  407. m_log.Error(e.ToString());
  408. return null;
  409. }
  410. }
  411. #region Inventory Rollback-via-.sql Support
  412. /// <summary>
  413. /// Not a good SQL escape function, but it'll do the job (if mutilate the data.)
  414. /// Someone may want to write something better here.
  415. /// </summary>
  416. /// <param name="str"></param>
  417. /// <returns></returns>
  418. private static string cheapSQLescape(string str)
  419. {
  420. str = str.Replace("\\", "");
  421. str = str.Replace("'", "");
  422. str = str.Replace("\"", "");
  423. return "'" + str + "'";
  424. }
  425. private static string InventoryItemToSql(InventoryItemBase item)
  426. {
  427. string sql =
  428. "REPLACE /*! INVITEM AT ***$SUBS$*** */ INTO inventoryitems (inventoryID, assetID, assetType, parentFolderID, avatarID, inventoryName"
  429. + ", inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType"
  430. + ", creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, inventoryGroupPermissions, salePrice, saleType"
  431. + ", creationDate, groupID, groupOwned, flags) VALUES ";
  432. sql +=
  433. "(?inventoryID, ?assetID, ?assetType, ?parentFolderID, ?avatarID, ?inventoryName, ?inventoryDescription"
  434. + ", ?inventoryNextPermissions, ?inventoryCurrentPermissions, ?invType, ?creatorID"
  435. + ", ?inventoryBasePermissions, ?inventoryEveryOnePermissions, ?inventoryGroupPermissions, ?salePrice, ?saleType, ?creationDate"
  436. + ", ?groupID, ?groupOwned, ?flags);\r\n";
  437. string itemName = item.Name;
  438. string itemDesc = item.Description;
  439. sql = sql.Replace("$SUBS$", Util.UnixTimeSinceEpoch().ToString());
  440. sql = sql.Replace("?inventoryID", cheapSQLescape(item.ID.ToString()));
  441. sql = sql.Replace("?assetID", cheapSQLescape(item.AssetID.ToString()));
  442. sql = sql.Replace("?assetType", cheapSQLescape(item.AssetType.ToString()));
  443. sql = sql.Replace("?parentFolderID", cheapSQLescape(item.Folder.ToString()));
  444. sql = sql.Replace("?avatarID", cheapSQLescape(item.Owner.ToString()));
  445. sql = sql.Replace("?inventoryName", cheapSQLescape(itemName));
  446. sql = sql.Replace("?inventoryDescription", cheapSQLescape(itemDesc));
  447. sql = sql.Replace("?inventoryNextPermissions", cheapSQLescape(item.NextPermissions.ToString()));
  448. sql = sql.Replace("?inventoryCurrentPermissions", cheapSQLescape(item.CurrentPermissions.ToString()));
  449. sql = sql.Replace("?invType", cheapSQLescape(item.InvType.ToString()));
  450. sql = sql.Replace("?creatorID", cheapSQLescape(item.CreatorId));
  451. sql = sql.Replace("?inventoryBasePermissions", cheapSQLescape(item.BasePermissions.ToString()));
  452. sql = sql.Replace("?inventoryEveryOnePermissions", cheapSQLescape(item.EveryOnePermissions.ToString()));
  453. sql = sql.Replace("?inventoryGroupPermissions", cheapSQLescape(item.GroupPermissions.ToString()));
  454. sql = sql.Replace("?salePrice", cheapSQLescape(item.SalePrice.ToString()));
  455. sql = sql.Replace("?saleType", cheapSQLescape(unchecked((sbyte)item.SaleType).ToString()));
  456. sql = sql.Replace("?creationDate", cheapSQLescape(item.CreationDate.ToString()));
  457. sql = sql.Replace("?groupID", cheapSQLescape(item.GroupID.ToString()));
  458. sql = sql.Replace("?groupOwned", cheapSQLescape(item.GroupOwned.ToString()));
  459. sql = sql.Replace("?flags", cheapSQLescape(item.Flags.ToString()));
  460. return sql;
  461. }
  462. private static string InventoryFolderToSql(InventoryFolderBase folder)
  463. {
  464. string sql =
  465. "REPLACE /*! INVFOLDER AT ***$SUBS$*** */ INTO inventoryfolders (folderID, agentID, parentFolderID, folderName, type, version) VALUES ";
  466. sql += "(?folderID, ?agentID, ?parentFolderID, ?folderName, ?type, ?version);\r\n";
  467. string folderName = folder.Name;
  468. sql = sql.Replace("$SUBS$", Util.UnixTimeSinceEpoch().ToString());
  469. sql = sql.Replace("?folderID", cheapSQLescape(folder.ID.ToString()));
  470. sql = sql.Replace("?agentID", cheapSQLescape(folder.Owner.ToString()));
  471. sql = sql.Replace("?parentFolderID", cheapSQLescape(folder.ParentID.ToString()));
  472. sql = sql.Replace("?folderName", cheapSQLescape(folderName));
  473. sql = sql.Replace("?type", cheapSQLescape(folder.Type.ToString()));
  474. sql = sql.Replace("?version", cheapSQLescape(folder.Version.ToString()));
  475. return sql;
  476. }
  477. private static string getRollbackFolderDate()
  478. {
  479. return DateTime.UtcNow.Year.ToString() + "-" + DateTime.UtcNow.Month.ToString() + "-" +
  480. DateTime.UtcNow.Day.ToString();
  481. }
  482. private void StoreRollbackItem(UUID ItemID)
  483. {
  484. if (rollbackStore == true)
  485. {
  486. string todaysPath = RollbackGetTodaysPath();
  487. InventoryItemBase imb = getInventoryItem(ItemID);
  488. string sql = InventoryItemToSql(imb);
  489. File.AppendAllText(Path.Combine(todaysPath, imb.Owner.ToString()), sql);
  490. }
  491. }
  492. private void StoreRollbackFolder(UUID FolderID)
  493. {
  494. if (rollbackStore == true)
  495. {
  496. string todaysPath = RollbackGetTodaysPath();
  497. InventoryFolderBase ifb = getInventoryFolder(FolderID);
  498. string sql = InventoryFolderToSql(ifb);
  499. File.AppendAllText(Path.Combine(todaysPath, ifb.Owner.ToString()), sql);
  500. }
  501. }
  502. private string RollbackGetTodaysPath()
  503. {
  504. if (!Directory.Exists(rollbackDir))
  505. Directory.CreateDirectory(rollbackDir);
  506. string todaysPath = Path.Combine(rollbackDir, getRollbackFolderDate());
  507. if (!Directory.Exists(todaysPath))
  508. Directory.CreateDirectory(todaysPath);
  509. return todaysPath;
  510. }
  511. #endregion
  512. /// <summary>
  513. /// Adds a specified item to the database
  514. /// </summary>
  515. /// <param name="item">The inventory item</param>
  516. public void addInventoryItem(InventoryItemBase item)
  517. {
  518. string sql =
  519. "REPLACE INTO inventoryitems (inventoryID, assetID, assetType, parentFolderID, avatarID, inventoryName"
  520. + ", inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType"
  521. + ", creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, inventoryGroupPermissions, salePrice, saleType"
  522. + ", creationDate, groupID, groupOwned, flags) VALUES ";
  523. sql +=
  524. "(?inventoryID, ?assetID, ?assetType, ?parentFolderID, ?avatarID, ?inventoryName, ?inventoryDescription"
  525. + ", ?inventoryNextPermissions, ?inventoryCurrentPermissions, ?invType, ?creatorID"
  526. + ", ?inventoryBasePermissions, ?inventoryEveryOnePermissions, ?inventoryGroupPermissions, ?salePrice, ?saleType, ?creationDate"
  527. + ", ?groupID, ?groupOwned, ?flags)";
  528. string itemName = item.Name;
  529. if (item.Name.Length > 64)
  530. {
  531. itemName = item.Name.Substring(0, 64);
  532. m_log.Warn("[INVENTORY DB]: Name field truncated from " + item.Name.Length + " to " + itemName.Length + " characters on add item");
  533. }
  534. string itemDesc = item.Description;
  535. if (item.Description.Length > 128)
  536. {
  537. itemDesc = item.Description.Substring(0, 128);
  538. m_log.Warn("[INVENTORY DB]: Description field truncated from " + item.Description.Length + " to " + itemDesc.Length + " characters on add item");
  539. }
  540. try
  541. {
  542. database.CheckConnection();
  543. MySqlCommand result = new MySqlCommand(sql, database.Connection);
  544. result.Parameters.AddWithValue("?inventoryID", item.ID.ToString());
  545. result.Parameters.AddWithValue("?assetID", item.AssetID.ToString());
  546. result.Parameters.AddWithValue("?assetType", item.AssetType.ToString());
  547. result.Parameters.AddWithValue("?parentFolderID", item.Folder.ToString());
  548. result.Parameters.AddWithValue("?avatarID", item.Owner.ToString());
  549. result.Parameters.AddWithValue("?inventoryName", itemName);
  550. result.Parameters.AddWithValue("?inventoryDescription", itemDesc);
  551. result.Parameters.AddWithValue("?inventoryNextPermissions", item.NextPermissions.ToString());
  552. result.Parameters.AddWithValue("?inventoryCurrentPermissions",
  553. item.CurrentPermissions.ToString());
  554. result.Parameters.AddWithValue("?invType", item.InvType);
  555. result.Parameters.AddWithValue("?creatorID", item.CreatorId);
  556. result.Parameters.AddWithValue("?inventoryBasePermissions", item.BasePermissions);
  557. result.Parameters.AddWithValue("?inventoryEveryOnePermissions", item.EveryOnePermissions);
  558. result.Parameters.AddWithValue("?inventoryGroupPermissions", item.GroupPermissions);
  559. result.Parameters.AddWithValue("?salePrice", item.SalePrice);
  560. result.Parameters.AddWithValue("?saleType", unchecked((sbyte)item.SaleType));
  561. result.Parameters.AddWithValue("?creationDate", item.CreationDate);
  562. result.Parameters.AddWithValue("?groupID", item.GroupID);
  563. result.Parameters.AddWithValue("?groupOwned", item.GroupOwned);
  564. result.Parameters.AddWithValue("?flags", item.Flags);
  565. lock (database)
  566. {
  567. result.ExecuteNonQuery();
  568. }
  569. result.Dispose();
  570. result = new MySqlCommand("update inventoryfolders set version=version+1 where folderID = ?folderID", database.Connection);
  571. result.Parameters.AddWithValue("?folderID", item.Folder.ToString
  572. ());
  573. lock (database)
  574. {
  575. result.ExecuteNonQuery();
  576. }
  577. result.Dispose();
  578. }
  579. catch (MySqlException e)
  580. {
  581. m_log.Error(e.ToString());
  582. }
  583. }
  584. /// <summary>
  585. /// Updates the specified inventory item
  586. /// </summary>
  587. /// <param name="item">Inventory item to update</param>
  588. public void updateInventoryItem(InventoryItemBase item)
  589. {
  590. StoreRollbackItem(item.ID);
  591. addInventoryItem(item);
  592. }
  593. /// <summary>
  594. /// Detele the specified inventory item
  595. /// </summary>
  596. /// <param name="item">The inventory item UUID to delete</param>
  597. public void deleteInventoryItem(UUID itemID)
  598. {
  599. StoreRollbackItem(itemID);
  600. try
  601. {
  602. database.CheckConnection();
  603. MySqlCommand cmd =
  604. new MySqlCommand("DELETE FROM inventoryitems WHERE inventoryID=?uuid", database.Connection);
  605. cmd.Parameters.AddWithValue("?uuid", itemID.ToString());
  606. lock (database)
  607. {
  608. cmd.ExecuteNonQuery();
  609. }
  610. }
  611. catch (MySqlException e)
  612. {
  613. database.Reconnect();
  614. m_log.Error(e.ToString());
  615. }
  616. }
  617. public InventoryItemBase queryInventoryItem(UUID itemID)
  618. {
  619. return getInventoryItem(itemID);
  620. }
  621. public InventoryFolderBase queryInventoryFolder(UUID folderID)
  622. {
  623. return getInventoryFolder(folderID);
  624. }
  625. /// <summary>
  626. /// Creates a new inventory folder
  627. /// </summary>
  628. /// <param name="folder">Folder to create</param>
  629. public void addInventoryFolder(InventoryFolderBase folder)
  630. {
  631. string sql =
  632. "REPLACE INTO inventoryfolders (folderID, agentID, parentFolderID, folderName, type, version) VALUES ";
  633. sql += "(?folderID, ?agentID, ?parentFolderID, ?folderName, ?type, ?version)";
  634. string folderName = folder.Name;
  635. if (folderName.Length > 64)
  636. {
  637. folderName = folderName.Substring(0, 64);
  638. m_log.Warn("[INVENTORY DB]: Name field truncated from " + folder.Name.Length + " to " + folderName.Length + " characters on add folder");
  639. }
  640. database.CheckConnection();
  641. MySqlCommand cmd = new MySqlCommand(sql, database.Connection);
  642. cmd.Parameters.AddWithValue("?folderID", folder.ID.ToString());
  643. cmd.Parameters.AddWithValue("?agentID", folder.Owner.ToString());
  644. cmd.Parameters.AddWithValue("?parentFolderID", folder.ParentID.ToString());
  645. cmd.Parameters.AddWithValue("?folderName", folderName);
  646. cmd.Parameters.AddWithValue("?type", folder.Type);
  647. cmd.Parameters.AddWithValue("?version", folder.Version);
  648. try
  649. {
  650. lock (database)
  651. {
  652. cmd.ExecuteNonQuery();
  653. }
  654. }
  655. catch (Exception e)
  656. {
  657. m_log.Error(e.ToString());
  658. }
  659. }
  660. /// <summary>
  661. /// Updates an inventory folder
  662. /// </summary>
  663. /// <param name="folder">Folder to update</param>
  664. public void updateInventoryFolder(InventoryFolderBase folder)
  665. {
  666. StoreRollbackFolder(folder.ID);
  667. addInventoryFolder(folder);
  668. }
  669. /// <summary>
  670. /// Move an inventory folder
  671. /// </summary>
  672. /// <param name="folder">Folder to move</param>
  673. /// <remarks>UPDATE inventoryfolders SET parentFolderID=?parentFolderID WHERE folderID=?folderID</remarks>
  674. public void moveInventoryFolder(InventoryFolderBase folder)
  675. {
  676. StoreRollbackFolder(folder.ID);
  677. string sql =
  678. "UPDATE inventoryfolders SET parentFolderID=?parentFolderID WHERE folderID=?folderID";
  679. database.CheckConnection();
  680. MySqlCommand cmd = new MySqlCommand(sql, database.Connection);
  681. cmd.Parameters.AddWithValue("?folderID", folder.ID.ToString());
  682. cmd.Parameters.AddWithValue("?parentFolderID", folder.ParentID.ToString());
  683. try
  684. {
  685. lock (database)
  686. {
  687. cmd.ExecuteNonQuery();
  688. }
  689. }
  690. catch (Exception e)
  691. {
  692. m_log.Error(e.ToString());
  693. }
  694. }
  695. /// <summary>
  696. /// Append a list of all the child folders of a parent folder
  697. /// </summary>
  698. /// <param name="folders">list where folders will be appended</param>
  699. /// <param name="parentID">ID of parent</param>
  700. protected void getInventoryFolders(ref List<InventoryFolderBase> folders, UUID parentID)
  701. {
  702. List<InventoryFolderBase> subfolderList = getInventoryFolders(parentID);
  703. foreach (InventoryFolderBase f in subfolderList)
  704. folders.Add(f);
  705. }
  706. /// <summary>
  707. /// See IInventoryDataPlugin
  708. /// </summary>
  709. /// <param name="parentID"></param>
  710. /// <returns></returns>
  711. public List<InventoryFolderBase> getFolderHierarchy(UUID parentID)
  712. {
  713. /* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one
  714. * - We will only need to hit the database twice instead of n times.
  715. * - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned
  716. * by the same person, each user only has 1 inventory heirarchy
  717. * - The returned list is not ordered, instead of breadth-first ordered
  718. There are basically 2 usage cases for getFolderHeirarchy:
  719. 1) Getting the user's entire inventory heirarchy when they log in
  720. 2) Finding a subfolder heirarchy to delete when emptying the trash.
  721. This implementation will pull all inventory folders from the database, and then prune away any folder that
  722. is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the
  723. database than to make n requests. This pays off only if requested heirarchy is large.
  724. By making this choice, we are making the worst case better at the cost of making the best case worse.
  725. This way is generally better because we don't have to rebuild the connection/sql query per subfolder,
  726. even if we end up getting more data from the SQL server than we need.
  727. - Francis
  728. */
  729. try
  730. {
  731. List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
  732. Dictionary<UUID, List<InventoryFolderBase>> hashtable
  733. = new Dictionary<UUID, List<InventoryFolderBase>>(); ;
  734. List<InventoryFolderBase> parentFolder = new List<InventoryFolderBase>();
  735. lock (database)
  736. {
  737. MySqlCommand result;
  738. MySqlDataReader reader;
  739. bool buildResultsFromHashTable = false;
  740. database.CheckConnection();
  741. /* Fetch the parent folder from the database to determine the agent ID, and if
  742. * we're querying the root of the inventory folder tree */
  743. result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid",
  744. database.Connection);
  745. result.Parameters.AddWithValue("?uuid", parentID.ToString());
  746. reader = result.ExecuteReader();
  747. while (reader.Read()) // Should be at most 1 result
  748. parentFolder.Add(readInventoryFolder(reader));
  749. reader.Close();
  750. result.Dispose();
  751. if (parentFolder.Count >= 1) // No result means parent folder does not exist
  752. {
  753. if (parentFolder[0].ParentID == UUID.Zero) // We are querying the root folder
  754. {
  755. /* Get all of the agent's folders from the database, put them in a list and return it */
  756. result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid",
  757. database.Connection);
  758. result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
  759. reader = result.ExecuteReader();
  760. while (reader.Read())
  761. {
  762. InventoryFolderBase curFolder = readInventoryFolder(reader);
  763. if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list
  764. folders.Add(curFolder);
  765. }
  766. reader.Close();
  767. result.Dispose();
  768. } // if we are querying the root folder
  769. else // else we are querying a subtree of the inventory folder tree
  770. {
  771. /* Get all of the agent's folders from the database, put them all in a hash table
  772. * indexed by their parent ID */
  773. result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid",
  774. database.Connection);
  775. result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
  776. reader = result.ExecuteReader();
  777. while (reader.Read())
  778. {
  779. InventoryFolderBase curFolder = readInventoryFolder(reader);
  780. if (hashtable.ContainsKey(curFolder.ParentID)) // Current folder already has a sibling
  781. hashtable[curFolder.ParentID].Add(curFolder); // append to sibling list
  782. else // else current folder has no known (yet) siblings
  783. {
  784. List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>();
  785. siblingList.Add(curFolder);
  786. // Current folder has no known (yet) siblings
  787. hashtable.Add(curFolder.ParentID, siblingList);
  788. }
  789. } // while more items to read from the database
  790. reader.Close();
  791. result.Dispose();
  792. // Set flag so we know we need to build the results from the hash table after
  793. // we unlock the database
  794. buildResultsFromHashTable = true;
  795. } // else we are querying a subtree of the inventory folder tree
  796. } // if folder parentID exists
  797. if (buildResultsFromHashTable)
  798. {
  799. /* We have all of the user's folders stored in a hash table indexed by their parent ID
  800. * and we need to return the requested subtree. We will build the requested subtree
  801. * by performing a breadth-first-search on the hash table */
  802. if (hashtable.ContainsKey(parentID))
  803. folders.AddRange(hashtable[parentID]);
  804. for (int i = 0; i < folders.Count; i++) // **Note: folders.Count is *not* static
  805. if (hashtable.ContainsKey(folders[i].ID))
  806. folders.AddRange(hashtable[folders[i].ID]);
  807. }
  808. } // lock (database)
  809. return folders;
  810. }
  811. catch (Exception e)
  812. {
  813. database.Reconnect();
  814. m_log.Error(e.ToString());
  815. return null;
  816. }
  817. }
  818. /// <summary>
  819. /// Delete a folder from database
  820. /// </summary>
  821. /// <param name="folderID">the folder UUID</param>
  822. protected void deleteOneFolder(UUID folderID)
  823. {
  824. StoreRollbackFolder(folderID);
  825. try
  826. {
  827. database.CheckConnection();
  828. MySqlCommand cmd =
  829. new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection);
  830. cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
  831. lock (database)
  832. {
  833. cmd.ExecuteNonQuery();
  834. }
  835. }
  836. catch (MySqlException e)
  837. {
  838. database.Reconnect();
  839. m_log.Error(e.ToString());
  840. }
  841. }
  842. /// <summary>
  843. /// Delete all item in a folder
  844. /// </summary>
  845. /// <param name="folderID">the folder UUID</param>
  846. protected void deleteItemsInFolder(UUID folderID)
  847. {
  848. if (rollbackStore)
  849. {
  850. foreach (InventoryItemBase itemBase in getInventoryInFolder(folderID))
  851. {
  852. StoreRollbackItem(itemBase.ID);
  853. }
  854. }
  855. try
  856. {
  857. database.CheckConnection();
  858. MySqlCommand cmd =
  859. new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection);
  860. cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
  861. lock (database)
  862. {
  863. cmd.ExecuteNonQuery();
  864. }
  865. }
  866. catch (MySqlException e)
  867. {
  868. database.Reconnect();
  869. m_log.Error(e.ToString());
  870. }
  871. }
  872. /// <summary>
  873. /// Deletes an inventory folder
  874. /// </summary>
  875. /// <param name="folderId">Id of folder to delete</param>
  876. public void deleteInventoryFolder(UUID folderID)
  877. {
  878. List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID);
  879. // Dont delete in OGM - makes for easier restores if someone sends a malcious command. (just restore the folder entry)
  880. if (opengridmode == false)
  881. {
  882. //Delete all sub-folders
  883. foreach (InventoryFolderBase f in subFolders)
  884. {
  885. StoreRollbackFolder(f.ID);
  886. deleteOneFolder(f.ID);
  887. if (rollbackStore)
  888. {
  889. foreach (InventoryItemBase itemBase in getInventoryInFolder(f.ID))
  890. {
  891. StoreRollbackItem(itemBase.ID);
  892. }
  893. }
  894. deleteItemsInFolder(f.ID);
  895. }
  896. }
  897. StoreRollbackFolder(folderID);
  898. //Delete the actual row
  899. deleteOneFolder(folderID);
  900. // Just delete the folder context in OGM
  901. if (opengridmode == false)
  902. {
  903. if (rollbackStore)
  904. {
  905. foreach (InventoryItemBase itemBase in getInventoryInFolder(folderID))
  906. {
  907. StoreRollbackItem(itemBase.ID);
  908. }
  909. }
  910. deleteItemsInFolder(folderID);
  911. }
  912. }
  913. public List<InventoryItemBase> fetchActiveGestures(UUID avatarID)
  914. {
  915. MySqlDataReader result = null;
  916. MySqlCommand sqlCmd = null;
  917. lock (database)
  918. {
  919. try
  920. {
  921. database.CheckConnection();
  922. sqlCmd = new MySqlCommand(
  923. "SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags = 1",
  924. database.Connection);
  925. sqlCmd.Parameters.AddWithValue("?uuid", avatarID.ToString());
  926. sqlCmd.Parameters.AddWithValue("?type", (int)AssetType.Gesture);
  927. result = sqlCmd.ExecuteReader();
  928. List<InventoryItemBase> list = new List<InventoryItemBase>();
  929. while (result.Read())
  930. {
  931. InventoryItemBase item = readInventoryItem(result);
  932. if (item != null)
  933. list.Add(item);
  934. }
  935. return list;
  936. }
  937. catch (Exception e)
  938. {
  939. database.Reconnect();
  940. m_log.Error(e.ToString());
  941. return null;
  942. }
  943. finally
  944. {
  945. if (result != null) result.Close();
  946. if (sqlCmd != null) sqlCmd.Dispose();
  947. }
  948. }
  949. }
  950. }
  951. }