<?php
# user_stats.php
# 
# Copyright (C) 2014  Matt Florell <vicidial@gmail.com>    LICENSE: AGPLv2
#
# CHANGES
#
# 60619-1743 - Added variable filtering to eliminate SQL injection attack threat
# 61201-1136 - Added recordings display and changed calls to time range with 10000 limit
# 70118-1605 - Added user group column to login/out and calls lists
# 70702-1231 - Added recording location link and truncation
# 80117-0316 - Added vicidial_user_closer_log entries to display
# 80501-0506 - Added Hangup Reason to logs display
# 80523-2012 - Added vicidial timeclock records display
# 80617-1402 - Fixed timeclock total logged-in time
# 81210-1634 - Added server recording display options
# 90208-0504 - Added link to multi-day report and fixed call status summary section
# 90305-1226 - Added user_call_log manual dial logs
# 90310-0734 - Added admin header
# 90508-0644 - Changed to PHP long tags
# 90524-2009 - Changed time display to use functions.php
# 91130-2037 - Added user closer log manager flag display
# 100126-0847 - Added DID log display options
# 100203-1008 - Added agent activity log section
# 100216-0042 - Added popup date selector
# 100425-0115 - Added more login data
# 100712-1324 - Added system setting slave server option
# 100802-2347 - Added User Group Allowed Reports option validation
# 100908-1205 - Added customer 3way hangup flags to user calls display
# 100914-1326 - Added lookup for user_level 7 users to set to reports only which will remove other admin links
# 110218-1523 - Added searches display
# 110703-1836 - Added download option
# 110718-1204 - Added skipped manual dial leads display
# 111103-1050 - Added admin_hide_phone_data and admin_hide_lead_data options
# 111106-1105 - Added user_group restrictions
# 120223-2135 - Removed logging of good login passwords if webroot writable is enabled
# 121222-2152 - Added email log display
# 130124-1740 - Added option to display first and last name of lead
# 130414-0146 - Added report logging
# 130610-0938 - Finalized changing of all ereg instances to preg
# 130616-0059 - Added filtering of input to prevent SQL injection attacks and new user auth
# 130625-1341 - Added phone login and phone_ip display to login/logout section
# 130901-0836 - Changed to mysqli PHP functions
# 131016-2102 - Added checking for level 8 add-copy restriction
# 131122-0705 - Added pause_code_rpt option coming from Agent Time Detail report
# 140108-0709 - Added webserver and hostname to report logging
#

$startMS = microtime();

require("dbconnect_mysqli.php");
require("functions.php");

$report_name = 'User Recordings';
$db_source = 'M';

$firstlastname_display_user_stats=0;
$add_copy_disabled=0;
if (file_exists('options.php'))
	{
	require('options.php');
	}

$PHP_AUTH_USER=$_SERVER['PHP_AUTH_USER'];
$PHP_AUTH_PW=$_SERVER['PHP_AUTH_PW'];
$PHP_SELF=$_SERVER['PHP_SELF'];
if (isset($_GET["did_id"]))					{$did_id=$_GET["did_id"];}
	elseif (isset($_POST["did_id"]))		{$did_id=$_POST["did_id"];}
if (isset($_GET["did"]))					{$did=$_GET["did"];}
	elseif (isset($_POST["did"]))			{$did=$_POST["did"];}
if (isset($_GET["begin_date"]))				{$begin_date=$_GET["begin_date"];}
	elseif (isset($_POST["begin_date"]))	{$begin_date=$_POST["begin_date"];}
if (isset($_GET["end_date"]))				{$end_date=$_GET["end_date"];}
	elseif (isset($_POST["end_date"]))		{$end_date=$_POST["end_date"];}
if (isset($_GET["user"]))					{$user=$_GET["user"];}
	elseif (isset($_POST["user"]))			{$user=$_POST["user"];}
if (isset($_GET["DB"]))						{$DB=$_GET["DB"];}
	elseif (isset($_POST["DB"]))			{$DB=$_POST["DB"];}
if (isset($_GET["submit"]))					{$submit=$_GET["submit"];}
	elseif (isset($_POST["submit"]))		{$submit=$_POST["submit"];}
if (isset($_GET["SUBMIT"]))					{$SUBMIT=$_GET["SUBMIT"];}
	elseif (isset($_POST["SUBMIT"]))		{$SUBMIT=$_POST["SUBMIT"];}
if (isset($_GET["file_download"]))				{$file_download=$_GET["file_download"];}
	elseif (isset($_POST["file_download"]))		{$file_download=$_POST["file_download"];}
if (isset($_GET["pause_code_rpt"]))				{$pause_code_rpt=$_GET["pause_code_rpt"];}
	elseif (isset($_POST["pause_code_rpt"]))		{$pause_code_rpt=$_POST["pause_code_rpt"];}

#############################################
##### START SYSTEM_SETTINGS LOOKUP #####
$stmt = "SELECT use_non_latin,outbound_autodial_active,slave_db_server,reports_use_slave_db,user_territories_active,webroot_writable,allow_emails,level_8_disable_add FROM system_settings;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {$MAIN.="$stmt\n";}
$qm_conf_ct = mysqli_num_rows($rslt);
if ($qm_conf_ct > 0)
	{
	$row=mysqli_fetch_row($rslt);
	$non_latin =					$row[0];
	$SSoutbound_autodial_active =	$row[1];
	$slave_db_server =				$row[2];
	$reports_use_slave_db =			$row[3];
	$user_territories_active =		$row[4];
	$webroot_writable =				$row[5];
	$allow_emails =					$row[6];
	$SSlevel_8_disable_add =		$row[7];
	}
##### END SETTINGS LOOKUP #####
###########################################

$STARTtime = date("U");
$TODAY = date("Y-m-d");

if ( (!isset($begin_date)) or (strlen($begin_date) < 10) ) {$begin_date = $TODAY;}
if ( (!isset($end_date)) or (strlen($end_date) < 10) ) {$end_date = $TODAY;}

if ($non_latin < 1)
	{
	$PHP_AUTH_USER = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_USER);
	$PHP_AUTH_PW = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_PW);
	}
else
	{
	$PHP_AUTH_PW = preg_replace("/'|\"|\\\\|;/","",$PHP_AUTH_PW);
	$PHP_AUTH_USER = preg_replace("/'|\"|\\\\|;/","",$PHP_AUTH_USER);
	}
$did_id = preg_replace("/'|\"|\\\\|;/","",$did_id);
$did = preg_replace("/'|\"|\\\\|;/","",$did);
$begin_date = preg_replace("/'|\"|\\\\|;/","",$begin_date);
$end_date = preg_replace("/'|\"|\\\\|;/","",$end_date);
$user = preg_replace("/'|\"|\\\\|;/","",$user);

$auth=0;
$reports_auth=0;
$admin_auth=0;
$auth_message = user_authorization($PHP_AUTH_USER,$PHP_AUTH_PW,'REPORTS',1);
if ($auth_message == 'GOOD')
	{$auth=1;}

if ($auth > 0)
	{
	$stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 7 and view_reports > 0;";
	if ($DB) {echo "|$stmt|\n";}
	$rslt=mysql_to_mysqli($stmt, $link);
	$row=mysqli_fetch_row($rslt);
	$admin_auth=$row[0];

	$stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 6 and view_reports > 0;";
	if ($DB) {echo "|$stmt|\n";}
	$rslt=mysql_to_mysqli($stmt, $link);
	$row=mysqli_fetch_row($rslt);
	$reports_auth=$row[0];

	if ($reports_auth < 1)
		{
		$VDdisplayMESSAGE = "You are not allowed to view reports";
		Header ("Content-type: text/html; charset=utf-8");
		echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n";
		exit;
		}
	if ( ($reports_auth > 0) and ($admin_auth < 1) )
		{
		$ADD=999999;
		$reports_only_user=1;
		}
	}
else
	{
	$VDdisplayMESSAGE = "Login incorrect, please try again";
	if ($auth_message == 'LOCK')
		{
		$VDdisplayMESSAGE = "Too many login attempts, try again in 15 minutes";
		Header ("Content-type: text/html; charset=utf-8");
		echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n";
		exit;
		}
	Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\"");
	Header("HTTP/1.0 401 Unauthorized");
	echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$PHP_AUTH_PW|$auth_message|\n";
	exit;
	}


$stmt="SELECT user_level from vicidial_users where user='$PHP_AUTH_USER';";
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$LOGuser_level				=$row[0];

if (($LOGuser_level < 9) and ($SSlevel_8_disable_add > 0))
	{$add_copy_disabled++;}


$date = date("r");
$ip = getenv("REMOTE_ADDR");
$browser = getenv("HTTP_USER_AGENT");

##### BEGIN log visit to the vicidial_report_log table #####
$LOGip = getenv("REMOTE_ADDR");
$LOGbrowser = getenv("HTTP_USER_AGENT");
$LOGscript_name = getenv("SCRIPT_NAME");
$LOGserver_name = getenv("SERVER_NAME");
$LOGserver_port = getenv("SERVER_PORT");
$LOGrequest_uri = getenv("REQUEST_URI");
$LOGhttp_referer = getenv("HTTP_REFERER");
if (preg_match("/443/i",$LOGserver_port)) {$HTTPprotocol = 'https://';} 
  else {$HTTPprotocol = 'http://';}
if (($LOGserver_port == '80') or ($LOGserver_port == '443') ) {$LOGserver_port='';}
else {$LOGserver_port = ":$LOGserver_port";}
$LOGfull_url = "$HTTPprotocol$LOGserver_name$LOGserver_port$LOGrequest_uri";

$LOGhostname = php_uname('n');
if (strlen($LOGhostname)<1) {$LOGhostname='X';}
if (strlen($LOGserver_name)<1) {$LOGserver_name='X';}

$stmt="SELECT webserver_id FROM vicidial_webservers where webserver='$LOGserver_name' and hostname='$LOGhostname' LIMIT 1;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {echo "$stmt\n";}
$webserver_id_ct = mysqli_num_rows($rslt);
if ($webserver_id_ct > 0)
	{
	$row=mysqli_fetch_row($rslt);
	$webserver_id = $row[0];
	}
else
	{
	##### insert webserver entry
	$stmt="INSERT INTO vicidial_webservers (webserver,hostname) values('$LOGserver_name','$LOGhostname');";
	if ($DB) {echo "$stmt\n";}
	$rslt=mysql_to_mysqli($stmt, $link);
	$affected_rows = mysqli_affected_rows($link);
	$webserver_id = mysqli_insert_id($link);
	}

$stmt="INSERT INTO vicidial_report_log set event_date=NOW(), user='$PHP_AUTH_USER', ip_address='$LOGip', report_name='$report_name', browser='$LOGbrowser', referer='$LOGhttp_referer', notes='$LOGserver_name:$LOGserver_port $LOGscript_name |$user, $query_date, $end_date, $shift, $file_download, $report_display_type|', url='$LOGfull_url', webserver='$webserver_id';";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$report_log_id = mysqli_insert_id($link);
##### END log visit to the vicidial_report_log table #####

if ( (strlen($slave_db_server)>5) and (preg_match("/$report_name/",$reports_use_slave_db)) )
	{
	mysqli_close($link);
	$use_slave_server=1;
	$db_source = 'S';
	require("dbconnect_mysqli.php");
	$MAIN.="<!-- Using slave server $slave_db_server $db_source -->\n";
	}

$stmt="SELECT full_name,user_group,admin_hide_lead_data,admin_hide_phone_data from vicidial_users where user='$PHP_AUTH_USER';";
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$LOGfullname =				$row[0];
$LOGuser_group =			$row[1];
$LOGadmin_hide_lead_data =	$row[2];
$LOGadmin_hide_phone_data =	$row[3];

$stmt="SELECT allowed_campaigns,allowed_reports,admin_viewable_groups from vicidial_user_groups where user_group='$LOGuser_group';";
if ($DB) {$MAIN.="|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$row=mysqli_fetch_row($rslt);
$LOGallowed_campaigns =		$row[0];
$LOGallowed_reports =		$row[1];
$LOGadmin_viewable_groups =	$row[2];

$LOGadmin_viewable_groupsSQL='';
$vuLOGadmin_viewable_groupsSQL='';
$whereLOGadmin_viewable_groupsSQL='';
if ( (!preg_match('/\-\-ALL\-\-/i',$LOGadmin_viewable_groups)) and (strlen($LOGadmin_viewable_groups) > 3) )
	{
	$rawLOGadmin_viewable_groupsSQL = preg_replace("/ -/",'',$LOGadmin_viewable_groups);
	$rawLOGadmin_viewable_groupsSQL = preg_replace("/ /","','",$rawLOGadmin_viewable_groupsSQL);
	$LOGadmin_viewable_groupsSQL = "and user_group IN('---ALL---','$rawLOGadmin_viewable_groupsSQL')";
	$whereLOGadmin_viewable_groupsSQL = "where user_group IN('---ALL---','$rawLOGadmin_viewable_groupsSQL')";
	$vuLOGadmin_viewable_groupsSQL = "and vicidial_users.user_group IN('---ALL---','$rawLOGadmin_viewable_groupsSQL')";

	if (strlen($user) > 0)
		{
		if ($did > 0)
			{
			$stmt="SELECT count(*) from vicidial_inbound_dids where did_pattern='$user' $LOGadmin_viewable_groupsSQL;";
			$rslt=mysql_to_mysqli($stmt, $link);
			$row=mysqli_fetch_row($rslt);
			$allowed_count = $row[0];
			}
		else
			{
			$stmt="SELECT count(*) from vicidial_users where user='$user' $LOGadmin_viewable_groupsSQL;";
			$rslt=mysql_to_mysqli($stmt, $link);
			$row=mysqli_fetch_row($rslt);
			$allowed_count = $row[0];
			}

		if ($allowed_count < 1)
			{
			echo "This user does not exist: |$PHP_AUTH_USER|$user|\n";
			exit;
			}
		}
	}

if ( (!preg_match("/$report_name/",$LOGallowed_reports)) and (!preg_match("/ALL REPORTS/",$LOGallowed_reports)) )
	{
    Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\"");
    Header("HTTP/1.0 401 Unauthorized");
    echo "You are not allowed to view this report: |$PHP_AUTH_USER|$report_name|\n";
    exit;
	}

if ($did > 0)
	{
	$stmt="SELECT did_description from vicidial_inbound_dids where did_pattern='$user' $LOGadmin_viewable_groupsSQL;";
	$rslt=mysql_to_mysqli($stmt, $link);
	$row=mysqli_fetch_row($rslt);
	$full_name = $row[0];
	}
else
	{
	$stmt="SELECT full_name from vicidial_users where user='$user' $LOGadmin_viewable_groupsSQL;";
	$rslt=mysql_to_mysqli($stmt, $link);
	$row=mysqli_fetch_row($rslt);
	$full_name = $row[0];
	}



$HEADER.="<html>\n";
$HEADER.="<head>\n";
$HEADER.="<script language=\"JavaScript\" src=\"calendar_db.js\"></script>\n";
$HEADER.="<link rel=\"stylesheet\" href=\"calendar.css\">\n";
$HEADER.="<link href='css/style.css' rel='stylesheet' />\n";
$HEADER.="<link href='js/bootstrap/dist/css/bootstrap.css' rel='stylesheet'/>\n";
$HEADER.="<link href='fonts/font-awesome-4/css/font-awesome.min.css' rel='stylesheet'/>\n";
$HEADER.="<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=utf-8\">\n";

if ($did > 0)
	{$HEADER.="<title>ADMINISTRATION: DID Call Stats";}
else
	{$HEADER.="<title>ADMINISTRATION: $report_name";}



##### BEGIN Set variables to make header show properly #####
$ADD =					'0';
$hh =					'users';
$LOGast_admin_access =	'1';
$ADMIN =				'admin.php';
$page_width='770';
$section_width='750';
$header_font_size='3';
$subheader_font_size='2';
$subcamp_font_size='2';
$header_selected_bold='<b>';
$header_nonselected_bold='';
$users_color =		'#FFFF99';
$users_font =		'BLACK';
$users_color =		'#E6E6E6';
$subcamp_color =	'#C6C6C6';
if ($did > 0)
	{
	$hh =	'ingroups';
	$ADD =	'3311';
	$ingroups_color =		'#FFFF99';
	$ingroups_font =		'BLACK';
	$ingroups_color =		'#E6E6E6';
	}
##### END Set variables to make header show properly #####

#require("admin_header.php");


$MAIN.="<div class='header'>";

$MAIN.="<h4> &nbsp; User Recordings</h4>";

$MAIN.='</div>';
//$MAIN.="</TD><TD ALIGN=RIGHT></TD></TR>\n";
$MAIN.="<TABLE WIDTH=770 BGCOLOR=#E6E6E6 cellpadding=3 cellspacing=0 class='no-border'><TR><TD ALIGN=LEFT class='no-border'>\n";
$MAIN.="<TR class='border'><TD ALIGN=LEFT COLSPAN=2 class='no-border'><FONT FACE=\"ARIAL,HELVETICA\" COLOR=BLACK SIZE=2><B> &nbsp; \n";

$download_link="$PHP_SELF?DB=$DB&begin_date=$begin_date&end_date=$end_date&user=$user&submit=$submit\n";

$MAIN.="<form action=$PHP_SELF method=GET name=vicidial_report id=vicidial_report>\n";
$MAIN.="<input type=hidden name=DB value=\"$DB\">\n";
$MAIN.="<div class='col-md-2 no-padding'><input class='form-control' type=text name=begin_date value=\"$begin_date\" size=10 maxsize=10></div><div class='col-sm-1 no-padding'>";

$MAIN.="<script language=\"JavaScript\">\n";
$MAIN.="var o_cal = new tcal ({\n";
$MAIN.="	// form name\n";
$MAIN.="	'formname': 'vicidial_report',\n";
$MAIN.="	// input name\n";
$MAIN.="	'controlname': 'begin_date'\n";
$MAIN.="});\n";
$MAIN.="o_cal.a_tpl.yearscroll = false;\n";
$MAIN.="// o_cal.a_tpl.weekstart = 1; // Monday week start\n";
$MAIN.="</script>\n";

$MAIN.="</div><div class='col-sm-1 no-padding' style='margin-top:9px;'>to</div> <div class='col-md-2 no-padding'><input class='form-control' type=text name=end_date value=\"$end_date\" size=10 maxsize=10></div><div class='col-sm-1 no-padding'>";

$MAIN.="<script language=\"JavaScript\">\n";
$MAIN.="var o_cal = new tcal ({\n";
$MAIN.="	// form name\n";
$MAIN.="	'formname': 'vicidial_report',\n";
$MAIN.="	// input name\n";
$MAIN.="	'controlname': 'end_date'\n";
$MAIN.="});\n";
$MAIN.="o_cal.a_tpl.yearscroll = false;\n";
$MAIN.="// o_cal.a_tpl.weekstart = 1; // Monday week start\n";
$MAIN.="</script></div>\n";

if (strlen($user)>1)
{
	//$MAIN.="<input type=hidden name=user value=\"$user\">\n";
	$MAIN.="<div class='col-md-2'><input placeholder='USER ID' class='form-control' type=text name=user value=\"$user\" size=12 maxlength=10></div>\n";

}
else
	{$MAIN.="<div class='col-md-2'><input placeholder='USER ID' class='form-control' type=text name=user size=12 maxlength=10></div>\n";}
$MAIN.="<input type=submit name=submit value=submit class='btn btn-success'>\n";


$MAIN.=" </form>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $user  $full_name<BR><BR>\n";




$MAIN.="</B></TD></TR>\n";
$MAIN.="<TR><TD ALIGN=LEFT COLSPAN=2 class='no-border'>\n";

$MAIN.="<br><center>\n";

if ($pause_code_rpt >= 1)
	{}
else
	{
	$user_con = "";
	if($user){
		$user_con = "user='" . mysqli_real_escape_string($link, $user) . "' and ";
	}
	
	
	##### vicidial recordings for this time period #####

	$MAIN.="<center><B>RECORDINGS FOR THIS TIME PERIOD: (10000 record limit)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='$download_link&file_download=8'>[DOWNLOAD]</a></B></center>";
	$MAIN.="<TABLE width=750 cellspacing=0 cellpadding=1 class='hover'>\n";
	$MAIN.="<tr style='background-color:#e8e8e8;'><td><b># </b></td><td ><b> LEAD</b></td><td><b>DATE/TIME</b> </td><td ><b>SECONDS</b> </td><td ><b> RECID</b></td><td ><b> USER</b></td><td ><b>FILENAME</b></td><td ><b>LOCATION </b> </td><td ><b>Rate </b> </td><td ><b>Rate By </b> </td></tr>\n";
	$CSV_text8.="\"RECORDINGS FOR THIS TIME PERIOD: (10000 record limit)\"\n";
	$CSV_text8.="\"\",\"#\",\"LEAD\",\"DATE/TIME\",\"SECONDS\",\"RECID\",\"USER\",\"FILENAME\",\"LOCATION\",\"RATING\",\"RATE BY\"\n";

		$stmt="select recording_id,channel,server_ip,extension,start_time,start_epoch,end_time,end_epoch,length_in_sec,length_in_min,filename,location,lead_id,user,vicidial_id, rating, rate_by from recording_log where $user_con start_time >= '" . mysqli_real_escape_string($link, $begin_date) . " 0:00:01'  and start_time <= '" . mysqli_real_escape_string($link, $end_date) . " 23:59:59' order by recording_id desc limit 10000;";
		$rslt=mysql_to_mysqli($stmt, $link);
		$logs_to_print = mysqli_num_rows($rslt);

		$u=0;
		while ($logs_to_print > $u) 
			{
			$row=mysqli_fetch_row($rslt);
			if (preg_match("/1$|3$|5$|7$|9$/i", $u))
				{$bgcolor='bgcolor="#B9CBFD"';} 
			else
				{$bgcolor='bgcolor="#9BB9FB"';}

			$location = $row[11];
			$CSV_location=$row[11];

			if (strlen($location)>2)
				{
				$URLserver_ip = $location;
				$URLserver_ip = preg_replace('/http:\/\//i', '',$URLserver_ip);
				$URLserver_ip = preg_replace('/https:\/\//i', '',$URLserver_ip);
				$URLserver_ip = preg_replace('/\/.*/i', '',$URLserver_ip);
				$stmt="select count(*) from servers where server_ip='$URLserver_ip';";
				$rsltx=mysql_to_mysqli($stmt, $link);
				$rowx=mysqli_fetch_row($rsltx);
				
				if ($rowx[0] > 0)
					{
					$stmt="select recording_web_link,alt_server_ip,external_server_ip from servers where server_ip='$URLserver_ip';";
					$rsltx=mysql_to_mysqli($stmt, $link);
					$rowx=mysqli_fetch_row($rsltx);
					
					if (preg_match("/ALT_IP/i",$rowx[0]))
						{
						$location = preg_replace("/$URLserver_ip/i", "$rowx[1]", $location);
						}
					if (preg_match("/EXTERNAL_IP/i",$rowx[0]))
						{
						$location = preg_replace("/$URLserver_ip/i", "$rowx[2]", $location);
						}
					}
				}

			if (strlen($location)>30)
				{$locat = substr($location,0,27);  $locat = "$locat...";}
			else
				{$locat = $location;}
			if ( (preg_match('/ftp/i',$location)) or (preg_match('/http/i',$location)) )
				{$location = "<a target='_blank' href=\"$location\">Recording</a>";}
			else
				{$location = $locat;}
			$u++;
			$MAIN.="<tr>";
			$MAIN.="<td>$u</td>";
			$MAIN.="<td > <A HREF=\"admin_modify_lead.php?lead_id=$row[12]\" target=\"_blank\">$row[12]</A> </td>";
			$MAIN.="<td > $row[4] </td>\n";
			$MAIN.="<td > $row[8] </td>\n";
			$MAIN.="<td > $row[0] </td>\n";
			$MAIN.="<td > $row[13] </td>\n";
			$MAIN.="<td > $row[10] </td>\n";
			$MAIN.="<td > $location &nbsp; </td>\n";
			$MAIN.="<td > <div class=\"star_rate\" rec-id=\"".$row[0]."\" data-rating-value=\"".$row[15]."\"></div> </td>\n";
			$MAIN.="<td > $row[16] </td>\n";
			
			$MAIN.="</tr>\n";
			$CSV_text8.="\"\",\"$u\",\"$row[12]\",\"$row[4]\",\"$row[8]\",\"$row[0]\",\"$row[13]\",\"$row[10]\",\"$CSV_location\",\"$row[15]\",\"$row[16]\"\n";
			}

	$MAIN.="</TABLE><BR><BR>\n";

	}

$ENDtime = date("U");

$RUNtime = ($ENDtime - $STARTtime);

$MAIN.="\n\n\n<br><br><br>\n\n";


$MAIN.="<font size=0>\n\n\n<br><br><br>\nscript runtime: $RUNtime seconds|$db_source</font>";

$MAIN.="</TD></TR><TABLE>";
$MAIN.='<script src="js/jquery.js"></script>
    <script src="js/jquery_j.js"></script>
    <script src="js/jquery.min.js"></script>
    <script src="libs/rating-star-icons/src/rating.js"></script>
	<script src="js/jquery.cookie/jquery.cookie.js"></script>
  <script src="js/jquery.pushmenu/js/jPushMenu.js"></script>
	<script type="text/javascript" src="js/jquery.nanoscroller/jquery.nanoscroller.js"></script>
	<script type="text/javascript" src="js/jquery.sparkline/jquery.sparkline.min.js"></script>
  <script type="text/javascript" src="js/jquery.ui/jquery-ui.js" ></script>
	<script type="text/javascript" src="js/jquery.gritter/js/jquery.gritter.js"></script>
	<script type="text/javascript" src="js/behaviour/core.js"></script>
  <script src="js/bootstrap/dist/js/bootstrap.min.js"></script>
  <script>
  	$(".star_rate").rating({
  		"half":true,
		"emptyStar": "fa fa-star-o icon",
		"halfStar": "fa fa-star-half-full icon",
		"filledStar": "fa fa-star icon",
		"color":"#0088fd",
		"readonly":true,

		"click": function (e) {
			if(e.event){
				$.post("user_recordings_update.php", {recording_id: e.recid, rating: e.stars}, function(result){
				    console.log(result);
				    if(result == \'updated\'){

				    }else{
				    	alert("unable to rate.");
				    }
				});
				//console.log(e); // {stars: 3, event: E.Event}

			}
		}
	});
  </script>
  ';
$MAIN.="</body>";
$MAIN.="</html>";


if ($file_download>0) 
	{
	$FILE_TIME = date("Ymd-His");
	$CSVfilename = "user_stats_$US$FILE_TIME.csv";
	$CSV_var="CSV_text".$file_download;
	$CSV_text=preg_replace('/^\s+/', '', $$CSV_var);
	$CSV_text=preg_replace('/\n\s+,/', ',', $CSV_text);
	$CSV_text=preg_replace('/ +\"/', '"', $CSV_text);
	$CSV_text=preg_replace('/\" +/', '"', $CSV_text);
	// We'll be outputting a TXT file
	header('Content-type: application/octet-stream');

	// It will be called LIST_101_20090209-121212.txt
	header("Content-Disposition: attachment; filename=\"$CSVfilename\"");
	header('Expires: 0');
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	header('Pragma: public');
	ob_clean();
	flush();

	echo "$CSV_text";
	}
else
	{
	header ("Content-type: text/html; charset=utf-8");
	echo $HEADER;
	require("admin_header.php");
	echo $MAIN;
	}

if ($db_source == 'S')
	{
	mysqli_close($link);
	$use_slave_server=0;
	$db_source = 'M';
	require("dbconnect_mysqli.php");
	}

$endMS = microtime();
$startMSary = explode(" ",$startMS);
$endMSary = explode(" ",$endMS);
$runS = ($endMSary[0] - $startMSary[0]);
$runM = ($endMSary[1] - $startMSary[1]);
$TOTALrun = ($runS + $runM);

$stmt="UPDATE vicidial_report_log set run_time='$TOTALrun' where report_log_id='$report_log_id';";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);

exit;

?>
