<?php

class exceptionReports{

	var $host;
	var $username;
	var $password;
	var $table;
	var $maps;
	var $email;
	var $reporturl;
	
	/**
	deletes a report by is id
	*/
	public function delete_report($id){
    mysql_query("DELETE FROM report_comments WHERE report = '$id'");
	  return mysql_query("DELETE FROM reports WHERE id = '$id'")or die(mysql_error());
	}
	
	/**
	updates the status of a report
	*/
	public function set_status($id, $status){
	  return mysql_query("UPDATE reports SET status='$status' WHERE id=$id");
	}
	
	/**
	diplays a list of exception reports, this list will link to the indiviual reports
	*/
	public function display_report_list() {
	
	
	/* Instantiate class */ 
require_once("pager.php"); 
$p = new Pager; 

/* Show many results per page? */ 
$limit = 5; 

/* Find the start depending on $_GET['page'] (declared if it's null) */ 
$start = $p->findStart($limit); 

/* Find the number of rows returned from a query; Note: Do NOT use a LIMIT clause in this query */ 
$count = mysql_num_rows(mysql_query("SELECT * FROM reports")); 

/* Find the number of pages based on $count and $limit */ 
$pages = $p->findPages($count, $limit); 

/* Now we use the LIMIT clause to grab a range of rows */ 
$r = mysql_query("SELECT * FROM reports ORDER BY id DESC LIMIT ".$start.", ".$limit); 

/* Now get the page list and echo it */ 
$pagelist = $p->pageList($_GET['page'], $pages); 


/* Or you can use a simple "Previous | Next" listing if you don't want the numeric page listing */ 
//$next_prev = $p->nextPrev($_GET['page'], $pages); 
//echo $next_prev; 

/* From here you can do whatever you want with the data from the $result link. */ 

		/*
		get all the reports
		*/
	//	$result = mysql_query("SELECT * FROM reports");

		while($report = mysql_fetch_assoc($r)) {
			$msg = stripslashes($report['msg']);
			$app = stripslashes($report['app']);
			$id = $report['id'];
			$status = $report['status'];
			$version = $report['version'];
			$count = $report['count'];
			$status_icon = '<img height="3%" src="res/newbutton.png"/>';
			
			if($status == 'updated')
			  $status_icon = '<img height="3%" src="res/updatedbutton.png"/>';
			else if ($status == 'old')
			  $status_icon = '<img height="3%" src="res/oldbutton.png"/>';
			$entry_display .= <<<ENTRY_DISPLAY
<div class="post">
<b>#$id</b> $status_icon App: <b class="centered">$app $version</b> <div align="right"> Count: <b>$count</b></div><hr/>
          <a href="{$_SERVER['PHP_SELF']}?report=$id">$msg</a>
</div>
<br/>
ENTRY_DISPLAY;

		    }
		    
		    $entry_display .= '<div class="centered">'.$pagelist.'</div>'; 
		return $entry_display;

	}


	/**
	This will display the specified report
	*/
	public function display_report($id) {

    $id = mysql_real_escape_string($id);

		/*
		get all the reports
		*/
		$r = mysql_query("SELECT * FROM reports WHERE id=".$id);

		if($report = mysql_fetch_assoc($r)) {

			$msg = stripslashes($report['msg']);
			$stackTrace = stripslashes($report['stackTrace']);
			$cause =stripslashes($report['cause']);
			$date = nl2br(stripslashes($report['date']));
			$device = nl2br(stripslashes($report['device']));
			$version = stripslashes($report['version']);
			$app = stripslashes($report['app']);
			$description = nl2br(stripslashes($report['description']));
			$count = $report['count'];
			$status = $report['status'];
			$status_icon = '<img height="5%" src="res/newbutton.png"/>';
			$update_status_button = '<a href="index.php?report='.$id.'&status=old">Mark as Old</a>';
			
			if($status == 'updated')
			  $status_icon = '<img height="5%" src="res/updatedbutton.png"/>';
			else if ($status == 'old'){
			  $status_icon = '<img height="5%" src="res/oldbutton.png"/>';
        $update_status_button = '<a href="index.php?report='.$id.'&status=new">Mark as New</a>';
      }
		 $entry_display .= <<<ENTRY_DISPLAY
        <P align="right"> 
          $update_status_button
          <a href="index.php?delete=$id" onclick="return confirm('Are you sure You want to delete this report forever?');">Delete Report</a>
        </P>
ENTRY_DISPLAY;


			$entry_display .= <<<ENTRY_DISPLAY

     <SCRIPT language=javascript Type=Text/javascript>
Function copyToClipBoard(sContents)
{
window.clipboardData.setData("Text", sContents);
alert("The contents have been copied to your clipboard.\t");
}
</SCRIPT>
     
<form name="report" >
			    	<h2>
			    	<b class="big"> #$id </b>$status_icon 
			    	<br/>
			    	$msg
		    	  </h2>
		    	  <b>Count:</b> $count
			    	<br/>
			    	<br/>
			    	<b>App</b>
			    	<br/> 
			    	$app
			    	<br/>
			    	<br/>
			    	<b>Version</b>
			    	<br/>
			    	$version
			    	<br/>
			    	<br/>
			    	<b>Stack Trace</b>
			    	<br/>
			    	<div name="stack" class="codebox" onClick="javascript:document.report.stack.select(); 
copyToClipBoard(document.report.stack.value);">$stackTrace</div>
			    	<br/>
			    	<b>Cause</b>
			    	<br/>
			      <div name="cause" class="codebox" onClick="javascript:document.report.cause.select(); 
copyToClipBoard(document.report.cause.value);">$cause</div>
			    	<br/>
			    	<b>Date</b>
			    	<br/>
			    	$date
			    	<br/>
			    	<b>Devices</b>
			    	<br/>
			    	$device
			    	<br/>
			    	<b>User Descriptions</b>
			    	<br/>
			    	$description
</form>

ENTRY_DISPLAY;
		    /*
		    comments
		    */
		    include_once('comments.php');
 		    $obj = new comments("report_comments",DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
  		
  		    $entry_display .= $obj->get_comments($id);
  		    $entry_display .= $obj->display_post($id);;
		} else {
		echo "<b>No Report Found: $id</b>";
		} 
		return $entry_display;

	}
	
	/*
	Files a new exception report into the database
	*/
	public function file_report($report){
	
		include('email.php');
	$output = "Filing report...";
	  
		/*
		add escapes to the data
		*/
		$report['msg'] = mysql_real_escape_string($report['msg']);
		$report['stackTrace'] = mysql_real_escape_string($report['stackTrace']);
		$report['cause'] = mysql_real_escape_string($report['cause']);
		$report['date'] = mysql_real_escape_string($report['date']) ."\n";
		$report['device'] = mysql_real_escape_string($report['device']) ."\n";
		$report['version'] = mysql_real_escape_string($report['version']);
		$report['app'] = mysql_real_escape_string($report['app']);
		$report['description'] = "--START NEW DESCRIPTION--- " . mysql_real_escape_string($report['description']) ."\n";

	  /*
	  check to see if a map exist
	  if it does, then we want to map the stack & cause
	  */
	  $map = $maps. $report['app'] . $report['version'] . ".txt";
    if (file_exists($map)) {
      $output .= $map . " Exists";
      $stack = fopen("tmp/stack", 'w');
      $cause = fopen("tmp/cause", 'w');      
      fwrite($stack, stripcslashes($report['stackTrace']));
      fwrite($cause, stripcslashes($report['cause']));
      fclose($stack);
      fclose($cause);
      
      $retrace = "java -jar ../lib/retrace.jar ".$map . " ";
      
      $output .= "\n";
      $output .= $retrace;
      
      $report['stackTrace'] = shell_exec($retrace . "tmp/stack");
      $output .= $report['stackTrace'];
      $report['cause'] = shell_exec($retrace . "tmp/cause");
      
      unlink("tmp/stack");
      unlink("tmp/cause");
      
    } else {
      $output .= "There was no existing map for ". $map;
    }

		/*
		Serach for duplicates and try to update them
		*/
		$updateStm = "UPDATE reports SET count=count+1, status='updated', description=concat(description,'".$report['description']."'), device=concat(device,'".$report['device']."'), date=concat(date,'".$report['date']."') WHERE msg='".$report['msg']."' AND stackTrace='".$report['stackTrace']."' AND cause='".$report['cause']."' AND version='".$report['version']."' AND app='".$report['app']."'";

		mysql_query($updateStm);

		/*
		check to see if there were any row affected
		*/
		if(mysql_affected_rows()<=0)
		{
		 /*
		 insert the new report
		 */
		 $insert =  "INSERT INTO reports (msg, stackTrace, cause, date, device, version, app, description, count, status) VALUES ('".$report['msg']."', '".$report['stackTrace']."', '".$report['cause']."', '".$report['date']."', '".$report['device']."', '".$report['version']."', '".$report['app']."', '".$report['description']."', 1, 'new')";
		 
		 
		if( mysql_query($insert))
      $output .= "Successfully filed new report";
      reportEmail($report['app'], $report['version'], $report['msg'], "NEW", mysql_insert_id());
		 return $output;

		} 
		else
		{
		  $output .= "Successfully updated an old report";
		  /*
		  we will run a query to get the row id of the updated rows
		  */
		  $query = mysql_query("SELECT * FROM reports WHERE msg='".$report['msg']."' AND stackTrace='".$report['stackTrace']."' AND cause='".$report['cause']."' AND version='".$report['version']."' AND app='".$report['app']."'");
  		while($r = mysql_fetch_assoc($query)) {
        reportEmail($report['app'], $report['version'], $report['msg'], "UPDATED", $r['id']);
      }
		 return $output;
		}
	}
	
	/*
	Converts the entire exception reports database into JSON so it can be downloaded, and parsed
	*/
	public function get_reports(){
	
		$result = mysql_query("SELECT * FROM reports");
		$reports = array();
		if(mysql_num_rows($result)) {
		        while($report = mysql_fetch_assoc($result)) {
		                $reports[] = array('report'=>$report);
	        	}
		}
//		header('Content-type: application/json');
		return json_encode(array('reports'=>$reports));
	}

	/*
	Connects the the database
	*/
	public function connect() {
    		mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
    		mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
		return $this->buildDB();
  	}

	/**
	Builds the database that will be used to for exception reports
	*/
  	private function buildDB() {
    		$sql = <<<MySQL_QUERY
			CREATE TABLE IF NOT EXISTS reports (
			id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
			msg TEXT,
			stackTrace TEXT,
			cause TEXT,
			date TEXT,
			device TEXT,
			version TEXT,
			app TEXT,
			description TEXT,
			count INTEGER,
			status TEXT
			)
MySQL_QUERY;

    		return mysql_query($sql);
    	}
}
?>
