Advertisement
IARI

Untitled

Jan 23rd, 2017
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.74 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5.  
  6. public class DatabaseController : MonoBehaviour {
  7.     // Make sure your data base contains:
  8.     // A table named "participants"
  9.     // A variable named participantID which is INT and AUTO_INCREMENT and PRIMARY_KEY
  10.  
  11.     /*
  12.     Here is how to setup the database
  13.    
  14.     Local Test with xampp server:
  15.     1. Set the DatabaseURL = localhost/experiments/emp
  16.     2. Change the cariables in the connect.php script
  17.     3. Move the php files (connect.php etc) to the folder C://xampp/htaccess/experiments/emp
  18.  
  19.     Online:
  20.     1. Set the DatabaseURL = www.janajarecki.de/experiments/
  21.     2. Change the cariables in the connect.php script
  22.     3. Upload the php files (connect.php etc) to the location www.janajarecki.de/experiments
  23.  
  24.     */
  25.  
  26.     public struct Payload {
  27.         public string tablename;
  28.         public string columnname;
  29.         public string data;
  30.         public string datatype;
  31.         public string id;
  32.         public string hash {
  33.             get {
  34.                 return Md5Sum(tablename + columnname + data + datatype + Globals.ParticipantID);
  35.             }
  36.         }
  37.         public string json() {
  38.             get {
  39.                 return "";
  40.             }
  41.         }
  42.        
  43.     }
  44.  
  45.     public bool DebugMode = false;
  46.     public bool DontSave = false;
  47.     public bool TestParticipant = false;
  48.     public string DatabaseURL; // this is the folder/url in the on the server where PHP scripts are
  49.     public List<string> TableNames;
  50.     private bool _paymentTable = true;
  51.     private Queue<Payload> queries = new Queue<>();
  52.  
  53.     // Make the tables in the data base and initialize the participants db
  54.     void Awake()
  55.     {
  56.         if(!DontSave)
  57.         {
  58.             StartCoroutine(CreateTablesPhp(TableNames));
  59.             StartCoroutine(InitializeParticipantPhp());
  60.         }
  61.     }
  62.  
  63.     // This creates tables (if they do not exist already)
  64.     // It always creates a table named `participants` with variables participantID, deviceID
  65.     private IEnumerator CreateTablesPhp(List<string> tablenames)
  66.     {
  67.         // by default we will add a participants table as the first table
  68.         tablenames.Insert(0, "participants");
  69.         // if we pay participants we will a payment table
  70.         if (_paymentTable) tablenames.Add("payment");
  71.  
  72.         // loop throught table names and create them one by one
  73.         foreach(string tablename in tablenames)
  74.         {
  75.             // create a new www form to post things into the DB
  76.             WWWForm form = new WWWForm();
  77.             form.AddField("tablename", tablename);
  78.             var url = DatabaseURL +"CreateTables.php?";
  79.             WWW webRequest = new WWW(url, form);
  80.             yield return webRequest;
  81.  
  82.             if (DebugMode)
  83.             {
  84.                 Debug.Log(webRequest.text +"(in CreateTablesPhp)");
  85.             }      
  86.  
  87.             // check for errors
  88.             if (webRequest.error != null)
  89.             {
  90.                 Debug.Log("WWW Error when trying to create tables: " +webRequest.error);
  91.             }
  92.         }
  93.     }
  94.  
  95.     // This initializes the participant
  96.     public IEnumerator InitializeParticipantPhp()
  97.     {
  98.        
  99.         if (TestParticipant)
  100.         {
  101.             WWW testWebRequest = new WWW(DatabaseURL +"DeleteTestParticipant.php?");
  102.             yield return testWebRequest;
  103.             if (DebugMode)
  104.             {
  105.                 Debug.Log("Deleted Test Participant: " +testWebRequest.text);
  106.             }
  107.  
  108.             if (testWebRequest.error != null)
  109.             {
  110.                 Debug.Log("Error (Database.Controller, testWebRequest): "+ testWebRequest.error);
  111.             }
  112.         }
  113.  
  114.         // store the real input to prevent user generated fake input
  115.         string hash = Md5Sum(SystemInfo.deviceUniqueIdentifier);
  116.  
  117.         // create a new www form to post things into the DB
  118.         WWWForm form = new WWWForm();
  119.         form.AddField("deviceId", SystemInfo.deviceUniqueIdentifier);
  120.         form.AddField("hash", hash);
  121.  
  122.         // locate the php file that saves our device ID and retrieves the unique ID
  123.         var url = DatabaseURL +"InitializeParticipant.php?";
  124.         WWW webRequest = new WWW(url, form);
  125.         yield return webRequest;
  126.  
  127.         // check for errors
  128.         if (webRequest.error != null)
  129.         {
  130.             Debug.Log("WWW Error when trying to save the device and get the ID in the data base: "+ webRequest.error);
  131.         }
  132.         else
  133.         {
  134.             Globals.ParticipantID = webRequest.text;
  135.  
  136.             if (DebugMode)
  137.             {
  138.                 Debug.Log("Initialized participant: " +webRequest.text);
  139.             }
  140.         }
  141.     }
  142.  
  143.  
  144.     // Save data to the data base
  145.     public void Save(object data, string tablename, string columnname, string datatype, bool multipleTrials)
  146.     {
  147.         if (!DontSave)
  148.         {          
  149.             StartCoroutine(SavePhp(data, tablename, columnname, datatype, multipleTrials));
  150.         }
  151.  
  152.         if(DebugMode)
  153.         {
  154.             Debug.Log("Data: " +data);
  155.         }
  156.     }
  157.  
  158.     // This function stores new values into the existing columns of our mysql data base
  159.     private IEnumerator SavePhp(object data, string tablename, string columnname, string datatype, bool multipleTrials)
  160.     {
  161.         // check if participant id was assigned
  162.         if (Globals.ParticipantID == null)
  163.         {
  164.             Debug.Log("ERROR: Globals.ParticipantId is not defined yet. You must move a script using .Save() to the next game object. (in SavePhp)");
  165.         }
  166.  
  167.         // store the real input to prevent user generated fake input
  168.         string hash = Md5Sum(tablename + columnname + data + datatype + Globals.ParticipantID);
  169.  
  170.         // create a new www form to post things into the DB
  171.         WWWForm form = new WWWForm();
  172.         form.AddField("tablename", tablename);
  173.         form.AddField("columnname", columnname);
  174.         form.AddField("data", data.ToString());
  175.         form.AddField("datatype", datatype);
  176.         form.AddField("id", Globals.ParticipantID);
  177.         form.AddField("hash", hash);
  178.  
  179.         // locate the php file that saves our data into the table named tablename
  180.         //var url = DatabaseURL +"Save_" +tablename.ToLower() +".php?";
  181.         var url = DatabaseURL;
  182.         if (!multipleTrials) // no new row (add data in the row where participantID == participantID)
  183.         {
  184.             url = url +"UpdateData.php?";
  185.         }
  186.         if (multipleTrials) // make a new row based on trial number
  187.         {
  188.             form.AddField("trial", Globals.trial.ToString());
  189.             url = url +"InsertData.php?";
  190.         }
  191.         WWW webRequest = new WWW(url, form);
  192.         yield return webRequest;
  193.        
  194.         if (DebugMode)
  195.         {
  196.             Debug.Log("SavePHP: " +webRequest.text);        
  197.         }      
  198.  
  199.         // check for errors
  200.         if (webRequest.error != null)
  201.         {
  202.             Debug.Log("WWW Error when trying to save the data: "+ webRequest.error +" -- Concerns data" +columnname +" " +data);
  203.         }
  204.     }
  205.  
  206.     // Compute MD5 sums for checking for user inserted input
  207.     public  string Md5Sum(string strToEncrypt)
  208.     {
  209.         System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
  210.         byte[] bytes = ue.GetBytes(strToEncrypt);
  211.      
  212.         // encrypt bytes
  213.         System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  214.         byte[] hashBytes = md5.ComputeHash(bytes);
  215.      
  216.         // Convert the encrypted bytes back to a string (base 16)
  217.         string hashString = "";
  218.      
  219.         for (int i = 0; i < hashBytes.Length; i++)
  220.         {
  221.             hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
  222.         }
  223.      
  224.         return hashString.PadLeft(32, '0');
  225.     }
  226.  
  227. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement