MySQLUserData.cs 24 KB

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