MySQLUserData.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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 OpenSim 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.Generic;
  29. using System.Data;
  30. using System.Reflection;
  31. using System.Text.RegularExpressions;
  32. using libsecondlife;
  33. using log4net;
  34. using OpenSim.Framework;
  35. namespace OpenSim.Data.MySQL
  36. {
  37. /// <summary>
  38. /// A database interface class to a user profile storage system
  39. /// </summary>
  40. internal class MySQLUserData : UserDataBase
  41. {
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. /// <summary>
  44. /// Database manager for MySQL
  45. /// </summary>
  46. public MySQLManager database;
  47. private string m_agentsTableName;
  48. private string m_usersTableName;
  49. private string m_userFriendsTableName;
  50. /// <summary>
  51. /// Loads and initialises the MySQL storage plugin
  52. /// </summary>
  53. override public void Initialise()
  54. {
  55. // Load from an INI file connection details
  56. // TODO: move this to XML? Yes, PLEASE!
  57. IniFile iniFile = new IniFile("mysql_connection.ini");
  58. string settingHostname = iniFile.ParseFileReadValue("hostname");
  59. string settingDatabase = iniFile.ParseFileReadValue("database");
  60. string settingUsername = iniFile.ParseFileReadValue("username");
  61. string settingPassword = iniFile.ParseFileReadValue("password");
  62. string settingPooling = iniFile.ParseFileReadValue("pooling");
  63. string settingPort = iniFile.ParseFileReadValue("port");
  64. m_usersTableName = iniFile.ParseFileReadValue("userstablename");
  65. if( m_usersTableName == null )
  66. {
  67. m_usersTableName = "users";
  68. }
  69. m_userFriendsTableName = iniFile.ParseFileReadValue("userfriendstablename");
  70. if (m_userFriendsTableName == null)
  71. {
  72. m_userFriendsTableName = "userfriends";
  73. }
  74. m_agentsTableName = iniFile.ParseFileReadValue("agentstablename");
  75. if (m_agentsTableName == null)
  76. {
  77. m_agentsTableName = "agents";
  78. }
  79. database =
  80. new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling,
  81. settingPort);
  82. TestTables();
  83. }
  84. #region Test and initialization code
  85. /// <summary>
  86. /// Ensure that the user related tables exists and are at the latest version
  87. /// </summary>
  88. private void TestTables()
  89. {
  90. Dictionary<string, string> tableList = new Dictionary<string, string>();
  91. tableList[m_agentsTableName] = null;
  92. tableList[m_usersTableName] = null;
  93. tableList[m_userFriendsTableName] = null;
  94. database.GetTableVersion(tableList);
  95. UpgradeAgentsTable(tableList[m_agentsTableName]);
  96. UpgradeUsersTable(tableList[m_usersTableName]);
  97. UpgradeFriendsTable(tableList[m_userFriendsTableName]);
  98. }
  99. /// <summary>
  100. /// Create or upgrade the table if necessary
  101. /// </summary>
  102. /// <param name="oldVersion">A null indicates that the table does not
  103. /// currently exist</param>
  104. private void UpgradeAgentsTable(string oldVersion)
  105. {
  106. // null as the version, indicates that the table didn't exist
  107. if (oldVersion == null)
  108. {
  109. database.ExecuteResourceSql("CreateAgentsTable.sql");
  110. return;
  111. }
  112. }
  113. /// <summary>
  114. /// Create or upgrade the table if necessary
  115. /// </summary>
  116. /// <param name="oldVersion">A null indicates that the table does not
  117. /// currently exist</param>
  118. private void UpgradeUsersTable(string oldVersion)
  119. {
  120. // null as the version, indicates that the table didn't exist
  121. if (oldVersion == null)
  122. {
  123. database.ExecuteResourceSql("CreateUsersTable.sql");
  124. return;
  125. }
  126. else if (oldVersion.Contains("Rev. 1"))
  127. {
  128. database.ExecuteResourceSql("UpgradeUsersTableToVersion2.sql");
  129. return;
  130. }
  131. //m_log.Info("[DB]: DBVers:" + oldVersion);
  132. }
  133. /// <summary>
  134. /// Create or upgrade the table if necessary
  135. /// </summary>
  136. /// <param name="oldVersion">A null indicates that the table does not
  137. /// currently exist</param>
  138. private void UpgradeFriendsTable(string oldVersion)
  139. {
  140. // null as the version, indicates that the table didn't exist
  141. if (oldVersion == null)
  142. {
  143. database.ExecuteResourceSql("CreateUserFriendsTable.sql");
  144. return;
  145. }
  146. }
  147. #endregion
  148. // see IUserData
  149. override public UserProfileData GetUserByName(string user, string last)
  150. {
  151. try
  152. {
  153. lock (database)
  154. {
  155. Dictionary<string, string> param = new Dictionary<string, string>();
  156. param["?first"] = user;
  157. param["?second"] = last;
  158. IDbCommand result =
  159. database.Query("SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param);
  160. IDataReader reader = result.ExecuteReader();
  161. UserProfileData row = database.readUserRow(reader);
  162. reader.Close();
  163. result.Dispose();
  164. return row;
  165. }
  166. }
  167. catch (Exception e)
  168. {
  169. database.Reconnect();
  170. m_log.Error(e.ToString());
  171. return null;
  172. }
  173. }
  174. #region User Friends List Data
  175. override public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms)
  176. {
  177. int dtvalue = Util.UnixTimeSinceEpoch();
  178. Dictionary<string, string> param = new Dictionary<string, string>();
  179. param["?ownerID"] = friendlistowner.UUID.ToString();
  180. param["?friendID"] = friend.UUID.ToString();
  181. param["?friendPerms"] = perms.ToString();
  182. param["?datetimestamp"] = dtvalue.ToString();
  183. try
  184. {
  185. lock (database)
  186. {
  187. IDbCommand adder =
  188. database.Query(
  189. "INSERT INTO `" + m_userFriendsTableName + "` " +
  190. "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
  191. "VALUES " +
  192. "(?ownerID,?friendID,?friendPerms,?datetimestamp)",
  193. param);
  194. adder.ExecuteNonQuery();
  195. adder =
  196. database.Query(
  197. "INSERT INTO `" + m_userFriendsTableName + "` " +
  198. "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
  199. "VALUES " +
  200. "(?friendID,?ownerID,?friendPerms,?datetimestamp)",
  201. param);
  202. adder.ExecuteNonQuery();
  203. }
  204. }
  205. catch (Exception e)
  206. {
  207. database.Reconnect();
  208. m_log.Error(e.ToString());
  209. return;
  210. }
  211. }
  212. override public void RemoveUserFriend(LLUUID friendlistowner, LLUUID friend)
  213. {
  214. Dictionary<string, string> param = new Dictionary<string, string>();
  215. param["?ownerID"] = friendlistowner.UUID.ToString();
  216. param["?friendID"] = friend.UUID.ToString();
  217. try
  218. {
  219. lock (database)
  220. {
  221. IDbCommand updater =
  222. database.Query(
  223. "delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID",
  224. param);
  225. updater.ExecuteNonQuery();
  226. updater =
  227. database.Query(
  228. "delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID",
  229. param);
  230. updater.ExecuteNonQuery();
  231. }
  232. }
  233. catch (Exception e)
  234. {
  235. database.Reconnect();
  236. m_log.Error(e.ToString());
  237. return;
  238. }
  239. }
  240. override public void UpdateUserFriendPerms(LLUUID friendlistowner, LLUUID friend, uint perms)
  241. {
  242. Dictionary<string, string> param = new Dictionary<string, string>();
  243. param["?ownerID"] = friendlistowner.UUID.ToString();
  244. param["?friendID"] = friend.UUID.ToString();
  245. param["?friendPerms"] = perms.ToString();
  246. try
  247. {
  248. lock (database)
  249. {
  250. IDbCommand updater =
  251. database.Query(
  252. "update " + m_userFriendsTableName +
  253. " SET friendPerms = ?friendPerms " +
  254. "where ownerID = ?ownerID and friendID = ?friendID",
  255. param);
  256. updater.ExecuteNonQuery();
  257. }
  258. }
  259. catch (Exception e)
  260. {
  261. database.Reconnect();
  262. m_log.Error(e.ToString());
  263. return;
  264. }
  265. }
  266. override public List<FriendListItem> GetUserFriendList(LLUUID friendlistowner)
  267. {
  268. List<FriendListItem> Lfli = new List<FriendListItem>();
  269. Dictionary<string, string> param = new Dictionary<string, string>();
  270. param["?ownerID"] = friendlistowner.UUID.ToString();
  271. try
  272. {
  273. lock (database)
  274. {
  275. //Left Join userfriends to itself
  276. IDbCommand result =
  277. database.Query(
  278. "select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " + m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" +
  279. " where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID",
  280. param);
  281. IDataReader reader = result.ExecuteReader();
  282. while (reader.Read())
  283. {
  284. FriendListItem fli = new FriendListItem();
  285. fli.FriendListOwner = new LLUUID((string)reader["ownerID"]);
  286. fli.Friend = new LLUUID((string)reader["friendID"]);
  287. fli.FriendPerms = (uint)Convert.ToInt32(reader["friendPerms"]);
  288. // This is not a real column in the database table, it's a joined column from the opposite record
  289. fli.FriendListOwnerPerms = (uint)Convert.ToInt32(reader["ownerperms"]);
  290. Lfli.Add(fli);
  291. }
  292. reader.Close();
  293. result.Dispose();
  294. }
  295. }
  296. catch (Exception e)
  297. {
  298. database.Reconnect();
  299. m_log.Error(e.ToString());
  300. return Lfli;
  301. }
  302. return Lfli;
  303. }
  304. #endregion
  305. override public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid)
  306. {
  307. m_log.Info("[USER DB]: Stub UpdateUserCUrrentRegion called");
  308. }
  309. override public List<AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query)
  310. {
  311. List<AvatarPickerAvatar> returnlist = new List<AvatarPickerAvatar>();
  312. Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
  313. string[] querysplit;
  314. querysplit = query.Split(' ');
  315. if (querysplit.Length == 2)
  316. {
  317. Dictionary<string, string> param = new Dictionary<string, string>();
  318. param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%";
  319. param["?second"] = objAlphaNumericPattern.Replace(querysplit[1], String.Empty) + "%";
  320. try
  321. {
  322. lock (database)
  323. {
  324. IDbCommand result =
  325. database.Query(
  326. "SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username like ?first AND lastname like ?second LIMIT 100",
  327. param);
  328. IDataReader reader = result.ExecuteReader();
  329. while (reader.Read())
  330. {
  331. AvatarPickerAvatar user = new AvatarPickerAvatar();
  332. user.AvatarID = new LLUUID((string) reader["UUID"]);
  333. user.firstName = (string) reader["username"];
  334. user.lastName = (string) reader["lastname"];
  335. returnlist.Add(user);
  336. }
  337. reader.Close();
  338. result.Dispose();
  339. }
  340. }
  341. catch (Exception e)
  342. {
  343. database.Reconnect();
  344. m_log.Error(e.ToString());
  345. return returnlist;
  346. }
  347. }
  348. else if (querysplit.Length == 1)
  349. {
  350. try
  351. {
  352. lock (database)
  353. {
  354. Dictionary<string, string> param = new Dictionary<string, string>();
  355. param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%";
  356. IDbCommand result =
  357. database.Query(
  358. "SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username like ?first OR lastname like ?first LIMIT 100",
  359. param);
  360. IDataReader reader = result.ExecuteReader();
  361. while (reader.Read())
  362. {
  363. AvatarPickerAvatar user = new AvatarPickerAvatar();
  364. user.AvatarID = new LLUUID((string) reader["UUID"]);
  365. user.firstName = (string) reader["username"];
  366. user.lastName = (string) reader["lastname"];
  367. returnlist.Add(user);
  368. }
  369. reader.Close();
  370. result.Dispose();
  371. }
  372. }
  373. catch (Exception e)
  374. {
  375. database.Reconnect();
  376. m_log.Error(e.ToString());
  377. return returnlist;
  378. }
  379. }
  380. return returnlist;
  381. }
  382. // see IUserData
  383. override public UserProfileData GetUserByUUID(LLUUID uuid)
  384. {
  385. try
  386. {
  387. lock (database)
  388. {
  389. Dictionary<string, string> param = new Dictionary<string, string>();
  390. param["?uuid"] = uuid.ToString();
  391. IDbCommand result = database.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param);
  392. IDataReader reader = result.ExecuteReader();
  393. UserProfileData row = database.readUserRow(reader);
  394. reader.Close();
  395. result.Dispose();
  396. return row;
  397. }
  398. }
  399. catch (Exception e)
  400. {
  401. database.Reconnect();
  402. m_log.Error(e.ToString());
  403. return null;
  404. }
  405. }
  406. /// <summary>
  407. /// Returns a user session searching by name
  408. /// </summary>
  409. /// <param name="name">The account name</param>
  410. /// <returns>The users session</returns>
  411. override public UserAgentData GetAgentByName(string name)
  412. {
  413. return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]);
  414. }
  415. /// <summary>
  416. /// Returns a user session by account name
  417. /// </summary>
  418. /// <param name="user">First part of the users account name</param>
  419. /// <param name="last">Second part of the users account name</param>
  420. /// <returns>The users session</returns>
  421. override public UserAgentData GetAgentByName(string user, string last)
  422. {
  423. UserProfileData profile = GetUserByName(user, last);
  424. return GetAgentByUUID(profile.ID);
  425. }
  426. override public void StoreWebLoginKey(LLUUID AgentID, LLUUID WebLoginKey)
  427. {
  428. Dictionary<string, string> param = new Dictionary<string, string>();
  429. param["?UUID"] = AgentID.UUID.ToString();
  430. param["?webLoginKey"] = WebLoginKey.UUID.ToString();
  431. try
  432. {
  433. lock (database)
  434. {
  435. IDbCommand updater =
  436. database.Query(
  437. "update " + m_usersTableName + " SET webLoginKey = ?webLoginKey " +
  438. "where UUID = ?UUID",
  439. param);
  440. updater.ExecuteNonQuery();
  441. }
  442. }
  443. catch (Exception e)
  444. {
  445. database.Reconnect();
  446. m_log.Error(e.ToString());
  447. return;
  448. }
  449. }
  450. /// <summary>
  451. /// Returns an agent session by account UUID
  452. /// </summary>
  453. /// <param name="uuid">The accounts UUID</param>
  454. /// <returns>The users session</returns>
  455. override public UserAgentData GetAgentByUUID(LLUUID uuid)
  456. {
  457. try
  458. {
  459. lock (database)
  460. {
  461. Dictionary<string, string> param = new Dictionary<string, string>();
  462. param["?uuid"] = uuid.ToString();
  463. IDbCommand result = database.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid", param);
  464. IDataReader reader = result.ExecuteReader();
  465. UserAgentData row = database.readAgentRow(reader);
  466. reader.Close();
  467. result.Dispose();
  468. return row;
  469. }
  470. }
  471. catch (Exception e)
  472. {
  473. database.Reconnect();
  474. m_log.Error(e.ToString());
  475. return null;
  476. }
  477. }
  478. /// <summary>
  479. /// Creates a new users profile
  480. /// </summary>
  481. /// <param name="user">The user profile to create</param>
  482. override public void AddNewUserProfile(UserProfileData user)
  483. {
  484. try
  485. {
  486. lock (database)
  487. {
  488. database.insertUserRow(user.ID, user.FirstName, user.SurName, user.PasswordHash, user.PasswordSalt,
  489. user.HomeRegion, user.HomeLocation.X, user.HomeLocation.Y,
  490. user.HomeLocation.Z,
  491. user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created,
  492. user.LastLogin, user.UserInventoryURI, user.UserAssetURI,
  493. user.CanDoMask, user.WantDoMask,
  494. user.AboutText, user.FirstLifeAboutText, user.Image,
  495. user.FirstLifeImage, user.WebLoginKey);
  496. }
  497. }
  498. catch (Exception e)
  499. {
  500. database.Reconnect();
  501. m_log.Error(e.ToString());
  502. }
  503. }
  504. /// <summary>
  505. /// Creates a new agent
  506. /// </summary>
  507. /// <param name="agent">The agent to create</param>
  508. override public void AddNewUserAgent(UserAgentData agent)
  509. {
  510. try
  511. {
  512. lock (database)
  513. {
  514. database.insertAgentRow(agent);
  515. }
  516. }
  517. catch (Exception e)
  518. {
  519. database.Reconnect();
  520. m_log.Error(e.ToString());
  521. }
  522. }
  523. /// <summary>
  524. /// Updates a user profile stored in the DB
  525. /// </summary>
  526. /// <param name="user">The profile data to use to update the DB</param>
  527. override public bool UpdateUserProfile(UserProfileData user)
  528. {
  529. lock (database)
  530. {
  531. database.updateUserRow(user.ID, user.FirstName, user.SurName, user.PasswordHash, user.PasswordSalt,
  532. user.HomeRegion, user.HomeLocation.X, user.HomeLocation.Y, user.HomeLocation.Z, user.HomeLookAt.X,
  533. user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin, user.UserInventoryURI,
  534. user.UserAssetURI, user.CanDoMask, user.WantDoMask, user.AboutText,
  535. user.FirstLifeAboutText, user.Image, user.FirstLifeImage, user.WebLoginKey);
  536. }
  537. return true;
  538. }
  539. /// <summary>
  540. /// Performs a money transfer request between two accounts
  541. /// </summary>
  542. /// <param name="from">The senders account ID</param>
  543. /// <param name="to">The receivers account ID</param>
  544. /// <param name="amount">The amount to transfer</param>
  545. /// <returns>Success?</returns>
  546. override public bool MoneyTransferRequest(LLUUID from, LLUUID to, uint amount)
  547. {
  548. return false;
  549. }
  550. /// <summary>
  551. /// Performs an inventory transfer request between two accounts
  552. /// </summary>
  553. /// <remarks>TODO: Move to inventory server</remarks>
  554. /// <param name="from">The senders account ID</param>
  555. /// <param name="to">The receivers account ID</param>
  556. /// <param name="item">The item to transfer</param>
  557. /// <returns>Success?</returns>
  558. override public bool InventoryTransferRequest(LLUUID from, LLUUID to, LLUUID item)
  559. {
  560. return false;
  561. }
  562. /// <summary>
  563. /// Database provider name
  564. /// </summary>
  565. /// <returns>Provider name</returns>
  566. override public string getName()
  567. {
  568. return "MySQL Userdata Interface";
  569. }
  570. /// <summary>
  571. /// Database provider version
  572. /// </summary>
  573. /// <returns>provider version</returns>
  574. override public string GetVersion()
  575. {
  576. return "0.1";
  577. }
  578. }
  579. }