MySQLInventoryData.cs 45 KB

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