<?php

include_once('inmateData.class.php');

require_once("shared_functions.php");

// Get results from mysqli query
function new_mysqli_result($res, $row, $field=0) { 
    $res->data_seek($row); 
    $datarow = $res->fetch_array(); 
	if ($datarow == NULL) { 
		return FALSE; 
	}
	else { 
 		return $datarow[$field]; 
	}
} 

function test_trace1() {
	print('Test trace 1.');
}

/*
 * Inmate data class.  This class interacts with the database of inmates.
 * It can update the database when a new xml file is uploaded. It is also
 * responsible for fetching inmate data.
 */
class inmateData
{
	
	function __construct($link, $filename, $mtime)
	{
		$this->link = $link;
		$this->inmateXml = $filename;
		$this->mtime = $mtime;
	}

	/*
	 * Check to see if databases are created.  If not, create them.
	 */
	function dbCheck($link)
	{	
		$query = "SELECT * FROM UDT_inmates2";

		if (!mysqli_query($link, $query)) {
			$qry = array();
			$qry[] = "CREATE TABLE UDT_inmates2 ( prikey INT NOT NULL PRIMARY KEY AUTO_INCREMENT, nn INT, nl TEXT, nf TEXT, nm TEXT, street TEXT, csz TEXT, racegend TEXT, race CHAR(255), sex CHAR(255), dob DATE, age INT, ht TEXT, wt INT, dtin DATE, tmin TIME, dttm DATETIME, src TEXT, height INT, width INT, style TEXT, border INT, inmate_id INT )";
			$qry[] = "CREATE TABLE UDT_arrests2 ( prikey INT NOT NULL PRIMARY KEY AUTO_INCREMENT, bn INT, aa TEXT, bd DATETIME, sr DATETIME, ao TEXT, inmate_id INT)";
			$qry[] = "CREATE TABLE UDT_offenses2 ( prikey INT NOT NULL PRIMARY KEY AUTO_INCREMENT, os TEXT, ow TEXT, ol TEXT, oc TEXT, ob DOUBLE, arrest_id INT)";
			for ($i = 0; $i < count($qry); $i++) {
				if (!mysqli_query($link, $qry[$i])) {
					die("Error: ".mysqli_error($link));
					return false;
				}
			}
		}
		return true;
	}

	function xmlCheck($pathToFile)
	{
		if (!file_exists($pathToFile))
		{
			return false;
		}
		if (filemtime($pathToFile) > $this->getMtime())
		{
			$this->processXml(basename($pathToFile));
			return true;
		}
		return true;
	}
	

	function normalizeNumber($number)
	{
		$number = preg_replace("/[^0-9\.]+/", "", $number);
		return $number;
	}

	function parseDate($date, $bd = false){
		if ($date == '**:**:** **/**/**')
		{
			return "00:00:00 00/00/00";
		}
		if ($bd == true)
		{
			$month = substr($date, 9, 2);
			$day = substr($date, 12, 2);
			$year = substr($date, 15, 2);

			$time = substr($date, 0, 8);

			if ( date('y') < $year)
			{
				$year = "19".$year;
			} else {
				$year = "20".$year;
			}

			$newDate = $year."-".$month."-".$day." ".$time;

			return $newDate;
		}
		if (!strpos($date, ":"))
		{
			$month = substr($date, 0, 2);
			$day = substr($date, 3, 2);
			$year = substr($date, -2);

			if ( date('y') < $year)
			{
				$year = "19".$year;
			} else {
				$year = "20".$year;
			}
			$newDate = $year."-".$month."-".$day;
		} else {
			$month = substr($date, 0, 2);
			$day = substr($date, 3, 2);
			$year = substr($date, 6, 2);

			$time = substr($date, -5);

			if ( date('y') < $year)
			{
				$year = "19".$year;
			} else {
				$year = "20".$year;
			}
			$newDate = $year."-".$month."-".$day." ".$time.":00";
		}
		return $newDate;
	}
	
	/*
	 * This function will drop all tables associated with this plugin.
	 */
	function dropTables($link)
	{
		$qry = "DROP TABLE IF EXISTS UDT_inmates2, UDT_arrests2, UDT_offenses2";
		if (!mysqli_query($link, $qry)) {return false;} else {return true;}
	}

	/*
	 * This function drops tables and re-imports the xml
	 * file.
	 */
	function processXml($link, $file)
	{
		$this->dropTables($link);
		if (!$this->dbCheck($link)) {
			return false;
		}

		$file1 = 'jailrostera.xml';
		$filename = "https://lookup.fayettesheriff.org/import/".basename($file1);

		$array = $this->xml2array($filename);
		$prisonerCount = count($array['envelop']['ins']['in']);
		$inmateArray = $array['envelop']['ins']['in'];

		for ($i = 0; $i < $prisonerCount; $i++) {
			$personInsertQry = "INSERT INTO UDT_inmates2 ( nn, nl, nf, nm, street, csz, racegend, race, sex, dob, age, ht, wt, dtin, tmin, dttm, src, height, width, style, border, inmate_id ) VALUES ('" . mysqli_real_escape_string($link, $inmateArray[$i]['nn']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['nl']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['nf']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['nm']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['street']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['csz']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['racegend']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['race']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['sex']) . "', '" . mysqli_real_escape_string($link, $this->parseDate($inmateArray[$i]['dob'])) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['age']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['ht']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['wt']) . "', '" . mysqli_real_escape_string($link, $this->parseDate($inmateArray[$i]['dtin'])) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['tmin']) . "', '" . mysqli_real_escape_string($link, $this->parseDate($inmateArray[$i]['dttm'])) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['src']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['height']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['width']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['style']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['border']) . "', '" . mysqli_real_escape_string($link, $inmateArray[$i]['inmate_id']) . "')";
						
			if (!mysqli_query($link, $personInsertQry)) { 
				print('Error: did not insert inmate.'); 
			} else {  
				//return true; 
			}

			# If person has only one arrest
			if ($inmateArray[$i]['ar']['aa']) {
				$bn = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['bn']);
				$aa = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['aa']);
				$bd = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['bd']);
				$sr = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['sr']);
				$ao = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['ao']);
				$inmate_id = mysqli_real_escape_string($link, $inmateArray[$i]['nn']);
								
				$arrestInsertQry = "INSERT INTO UDT_arrests2 ( bn, aa, bd, sr, ao, inmate_id ) VALUES ('" . $bn . "', '" . $aa . "', '" . $bd . "', '" . $sr . "', '" . $ao . "','" . $inmate_id . "')";
			} 
			
			# If a person has many arrests
			else {
				for ($j = 0; $j < count($inmateArray[$i]['ar']); $j++) {
					$bn = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['bn']);
					$aa = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['aa']);
					$bd = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['bd']);
					$sr = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['sr']);
					$ao = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['ao']);
					$inmate_id = mysqli_real_escape_string($link, $inmateArray[$i]['nn']);
					
					$arrestInsertQry[] = "INSERT INTO UDT_arrests2 ( bn, aa, bd, sr, ao, inmate_id ) VALUES ('" . $bn . "', '" . $aa . "', '" . $bd . "', '" . $sr . "', '" . $ao . "','" . $inmate_id . "')";
				}
			}
			
			if (!is_array($arrestInsertQry)) {
				if(!mysqli_query($link, $arrestInsertQry)) { 
					//print('Error: could not insert arrest.'); 
				} else { 
					//print('did insert'); 
				}
			}
			else {
				$arrestCount = count($arrestInsertQry);
				for ($k = 0; $k < $arrestCount; $k++)
				{
					if (!mysqli_query($link, $arrestInsertQry[$k])) {
						//print("Error: could not insert one of multiple arrests.");
					}
					else {
						//print('inserted array item');
					}
				}	
			}	
			unset($personInsertQry);
			unset($mugshotInsertQry);
			unset($arrestInsertQry);
		}

		# Now parse the offenses, loop through each person
		for ($i = 0; $i < $prisonerCount; $i++) {
			# If a person has only one arrest
			if ($inmateArray[$i]['ar']['aa']) {
				# If the arrest has only one offense
				if ($inmateArray[$i]['ar']['of']['os']) {
					$arrest_id = new_mysqli_result(mysqli_query($link, "SELECT prikey FROM UDT_arrests2 where inmate_id = '" .$inmateArray[$i]['nn'] . "'"), 0, 0);
			
					$os = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['of']['os']);
					$ow = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['of']['ow']);
					$ol = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['of']['ol']);
					$oc = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['of']['oc']);
					$ob = mysqli_real_escape_string($link, $this->normalizeNumber($inmateArray[$i]['ar']['of']['ob']));
					$offenseInsertQry = "INSERT INTO UDT_offenses2 (os, ow, ol, oc, ob, arrest_id) VALUES ('" . $os . "', '" . $ow . "', '" . $ol . "', '" . $oc . "', '" . $ob . "', '" . $arrest_id ."')";
				} 
				# If the arrest has many offenses
				else {
					for ($j = 0;$j < count($inmateArray[$i]['ar']['of']); $j++) {
						$arrest_id = new_mysqli_result(mysqli_query($link, "SELECT prikey FROM UDT_arrests2 where inmate_id = '" .$inmateArray[$i]['nn'] . "'"), 0, 0);
						$os = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['of'][$j]['os']);
						$ow = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['of'][$j]['ow']);
						$ol = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['of'][$j]['ol']);
						$oc = mysqli_real_escape_string($link, $inmateArray[$i]['ar']['of'][$j]['oc']);
						$ob = mysqli_real_escape_string($link, $this->normalizeNumber($inmateArray[$i]['ar']['of'][$j]['ob']));
						$offenseInsertQry[] = "INSERT INTO UDT_offenses2 (os, ow, ol, oc, ob, arrest_id) VALUES ('" . $os . "', '" . $ow . "', '" . $ol . "', '" . $oc . "', '" . $ob . "', '" . $arrest_id . "')";
					}
				}
			} 
			
			# If the person has many arrests
			else {
				$qry = mysqli_query($link, "SELECT prikey FROM UDT_arrests2 WHERE inmate_id = '" . $inmateArray[$i]['nn'] . "'");
				$row = array();
				while ($row[] = mysqli_fetch_array($qry, MYSQLI_NUM)) { 
					echo "";
				}
				$result = array();
				for ($c = 0; $c < count($row); $c++)
				{
					$result[] = $row[$c]['prikey'];
				}
				for ($j = 0; $j < count($inmateArray[$i]['ar']); $j++)
				{
					$arrest_id = $result[$j];
					# If the arrest has only one offense
					if ($inmateArray[$i]['ar'][$j]['of']['os'])
					{
						$os = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['of']['os']);
						$ow = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['of']['ow']);
						$ol = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['of']['ol']);
						$oc = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['of']['oc']);
						$ob = mysqli_real_escape_string($link, $this->normalizeNumber($inmateArray[$i]['ar'][$j]['of']['ob']));
						$offenseInsertQry[] = "INSERT INTO UDT_offenses2 (os, ow, ol, oc, ob, arrest_id) VALUES ('" . $os . "', '" .$ow . "', '" . $ol . "', '" . $oc . "', '" . $ob . "', '" . $arrest_id . "')";
					} else {
						# If the arrest has many offenses
						for ($k = 0;$k < count($inmateArray[$i]['ar'][$j]['of']); $k++)
						{
							$os = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['of'][$k]['os']);
							$ow = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['of'][$k]['ow']);
							$ol = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['of'][$k]['ol']);
							$oc = mysqli_real_escape_string($link, $inmateArray[$i]['ar'][$j]['of'][$k]['oc']);
							$ob = mysqli_real_escape_string($link, $this->normalizeNumber($inmateArray[$i]['ar'][$j]['of'][$k]['ob']));
							$offenseInsertQry[] = "INSERT INTO UDT_offenses2 (os, ow, ol, oc, ob, arrest_id) VALUES ('" . $os . "', '" .$ow . "', '" . $ol . "', '" . $oc . "', '" . $ob . "', '" . $arrest_id . "')";
						}
					}
				}
			}
			
			if (!is_array($offenseInsertQry)) {
				if(!mysqli_query($link, $offenseInsertQry)) { 
					//print('Error: could not insert offense.'); 
				} else { 
					//print('did insert 1 offense'); 
				}
			}
			else {
				$offenseCount = count($offenseInsertQry);
				for ($k = 0; $k < $offenseCount; $k++)
				{
					if (!mysqli_query($link, $offenseInsertQry[$k])) {
						//print("Error: could not insert one of multiple offenses.");
					}
					else {
						//print('inserted one of multi offense');
					}
				}	
			}
			unset($offenseInsertQryArr);
			unset($offenseInsertQry);
		}
		clearstatcache();
		$filename = $_SESSION['docroot_path']."/import/".basename($file);
		if (!filemtime($filename)) { touch($filename); }
		$qry = "UPDATE smt_userdata set data = '".mysqli_real_escape_string($link, filemtime($filename))."' WHERE plugin = 'inmateXmlInfo' AND fieldname = 'mtime'";
		if (!mysqli_query($link, $qry)) {die("Error: ".mysqli_error());}
		return true;
	}

	/*
	 * Return inmate count.
	 */
	function countInmates($link)
	{
		$qry = mysqli_query($link, "SELECT COUNT(*) FROM UDT_inmates2");
		return new_mysqli_result($qry, 0, 0);
	}

	/*
	 * Return arrest count.
	 */
	function countArrests($link)
	{
		$qry2 = mysqli_query($link, "SELECT COUNT(*) FROM UDT_arrests2");
		return new_mysqli_result($qry2, 0, 0);
	}

	/*
	 * Return offense count
	 */
	function countOffenses($link)
	{
		$qry3 = mysqli_query($link, "SELECT COUNT(*) FROM UDT_offenses2");
		return new_mysqli_result($qry3, 0, 0);
	}	
	/*
	 * Returns an array from an xml file.
	 */
	function xml2array($url, $get_attributes = 1, $priority = 'tag'){
		$contents = "";
		if (!function_exists('xml_parser_create')){
			return array ();
		}
		$parser = xml_parser_create('');
		if (!($fp = @ fopen($url, 'r'))){
			return array ();
		}
		while (!feof($fp)){
			$contents .= fread($fp, 8192);
		}
		fclose($fp);
		xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
		xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
		xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
		xml_parse_into_struct($parser, trim($contents), $xml_values);
		xml_parser_free($parser);
		if (!$xml_values){
			return; //Hmm...
		}
		$xml_array = array ();
		$parents = array ();
		$opened_tags = array ();
		$arr = array ();
		$current = & $xml_array;
		$repeated_tag_index = array ();
		foreach ($xml_values as $data){
			unset ($attributes, $value);
			extract($data);
			$result = array ();
			$attributes_data = array ();
			if (isset ($value)){
				if ($priority == 'tag'){
					$result = $value;
				} else {
					$result['value'] = $value;
				}
			}
			if (isset ($attributes) and $get_attributes){
				foreach ($attributes as $attr => $val){
					if ($priority == 'tag'){
						$attributes_data[$attr] = $val;
					} else {
						$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
					}
				}
			}
			if ($type == "open"){
				$parent[$level -1] = & $current;
				if (!is_array($current) or (!in_array($tag, array_keys($current)))){
					$current[$tag] = $result;
					if ($attributes_data){
						$current[$tag . '_attr'] = $attributes_data;
					}
					$repeated_tag_index[$tag . '_' . $level] = 1;
					$current = & $current[$tag];
				} else {
					if(isset ($current[$tag][0])){
						$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
						$repeated_tag_index[$tag . '_' . $level]++;
					} else {
						$current[$tag] = array (
						$current[$tag],
						$result
						);
						$repeated_tag_index[$tag . '_' . $level] = 2;
						if (isset ($current[$tag . '_attr'])){
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
							unset ($current[$tag . '_attr']);
						}
					}
					$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
					$current = & $current[$tag][$last_item_index];
				}
			} elseif ($type == "complete"){
				if (!isset ($current[$tag])){
					$current[$tag] = $result;
					$repeated_tag_index[$tag . '_' . $level] = 1;
					if ($priority == 'tag' and $attributes_data){
						$current[$tag . '_attr'] = $attributes_data;
					}
				} else {
					if (isset ($current[$tag][0]) and is_array($current[$tag])) {
						$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
						if ($priority == 'tag' and $get_attributes and $attributes_data){
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
						}
						$repeated_tag_index[$tag . '_' . $level]++;
					} else {
						$current[$tag] = array (
						$current[$tag],
						$result
						);
						$repeated_tag_index[$tag . '_' . $level] = 1;
						if ($priority == 'tag' and $get_attributes){
							if (isset ($current[$tag . '_attr'])){
								$current[$tag]['0_attr'] = $current[$tag . '_attr'];
								unset ($current[$tag . '_attr']);
							}
							if ($attributes_data){
								$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
							}
						}
						$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
					}
				}
			} elseif ($type == 'close'){
				$current = & $parent[$level -1];
			}
		}
		return ($xml_array);
	}
	
	// Moved inmate class functions
	protected $inmateId;
	protected $inmateStats = array();
	protected $inmateArrest = array();

	protected function setInmateId($id)
	{
		$this->inmateId = $id;
	}
	protected function setInmateStats($link, $inmateId)
	{
		(!isset($this->inmateId)) ? $this->setInmateId($inmateId) : "";

		$qry = mysqli_query($link, "SELECT * FROM UDT_inmates2 WHERE nn = '".$this->inmateId."'");
		$result = mysqli_fetch_assoc($qry);
		$this->inmateStats = $result;
		$this->setInmateArrests($this->inmateId);
		return true;
	}

	protected function setInmateArrests($link, $id)
	{
		$arrests = array();
		$offenses = array();
		$qry = mysqli_query($link, "SELECT * FROM UDT_arrests2 WHERE inmate_id = '".$id."'");
		while ($result = mysqli_fetch_assoc($qry))
		{
			$arrests[] = $result;
		}

		$count = count($arrests);
		for ($i = 0; $i < $count; $i++)
		{
			$qry = mysqli_query($link, "SELECT * FROM UDT_offenses2 WHERE arrest_id = '".$arrests[$i]['prikey']."'");
			while ($result = mysqli_fetch_assoc($qry))
			{
				$offenses[] = $result;
			}
			$arrests[$i]['offenses'] = $offenses;
			unset($offenses);
		}
		
		$this->inmateArrest = $arrests;
		return true;
	}

	function getInmateStats($link, $id)
	{
		$this->setInmateStats($link, $id);
		return $this->inmateStats;
	}

	function getInmateArrests($link, $id)
	{
		$this->setInmateArrests($link, $id);
		return $this->inmateArrest;
	}

	function getAllInmates($link)
	{
		$qry = mysqli_query($link, "SELECT * FROM UDT_inmates2");
		while ($result = mysqli_fetch_assoc($qry))
		{
			$inmatesArray[] = $result;
		}
		return $inmatesArray;
	}

	function test()
	{
		return false;
	}

	/*
	 * Return all inmates ordered by booking date
	 */
	function getInmatesByBookingDate($link, $limit = false) {
		$qrys = "SELECT * FROM UDT_inmates2 ORDER BY dtin DESC";
		if ($limit && preg_match("/^[0-9]+$/", $limit)) {$qrys .= " LIMIT ".$limit;}
		$qry = mysqli_query($link, $qrys);
			while ($result = mysqli_fetch_assoc($qry)) {
				$inmatesArray[] = $result;
			}
		return $inmatesArray;
	}

	/*
	 * Return array of inmates arrested in the last 72 Hours
	 */
	function getRecentInmates($link, $test = false)
	{
		# 72 hours
		$timeOffset = time() - 259200;
				
		$qry = mysqli_query($link, "SELECT * FROM UDT_inmates2 WHERE dttm >= '".date('Y-m-d H:i:s', $timeOffset)."'");
		if(!$qry) {
			//print('No inmates found in recent inmate query. <br />');
		}
		else {
			while ($result = mysqli_fetch_assoc($qry)) {
				$inmatesArray[] = $result;
			}
		}
		return $inmatesArray;
	}

	/*
	 * Return inmates ordered by booking date from the last 72 hours
	 */
	function getRecentInmatesByBookingDate($link, $test = false) {
		$timeOffset = time() - 259200;
		
		$qry = mysqli_query($link, "SELECT * FROM UDT_inmates2 WHERE dttm >= '".date('Y-m-d H:i:s', $timeOffset)."' ORDER BY dtin DESC");
		if (!$qry) {
			//print('Get inmates by booking date query failed. <br />');
		}
		else {
			while ($result = mysqli_fetch_assoc($qry)) {
				$inmatesArray[] = $result;
			}
		}

		return $inmatesArray;
	}

   # Called first -- the other methods depend on this being set
   function userdata($plugin) {
		$plugin = $plugin;
   }

   # Updates value of specific field (or inserts as new rec if fieldname not found)
   # Example call: set("firstname", "billy")
   function set($link, $fieldname, $data) {
      $qry = "SELECT * FROM smt_userdata WHERE plugin='".$this->plugin."' AND fieldname = '".$fieldname."'";
      $rez = mysqli_query($link, $qry);

      # Insert new or update existing?
      if ( mysqli_num_rows($rez) < 1 ) {
         $qry = "INSERT INTO smt_userdata VALUES('', '".$this->plugin."', '".$fieldname."', '".$data."')";
         mysqli_query($link, $qry);
         //echo mysql_error(); exit;

      }
	else {
         $qry = "UPDATE smt_userdata SET data = '".$data."' WHERE plugin='".$this->plugin."' AND fieldname = '".$fieldname."'";
         mysqli_query($link, $qry);
      }
   }

   # If $fieldname is NOT passed: Gets all userdata related to passed plugin and returns it in an array
   # If $fieldname IS passed: Gets data for requested field
   # Example call: get() or get("account_id")
   function get($link, $fieldname = "") {

      # Return value of all fields or just a specific one?
      if ( $fieldname == "" ) {
         # Return all field data for this plugin
         $userdata = array();
         $qry = "SELECT * FROM smt_userdata WHERE plugin='".$this->plugin."'";
         $rez = mysqli_query($link, $qry);
         while ( $getData = mysqli_fetch_array($rez) ) {
            $userdata[$getData['fieldname']] = $getData['data'];
         }

      } else {
         # Return value of specific fieldname
         $qry = "SELECT data FROM smt_userdata WHERE plugin='".$this->plugin."' and fieldname='".$fieldname."'";
         $rez = mysqli_query($link, $qry);

         $userdata = mysqli_result($rez, 0);
      }
      return $userdata;
   }
	
}

function test_trace2() {
	print('Test trace 2.');
}

?>
