functions.php

Requires

This file includes env.inc.php.

include_once 'env.inc.php'; 

Form and Function

Holds the majority of the site functions.

//Check if magic qoutes is on then stripslashes if needed
function codeClean($var)
{
    if (is_array($var)) {
		foreach($var as $key=>$val) {
			$output[$key] = codeClean($val);
    	}
    } else {
		$var = strip_tags(trim($var));
		$output = sqlEscapeString((get_magic_quotes_gpc())? stripslashes($var): $var);
	}
	if (!empty($output))
		return $output;
}
function viewOnPage($var)
{
    $var = htmlentities(trim($var));
    $output = sqlEscapeString((get_magic_quotes_gpc())? stripslashes($var): $var);
 
	if (!empty($output))
	    return $output;
}
//Mail functions
function sendEmail($ToEmail,$Subject,$Body,$From,$FromEmail)
{
	$ver = phpversion();
	$Body = preg_replace("!<br \/>!","\n",$Body);
 
	$headers.="From: $From <$FromEmail>\n";
	$headers.="Reply-To: <$FromEmail>\n";
	$headers.="X-Sender: <$FromEmail>\n";
	$headers.="X-Mailer: PHP-$ver \n";
	$headers.="X-Priority: 3\n"; //1 UrgentMessage, 3 Normal
	$headers.="Return-Path: <$FromEmail> \n";
 
	mail($ToEmail,$Subject,wordwrap($Body),$headers);
}
//check contact us form for submission errors
function checkSubmitForm($from_email,$from_name,$subject,$msg,$captcha,$security_code)
{
	if (!validateEmail($from_email)){
		return 1;
	} elseif (empty($from_name)) {
		return 2; 
	} elseif (empty($subject)) {
		return 3;
	} elseif (empty($msg)) {
		return 4;
	} elseif (!empty($security_code) && $security_code !== "$captcha") {
		return 5;
	} elseif (empty($captcha)) {
		return 6;
	} else {
		return 99;
	}
}
// function to check the referer for security reasons.
function checkReferer($referers) 
{
	$referer = getenv("HTTP_REFERER");
	list($remove,$stuff) = split('//',$referer,2);
	list($home,$stuff) = split('/',$stuff,2);
 
	for ($x = 0; $x < count($referers); $x++) {
		if (preg_match("!$referers[$x]!","$home")) {
			//print "".__LINE__." $home <-home $referer <-referer";
			return true;
		}
	}
 
   	//if you get this far you have not met the criteria and will be redirected
	//if someone comes from a place other then in our referers list
	//set them in the right spot on our domain
	$time = date('Y-m-d h:i');
	if (empty($referer)) {
		error_log(" $time Empty Referer. '".getenv("REMOTE_ADDR")."' \r\n", 3, "error.txt");
		header("Location: index.php");
		return false;
	} else {
		error_log(" $time Illegal Referer. '".getenv("HTTP_REFERER")."' \r\n", 3, "error.txt");
		header("Location: index.php");
		return false;
	}
}
//Login functions
function verifyLogin($user,$pass)
{
	//Encrypt password for database verification
	$salt = 's+(_a*';
	$pass = md5($pass.$salt);
 
	$sql = "SELECT pass FROM users WHERE pass = '" . $pass . "' AND user = '" . $user ."'";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$num = sqlNumRows($res);
 
	if ($num > 0)
		return true;
	return false;	
}
function verifyCookie($user,$pass)
{
	$sql = "SELECT pass FROM users WHERE pass = '" . $pass . "' AND user = '" . $user ."'";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$num = sqlNumRows($res);
 
	if ($num > 0)
		return true;
	return false;	
}
//Page auth function
function checkPrivs()
{
	if (!empty($_SESSION["admin"])) {
		return 'admin';
	} elseif (!empty($_SESSION["seller"])) {
		return 'seller';
	} else {
		return 'user';
	}
}
function checkIfAdmin($user,$pass)
{
	$sql = "SELECT pass FROM users WHERE pass = '" . $pass . "' AND user = '" . $user ."' AND user_level = 9 ";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$num = sqlNumRows($res);
 
	if ($num > 0)
		return true;
	return false;	
}
function checkIfSeller($user,$pass)
{
	$sql = "SELECT pass FROM users WHERE pass = '" . $pass . "' AND user = '" . $user ."' AND user_level = 2 ";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$num = sqlNumRows($res);
 
	if ($num > 0)
		return true;
	return false;	
}
function logoff()
{
	global $visitor_tracking;
 
	//when logging off delete from the online users tables if user tracking is enabled
	if (!empty($visitor_tracking) && isset($_SESSION["user"])) {
		$sql = "DELETE FROM onlineusers WHERE user = '" . $_SESSION["user"] . "'";
		$del = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	}
 
	// remove all session variables and destroy session
	unset($_SESSION["user"]);
	unset($_SESSION["pass"]);
	unset($_SESSION["logged_in"]);
	unset($_SESSION["admin"]);
 
	session_destroy();
 
	if (isset($_COOKIE["user"])) {
		setcookie("user", NULL, time()-3600);
		setcookie("pass", NULL, time()-3600);
	}
 
	if (isset($_COOKIE[session_name()])) {
    	setcookie(session_name(), NULL, time()-3600);
	}
 
	// redirect them to anywhere you like.
	header("Location: login.php");
}
//Update account functions
function getUserRecords($user)
{
	$sql = "SELECT * FROM users WHERE user = '" . $user . "'"; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		$records[$c]["id"] = $a_row["id"];
		$records[$c]["email"] = $a_row["email"];
		$records[$c]["user"] = $a_row["user"];
		$records[$c]["first_name"] = $a_row["first_name"];
		$records[$c]["last_name"] = $a_row["last_name"];
		$records[$c]["phone"] = $a_row["phone"];
		$records[$c]["alt_phone"] = $a_row["alt_phone"];
		$records[$c]["fax"] = $a_row["fax"];
		$records[$c]["image"] = $a_row["image"];
		$records[$c]["address"] = $a_row["address"];
		$records[$c]["city"] = $a_row["city"];
		$records[$c]["state"] = $a_row["state"];
		$records[$c]["zip"] = $a_row["zip"];
		$records[$c]["reg_date"] = $a_row["reg_date"];
		$records[$c]["image"] = $a_row["image"];
	$c++;
    }
	if (!empty($records))
	    return $records;
}
function updateUser($user, $email, $first_name, $last_name, $phone, $alt_phone, $fax, $address, $city, $state, $zip)
{
	if (!validateEmail($email))	{
		return 1;
	} elseif (!validatePhone($phone)) {
		return 2;
	} elseif (!validateName($first_name)) {
		return 3;
	} elseif (!validateName($last_name)) {
		return 4;
	} else {
		// Get remote IP
		$ipaddress = ipConvertLong(getenv('REMOTE_ADDR'));
		$sql = "UPDATE users SET ipaddress = '" . $ipaddress . "', email = '" . $email . "', first_name = '" . $first_name . "', last_name = '" . $last_name . "', phone = '" . $phone . "', alt_phone = '" . $alt_phone . "', fax = '" . $fax . "', address = '". $address . "', city = '". $city . "', state = '". $state . "', zip = '". $zip . "' WHERE user = '" . $user . "'";		
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	return 99;
	}
}
//Reset password functions
function updatePass($user,$pass)
{
	//Encrypt password for database
	$salt = 's+(_a*';
	$new_password = md5($pass.$salt);
	//if user logged in change their session password 
	if (isset($_SESSION["pass"])) {
		$_SESSION["pass"] = "$new_password";
	}
 
	//if remember me function already set
	//change cookie for remember me
	if (isset($_COOKIE["pass"])) {
		setcookie("pass", "$new_password", time() + (60*60*24*30));
	}
 
	//perform sqlQuery and update user info in the database
	$sql = "UPDATE users SET pass = '" . $new_password . "' WHERE user = '" . $user . "'";
 	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
}
function generatePassword($len)
{
	$password = "";
	$char = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
 
	$count=0;
	while ($count <= $len) {
		$random = rand(1,strlen($char));
		$password.=substr($char,$random -1,1);
	$count++;
	} 
 
	if (!empty($password))
	    return $password;//echo $password;
}
//Registration functions
function checkIfUser($user)
{
	$sql = "SELECT user FROM users WHERE user = '" . $user ."' ";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$num = sqlNumRows($res);
 
	if ($num > 0)
		return true;
	return false;	
}
function checkIfEmail($email)
{
	if (isset($_SESSION["user"])) {
		$user = $_SESSION["user"];
		$sql = "SELECT * FROM users WHERE email = '" . $email ."' AND user = '" . $user ."'";
	} else {
		$sql = "SELECT * FROM users WHERE email = '" . $email ."' ";
	}
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$num = sqlNumRows($res);
	//$num = sqlResult($res,0,"NUMBER");
 
	if ($num > 0)
		return true;
	return false;	
}
function validatePhone($phone)
{
	if (preg_match('!^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$!', $phone))
		return true;
	return false;
}
function validateName($name)
{
	if (preg_match('!^([a-zA-Z]{3,60})$!', $name))
    	return true;
	return false;
}
function validateUsername($user)
{
	if (preg_match('!^\w+$!', $user))
    	return true;
	return false;
}
function validateEmail($email)
{
	if (preg_match("!^[a-zA-Z0-9]+([_\\.-][a-zA-Z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,4}$!", $email))
   		return true;
	return false;
}
//start user contributed functions verify by email[leowmjw]
function generateConfirmationID($user, $timestamp)
{
	$sql = "SELECT id FROM users WHERE user = '" . $user . "'";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	// if cannot get anything back; croak and die
	if ($a_row = sqlFetchArray($res)) {
		return $timestamp . "-" . $a_row["id"];
	} else {
		return false;
	}
}
function updateUsername($uid, $user)
{
	$uid = codeClean($uid);
	$user = codeClean($user);
	$sql = "UPDATE users SET user = '" . $user . "', activated = 1 WHERE id = '" .$uid . "'";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	// If succeed; return TRUE, else FALSE!!
	if (!empty($res))
		return $res;
	return false;
}
function getUsername($uid)
{
	$uid = codeClean($uid);
	$sql = "SELECT user FROM users WHERE id = '" . $uid ."'";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	// if cannot get anything back; croak and die
	if ($a_row = sqlFetchArray($res))
		return $a_row["user"];
	return false;
}
function activateProfile($confirmationID)
{
	// Purpose: Activate a registered Profile based on a unique confirmation number
	// Returns: TRUE if all check passes and username is updated correctly
	//          FALSE if any check fails or anything bad happens.
	//          Reasons to fail:
	//              timestamp does not match
	//              wrong format
	// Check that it fits the regexp for confirmationID -- ^[0-9]-[0-9]+$ => ^{timestamp}-{uid}$
	// [bkeep] Changed if (!eregi("^([0-9]+)-([0-9]+)$", $confirmationID, $regs)) { 
	if (!preg_match_all("!^([0-9]+)-([0-9]+)$!", $confirmationID, $regs)) {
		//$error_code = "Confirmation ID - $confirmationID - is not valid!";
		//return false;
		return 1;
	}
	// If it fits the profile; split the string to the timestamp component and uid component
	// First parenthesis is for timestamp; second parenthesis is for user ID
	$timestamp = $regs[1][0];
	$uid = $regs[2][0];
 
	// Pull out the record based on the uid and compare if it fits the regexp
	if ($user = getUsername($uid)) {
		// If does not fit the pattern; possibly this username has already been activated!!!
		// [bkeep] Changed if (!eregi("^<([0-9]+)>-([A-Z0-9]{5,20})$", $user, $regs)) {
		if (!preg_match_all("!^<([0-9]+)>-([a-zA-Z0-9]{5,60})$!", $user, $regs)) {
			//$error_code = "The username - $user - has been activated!  Please login with this username!";
			//return false;
			return 2;
		}
 
		// Now we have the correct username
		// Pull out the original username component from the matching regexp
		// First parenthesis is for timestamp; second parenthesis is for username
		$stored_timestamp = $regs[1][0];
		$user = $regs[2][0];
 
		// Update DB with correct username if timestamp matches
		if ($timestamp == $stored_timestamp) {
			// If $user already exists in the system; must re-register!
			$res = updateUsername($uid, $user);
			if (!$res) {
				//$error_code = "User $user already exists on the system.  " . 'Please re-register at the <a href="register.php">Registration Page</a> with another username.';
				//return false;
				return 3;
			} else {
				//return $res;
				return 99;
			}
		} else {
			//$error_code = "The timestamp does not match with the records!";
			//return false;
			return 4;
		}
	} else {
		//$error_code = "Invalid uid!";
		//return false;
		return 5;
	}
}
//end user contributed function [leowmjw]
function registerUser($user, $pass, $email, $first_name, $last_name, $phone, $alt_phone, $fax, $address, $city, $state, $zip, $agree)
{
	global $admin_name;
	global $admin_email;
	global $site_url;
	global $use_verify_email;
 
	//todo work out better error handling routine
	if (checkIfUser($user))	{
		return 1;
	} elseif (!validateEmail($email)) {
		return 2;
	} elseif (!validateUsername($user)) {
		return 3;
	} elseif (checkIfEmail($email)) {
		return 4;
	} elseif (empty($agree)) {
		return 5;
	} elseif (!validatePhone($phone)) {
		return 6;
	} elseif (!validateName($first_name)) {
		return 7;
	} elseif (!validateName($last_name)) {
		return 8;
	} else {
 
		//if blank password one is generated then the details are emailed
		if (empty($pass)) {
			$pass = generatePassword(6);
 
			// If email verification functionality is enabled
			if ($use_verify_email) { 
				$body = preg_replace("!%USERNAME%!","$user",ACCT_SIGNUP_BODY_VERIFY);
			} else {
 				$body = preg_replace("!%USERNAME%!","$user",ACCT_SIGNUP_BODY);
			}
		} else {
			// If email verification functionality is enabled
			if ($use_verify_email) {
				$body = preg_replace("!%USERNAME%!","$user",ACCT_SIGNUP_BODY_WPASS_VERIFY);
			} else {
				$body = preg_replace("!%USERNAME%!","$user",ACCT_SIGNUP_BODY_WPASS);
			}
 
			//build email to be sent from lang file
			$body = preg_replace("!%PASSWORD%!","$pass", $body);
			$body = preg_replace("!%URL%!","$site_url/login.php", $body);
			$subject = preg_replace("!%URL%!","$site_url",ACCT_SIGNUP_SUBJECT);
			$subject = preg_replace("!%USERNAME%!","$user", $subject);
			//The last part of the email is at the bottom!!
		}
 
	  	// Get remote IP
		$ipaddress = ipConvertLong(getenv('REMOTE_ADDR'));
		$reg_date = date("Y-m-d H:i:s");
 
	  	//Encrypt password for database
	    $salt = 's+(_a*';
		$pass = md5($pass.$salt);
 
		//Set the default activated status if not using the verify email functions
		$activated = 1;
 
		// If email verification functionality is enabled
		if ($use_verify_email) {
			// Mangle username with timestamp to make sure user confirm e-mail address.
			// After e-mail is confirmed; this username will be unmangled
			// This will also set the actived status to 0 awaiting a proper verification 
			$timestamp = time();
			$user = "<" . $timestamp . ">-" . $user;
			$activated = 0;
		}
 
		$sql = "INSERT INTO users (ipaddress,user,pass,email,first_name,last_name,phone,alt_phone,fax,address,city,state,zip,reg_date,activated) VALUES ('" . $ipaddress . "', '" . $user . "','" . $pass . "', '" . $email . "', '" . $first_name . "', '" . $last_name . "', '" . $phone . "', '" . $alt_phone . "', '" . $fax . "', '" . $address . "', '" . $city . "', '" . $state . "', '" . $zip . "', '" . $reg_date . "', '" . $activated . "')"; 
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
		// If email verification functionality is enabled
		if ($use_verify_email) {
			// ConfirmationID ==> timestamp.uid
			$cid = generateConfirmationID($user, $timestamp);
			// Put in the correctly generated confirmation URL into the
			$body = preg_replace("!%CONFIRMURL%!","$site_url/login.php?verify=$cid", $body);
		}
 
		// Send off the completed mail to user; with username and password in it.
		// Also will have confirmation URL if feature: validate email enabled.
		sendEmail($email,$subject,$body,$admin_name,$admin_email);
		return 99;
	}
}
function lastActive($user)
{
	global $visitor_tracking;
 
	$current_time = date("Y-m-d H:i:s");
	$ipaddress = ipConvertLong(getenv('REMOTE_ADDR'));
 
	//check if user is a guest or a logged in user
	//if logged in update the last active time in the users table and if activated the onlineusers table
	//if not logged in update the onlineusers table with correct guest info
	//checks for guest user first then checks if a user is logged in
 
	if (!empty($visitor_tracking) && $user == 'guest') {
		//guest is viewing check if already listed using their ip address in onlineusers table
		$sql = "SELECT ipaddress FROM onlineusers WHERE user = '" . $user . "' AND ipaddress = '" . $ipaddress . "'";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		$num = sqlNumRows($res);
		if ($num > 0) {
			//if check showed result then perform an update to the onlineusers table
			$sql = "UPDATE onlineusers SET last_active = '" . $current_time . "', ipaddress = '" . $ipaddress . "' WHERE user = '" . $user . "' AND ipaddress = '" . $ipaddress . "'";
			$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		} else {
			//if check failed insert result in to the onlineusers table
			$sql = "INSERT INTO onlineusers (user,last_active,ipaddress) VALUES ('" . $user . "', '" . $current_time . "', '" . $ipaddress . "')";
			$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		} 
	} elseif (!empty($visitor_tracking) && $user == $_SESSION["user"]) {
		//user is logged in check if they are listed in onlineusers table
		$sql = "SELECT user FROM onlineusers WHERE user = '" . $user . "'";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		$num = sqlNumRows($res);
		if ($num > 0) {
			//if check showed result then perform the update to the tables users and onlineusers
			$sql = "UPDATE users,onlineusers SET users.last_active = '" . $current_time . "', onlineusers.last_active = '" . $current_time . "' WHERE onlineusers.user = users.user";
			$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		} else {
			//if check failed insert result in the onlineusers table
			$sql = "INSERT INTO onlineusers (user,last_active,ipaddress) VALUES ('" . $user . "', '" . $current_time . "', '" . $ipaddress . "')";
			$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		}
	} else {
		//not using the visitor tracking feature so just update the last_active field for the user
		$sql = "UPDATE users SET last_active = '" . $current_time . "' WHERE user = '" . $user . "' ";
	}
 
	//perform some cleanup actions for the onlineusers table if visitor_tracking is enabled
	if (!empty($visitor_tracking)) {
		//now that we have checked the guest user or logged in user perform some cleanups of old dead userdata
		$sql = "SELECT * FROM onlineusers";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		$num = sqlNumRows($res);
 
		//print "".__LINE__." $sql, $num, I am $user this is my ip $ipaddress<br />";
		if ($num > 0) {
			while ($a_row = sqlFetchArray($res)) {
				$id = $a_row["id"];
		 		$last_active_time = $a_row["last_active"];
				//print $last_active_time;
 
				//if last active time is less than last active time plus 5 minutes
				$last_active_timestamp = strtotime($last_active_time);
				$current_timestamp = strtotime(date("Y-m-d H:i:s"));
				//print "<br />$last_active_timestamp";
				//print "<br />$current_timestamp";
 
				$time_diff = ($current_timestamp-$last_active_timestamp);
				//print "<br />$time_diff";
 
				$time_diff_minutes = date("i",$time_diff);
				//print "<br /> $time_diff_minutes<br />";
 
				//delete the row from onlineusers if the current time is greater than last_active_time by x minutes
				if ($time_diff_minutes >= 5) {
					$sql = "DELETE FROM onlineusers WHERE id = '" . $id . "'";
					$del = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
					//print "it worked there is a difference of $time_diff_minutes minutes<br />";
				} else {
					//print "it did not work there is only a difference of $time_diff_minutes minutes<br />";
				}
			}
		}
	}
}
//Admin Functions
//function updateEnv($url, $admin_name, $admin_email, $site_mode, $listings_per_page, $users_per_page, $listings_stored_path, $users_stored_path, $site_name, $description, $keywords, $site_lang, $site_template, $verify_email)
function updateEnv($env_data)
{
	foreach ($env_data as $field => $value ) {
		if ("$value" !== SUBMIT) {
			$fieldstr .= "$field = '" . $value . "', ";
		}
	}
	$fields = substr($fieldstr, 0, -2);
 
	$sql = "UPDATE env_settings SET $fields";
	//$sql = "UPDATE env_settings SET site_url = '" . $url . "', admin_name = '" . $admin_name . "', admin_email = '" . $admin_email . "', site_mode = '" . $site_mode . "', listings_per_page = " . $listings_per_page . ", users_per_page = " . $users_per_page . ", listings_stored_path = '" . $listings_stored_path . "', users_stored_path = '" . $users_stored_path . "', site_name = '" . $site_name . "', description = '" . $description . "', keywords = '" . $keywords . "', site_lang = '" . $site_lang . "', site_template = '" . $site_template . "', verify_email = '" . $verify_email . "' ";		
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	if (!empty($res))
		return 99;
	return false;
}
function deleteUser($id)
{
	$sql = "DELETE FROM users WHERE id = " . $id . ""; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	if (!empty($res))
		return 99;
	return false;
}
//function updateUserDetails($user, $email, $first_name, $last_name, $phone, $alt_phone, $fax, $address, $city, $state, $zip, $user_level, $admin_notes, $id)
function updateUserDetails($details)
{
	foreach ($details as $field => $value ) {
		if ($value !== UPDATE) {
			if ($field !== 'id') {
				$fieldstr .= "$field = '" . $value . "', ";
			}
		}
		if ("$field" == 'id') {
			$id = $value;
		}
	}
	$fields = substr($fieldstr, 0, -2);
 
	$sql = "UPDATE users SET $fields WHERE id = " . $id . "";
	//$sql = "UPDATE users SET user = '" . $user . "', email = '" . $email . "', first_name = '" . $first_name . "', last_name = '" . $last_name . "', phone = '" . $phone . "', alt_phone = '" . $alt_phone . "', fax = '" . $fax . "', address = '" . $address . "', city = '" . $city . "', state = '" . $state . "', zip = '" . $zip . "', user_level = '" . $user_level . "', admin_notes = '" . $admin_notes . "'  WHERE id = " . $id . "";		
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	if (!empty($res))
		return 99;
	return false;
}
//function to convert from INET_ATON http://www.ipligence.com/en/faq/
//select INET_NTOA('3515134258');
function ipConvert($ip)
{
	$b = array(0,0,0,0);
	$c = 16777216.0;
	$ip += 0.0;
	for ($i = 0; $i < 4; $i++) {
		$k = (int)($ip / $c);
		$ip -= $c * $k;
		$b[$i]= $k;
		$c /=256.0;
	}
	$d = join('.', $b);
	if (!isset($d))
		return $d;
	return false;
}
function ipConvertLong($ip)
{
	$d = 0.0;
	$b = explode(".", $ip,4);
	for ($i = 0; $i < 4; $i++) {
		$d *= 256.0;
		$d += $b[$i];
	}
	if (!isset($d))
		return $d;
	return false;
}
function getUserDetails($id)
{
	if (!empty($id) && $id == "all") {
		$sql = "SELECT * FROM users";
	} else {
		$sql = "SELECT * FROM users WHERE id = " . $id . "";  
	}
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		 $records[$c]["id"] = $a_row["id"];
		 $records[$c]["ipaddress"] = ipConvert($a_row["ipaddress"]);
		 $records[$c]["user"] = $a_row["user"];
		 $records[$c]["email"] = $a_row["email"];
		 $records[$c]["first_name"] = $a_row["first_name"];
		 $records[$c]["last_name"] = $a_row["last_name"];
		 $records[$c]["phone"] = $a_row["phone"];
		 $records[$c]["alt_phone"] = $a_row["alt_phone"];
		 $records[$c]["fax"] = $a_row["fax"];
		 $records[$c]["address"] = $a_row["address"];
		 $records[$c]["city"] = $a_row["city"];
		 $records[$c]["state"] = $a_row["state"];
		 $records[$c]["zip"] = $a_row["zip"];
		 $records[$c]["reg_date"] = $a_row["reg_date"];
		 $records[$c]["last_active"] = $a_row["last_active"];
		 $records[$c]["user_level"] = $a_row["user_level"];
		 $records[$c]["notes"] = $a_row["notes"];
		 $records[$c]["image"] = $a_row["image"];
		 $records[$c]["admin_notes"] = $a_row["admin_notes"];
	$c++;
	}
 
	if (!empty($id) && $id == "all") {
		//smarty paginate class used for users list in admin and also vehicle listings
		$paginate = new SmartyPaginate();
		$paginate->setTotal(count($records));
		if (!empty($records))
			return array_slice($records, $paginate->getCurrentIndex(), $paginate->getLimit());
	} elseif (isset($records)) {
		return $records; 
	}
}
//Image functions
function checkImageSize($tmpfile, $max)
{
	//check the tmpimage file size and see if it is to big returns true if to large
	$size = filesize($tmpfile);
	if ($size > $max)
		return true;
	return false;
}
function checkAllowedExt($file)
{
	//check file for allowed extensions returns true if wrong type
	$temp = strtolower($file);
	$ext_split = split("\.",$temp);
	$ext = $ext_split[1];
	$allowed = array('gif', 'jpg', 'jpeg', 'png');
	if (!in_array($ext, $allowed))
		return true;
	return false;
}
function deleteUserImage($user)
{
	//look up old image path then remove the file before preceding with the new image upload
	$sql = "SELECT image FROM users WHERE user = '" . $user . "'";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$row = sqlFetchAssoc($res);
	$del = $row["image"];
	if (!empty($del)) {
		$ext_split = split("\.",$del);
		$ext = $ext_split[1];
		$base = $ext_split[0];
 
		unlink("$del");
		unlink("$base" . "_thumb" . "." . "$ext");
 
		$sql = "UPDATE users SET image = ''  WHERE user = '" . $user . "'";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		return true;
	}
	return false;
}
function openImage($file)
{
	// Get extension and return it
	$temp = strtolower($file);
	$ext_split = split("\.",$temp);
	$ext = $ext_split[1];
	switch($ext) {
		case 'jpg':
		case 'jpeg':
			$im = @imagecreatefromjpeg($file);
			break;
		case 'gif':
			$im = @imagecreatefromgif($file);
			break;
		case 'png':
			$im = @imagecreatefrompng($file);
			break;
		default:
			$im = false;
			break;
	}
	return $im;
}
function createThumb($file, $ext, $width)
{
	$im    = openImage($file);
    $old_x = imageSX($im);
    $old_y = imageSY($im);
    $new_w = (int)($width);
 
	if (($new_w <= 0) or ($new_w>$old_x)) {
		$new_w=$old_x;
    }
 
    $new_h = ($old_x*($new_w/$old_x));
 
    if ($old_x > $old_y) {
        $thumb_w = $new_w;
        $thumb_h = $old_y*($new_h/$old_x);
    }
    if ($old_x < $old_y) {
        $thumb_w = $old_x*($new_w/$old_y);
        $thumb_h = $new_h;
    }
    if ($old_x == $old_y) {
		$thumb_w = $new_w;
		$thumb_h = $new_h;
    }
 
	$thumb = ImageCreateTrueColor($thumb_w,$thumb_h);
 
	if ($ext == 'png' || 'PNG') {
    	imagealphablending($thumb, false);
        $colorTransparent = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
        imagefill($thumb, 0, 0, $colorTransparent);
        imagesavealpha($thumb, true);
	} elseif ($ext == 'gif' || 'GIF') {
    	$trnprt_indx = imagecolortransparent($im);
        if ($trnprt_indx >= 0) {
        	//its transparent
            $trnprt_color = imagecolorsforindex($im, $trnprt_indx);
            $trnprt_indx = imagecolorallocate($thumb, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
            imagefill($thumb, 0, 0, $trnprt_indx);
            imagecolortransparent($thumb, $trnprt_indx);
		}
	}
 
    imagecopyresampled($thumb,$im,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
 
	//choose which image program to use
	if ($ext == 'jpeg' || 'jpg' || 'JPEG' || 'JPG') {
		imagejpeg($thumb,$file,75);
	} elseif ($ext == 'png' || 'PNG') {
		imagepng($thumb,$file,75);
	} elseif ($ext == 'gif' || 'GIF') {
		imagegif($thumb,$file,75);
	}
    imagedestroy($thumb);
}
function moveUploadImage($path, $file, $tmpfile, $max, $user)
{
	//upload your image and give it a random name so no conflicts occour
	$rand = mt_rand(1,3000);
	$save_path = $path . $user . $rand . $file;
 
	//move the temp file to the proper place
	if (move_uploaded_file($tmpfile, $save_path)) {
		$ext_split = split("\.",$save_path);
		$ext = $ext_split[1];
		$base = $ext_split[0];
 
		copy($save_path, "$base" . "_thumb" . "." . "$ext");
		createThumb("$base" . "_thumb" . "." . "$ext", $ext, 150);
		createThumb("$base" . "." . "$ext", $ext, 350);
 
		//chmod("$base" . "_thumb" . "." . "$ext", 0644);
		//chmod("$base" . "." . "$ext", 0644);
 
		return $save_path;
	}
	return false;
}
//upload the images for the members page
function uploadUserImage($path, $file, $tmpfile, $max, $user)
{
	if (empty($file))
		return false;
	if (checkImageSize($tmpfile, $max))
		return 1;
	if (checkAllowedExt($file))
		return 2;
 
	//look up old image path then remove the file before preceding with the new image upload
	$sql = "SELECT image FROM users WHERE user = '" . $user . "'";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$row = sqlFetchAssoc($res);
	$del = $row["image"];
	if (!empty($del)) {
		$ext_split = split("\.",$del);
		$ext = $ext_split[1];
		$base = $ext_split[0];
 
		unlink("$del");
		unlink("$base" . "_thumb" . "." . "$ext");
	}
 
	$save_path = moveUploadImage($path, $file, $tmpfile, $max, $user);
	if (isset($save_path)) {
		$sql = "UPDATE users SET image = '" . $save_path . "'  WHERE user = '" . $user . "'";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		return 99;
	}
	return false;
}
//upload the images for the listings pages
function uploadListImage($path, $file, $tmpfile, $max, $listingid, $user, $owner)
{
	if (empty($file))
		return false;
	if (checkImageSize($tmpfile, $max))
		return 1;
	if (checkAllowedExt($file))
		return 2;
 
	//see if listing already has main image set if not set image as main
	$sql = "SELECT * FROM listimages WHERE listingid = " . $listingid ." AND mainimage = 1";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$num = sqlNumRows($res);
 
	$save_path = moveUploadImage($path, $file, $tmpfile, $max, $user);
	$ext_split = split("\.",$save_path);
	$ext = $ext_split[1];
	$base = $ext_split[0];
	$save_thumb_path = "$base" . "_thumb" . "." . "$ext";
 
	//set default image status
	$approved = 0;
 
	if ($num > 0) {
		if (isset($save_path)) {
			$sql = "INSERT INTO listimages (imagepath,imagethumbpath,listingid,owner,approved) VALUES ('" . $save_path . "','" . $save_thumb_path . "', " . $listingid . ", '" . $owner . "', " . $approved . ")";
			$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
			return 99;
		}
	} else {
		if (isset($save_path)) {
			$sql = "INSERT INTO listimages (imagepath,imagethumbpath,mainimage,listingid,owner,approved) VALUES ('" . $save_path . "','" . $save_thumb_path . "',1, " . $listingid . ", '" . $owner . "', " . $approved . ")";
			$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
			return 99;
		}
	}
	return false;
}
function approveImage($listingid, $imageid)
{
	if (isset($listingid) && isset($imageid)) {
		//check if already main and unset
		$sql = "SELECT id FROM listimages WHERE listingid = " . $listingid . " AND id = '" . $imageid . "'";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		$num = sqlNumRows($res);
		if (!empty($num)) {
			$row = sqlFetchAssoc($res);
			$setimageid = $row["id"];
 
			$sql = "UPDATE listimages SET approved = 1 WHERE id = " . $setimageid . "";
			$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
			if (!$res)
				return false;
			return 99;
		}
	}
	return false;
}
function markImageMain($listingid, $imageid, $owner)
{
	if (isset($listingid) && isset($imageid) && !empty($owner)) {
		//check if already main and unset
		$sql = "SELECT id FROM listimages WHERE listingid = " . $listingid . " AND owner = '" . $owner . "' AND mainimage = 1";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		$num = sqlNumRows($res);
		if (!empty($num)) {
			$row = sqlFetchAssoc($res);
			$setimageid = $row["id"];
 
			$sql = "UPDATE listimages SET mainimage = 0 WHERE id = " . $setimageid . "";
			$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		} else {
			//return false;
			// Possibly, this happens when mainimage is deleted
            // Correct approach would be to mark this image as main!
			$sql = "UPDATE listimages SET mainimage = 1  WHERE id = " . $imageid . "";
			$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
			if (!$res)
				return false;
			return 99;
		}
 
		$sql = "UPDATE listimages SET mainimage = 1  WHERE id = " . $imageid . "";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		if (!$res)
			return false;
		return 99;
	}
}
function deleteFullListing($listingid)
{
	$sql = "DELETE FROM listings WHERE id = " . $listingid . ""; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$sql = "SELECT * FROM listimages WHERE listingid = " . $listingid . ""; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		if (!empty($a_row["imagepath"]))
			unlink($a_row["imagepath"]);
		if (!empty($a_row["imagethumbpath"]))
			unlink($a_row["imagethumbpath"]);
	$c++;
    }
 
	$sql = "DELETE FROM listimages WHERE listingid = " . $listingid . ""; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	return 99;	
}
function deleteListingsImage($id, $imageid, $owner)
{
	if (isset($id) && isset($imageid) && !empty($owner)) {
		//look up image path then remove the files before preceding
		$sql = "SELECT imagepath,imagethumbpath FROM listimages WHERE id = " . $imageid . " AND owner = '" . $owner . "' LIMIT 1";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		$num = sqlNumRows($res);
		if (!empty($num)) {
			$row = sqlFetchAssoc($res);
			$imagepath = $row["imagepath"];
			$imagethumbpath = $row["imagethumbpath"];
		} else {
			return false;
		}
	}
 
	if (!empty($imagepath)) {
		unlink("$imagepath");
		unlink("$imagethumbpath");
 
		$sql = "DELETE FROM listimages WHERE id = " . $imageid . "  AND owner = '" . $owner . "'";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		return 99;
	}
	return false;
}
function getListingTitle ($listingid) 
{
	$sql = "SELECT ad_title FROM listings WHERE id = " . $listingid . " LIMIT 1";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$row = sqlFetchAssoc($res);
 
	$title = $row["ad_title"];
 
	if (isset($title))
		return $title;
}
function getRandomImage()
{
	$limit = 6;
	$sql = "SELECT * FROM listimages, listings WHERE listings.id = listimages.listingid AND listings.sold !=1 AND listings.approved = 1 AND listimages.approved = 1 AND listimages.mainimage = 1 ORDER BY RAND() LIMIT $limit";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		$records[$c]["ad_title"] = getListingTitle($a_row["listingid"]);
		$records[$c]["listingid"] = $a_row["listingid"];
		$records[$c]["imagepath"] = $a_row["imagepath"];
		$records[$c]["imagethumbpath"] = $a_row["imagethumbpath"];
	$c++;
    }
	if (isset($records))
		return $records;
}
function getListImages($listingid)
{
	global $use_listing_activation;
 
	if (!empty($use_listing_activation)) {
		if (!isset($_SESSION["admin"])) {
			$approved = "approved = 1 AND ";
		}
 
		$sql = "SELECT seller FROM listings WHERE id = " . $listingid . " LIMIT 1";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		$a_row = sqlFetchAssoc($res);
		if ($a_row["seller"] == $_SESSION["user"]) {
			$approved = "";
		}
	}
 
	//look up image path for listing
	$sql = "SELECT * FROM listimages WHERE $approved listingid = " . $listingid . "";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		$records[$c]["id"] = $a_row["id"];
		$records[$c]["imagepath"] = $a_row["imagepath"];
		$records[$c]["imagethumbpath"] = $a_row["imagethumbpath"];
		$records[$c]["mainimage"] = $a_row["mainimage"];
		$records[$c]["listingid"] = $a_row["listingid"];
		$records[$c]["approved"] = $a_row["approved"];
	$c++;
	}
	if (isset($records))
		return $records;
}
function getListing($id='all', $addOnSQL="", $sellerid="", $sort="")
{
	global $use_listing_activation;
 
	if (empty($sort))
		$sort = "ORDER BY sold,id DESC";
 
	if (!empty($use_listing_activation)) {
		if (!isset($_SESSION["admin"])) {
			$approved = "WHERE approved = 1";
		}
		if ($sellerid == getSellerId($_SESSION["user"])) {
			$no_seller_list = "approved = 1 AND";
		}
	}
 
	if (!empty($id) && $id == "all") {
		$sql = "SELECT * FROM listings $approved $sort"; 
	} elseif (!empty($addOnSQL)) {
		$sql = "SELECT * FROM listings WHERE $no_seller_list $addOnSQL $sort";
	} else {
		$sql = "SELECT * FROM listings WHERE id = " . $id . " LIMIT 1";  
	}
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		$records[$c]["id"] = $a_row["id"];
		$records[$c]["approved"] = $a_row["approved"];
		$records[$c]["sold"] = $a_row["sold"];
		$records[$c]["featured"] = $a_row["featured"];
		$records[$c]["ad_title"] = $a_row["ad_title"];
		$records[$c]["make"] = $a_row["make"];
		$records[$c]["model"] = $a_row["model"];
		$records[$c]["vehicle_type"] = $a_row["vehicle_type"];
		$records[$c]["doors"] = $a_row["doors"];
		$records[$c]["color"] = $a_row["color"];
		$records[$c]["mileage"] = $a_row["mileage"];
		$records[$c]["year"] = $a_row["year"];
		$records[$c]["listing_condition"] = $a_row["listing_condition"];
		$records[$c]["engine"] = $a_row["engine"];
		$records[$c]["trans"] = $a_row["trans"];
		$records[$c]["drive_train"] = $a_row["drive_train"];
		$records[$c]["mpg"] = $a_row["mpg"];
		$records[$c]["fuel_type"] = $a_row["fuel_type"];
		$records[$c]["price"] = $a_row["price"];
		$records[$c]["adddesc"] = $a_row["adddesc"];
		$records[$c]["features"] = unserialize($a_row["features"]);
		$records[$c]["vin"] = $a_row["vin"];
		$records[$c]["stock"] = $a_row["stock"];
		$records[$c]["state"] = $a_row["state"];
		$records[$c]["zip"] = $a_row["zip"];
		$records[$c]["sellerid"] = $a_row["sellerid"];
		$records[$c]["seller"] = $a_row["seller"];
		$records[$c]["added_on"] = $a_row["added_on"];
		$records[$c]["last_updated"] = $a_row["last_updated"];
		$records[$c]["images"] = getListImages($a_row["id"]);
	$c++;
	}
 
	if (!empty($id) && $id == "all" || !empty($addOnSQL)) {
		//smarty paginate class used for users list in admin and also vehicle listings
		$paginate = new SmartyPaginate();
		$paginate->setTotal(count($records));
		if (!empty($records))
    		return array_slice($records, $paginate->getCurrentIndex(), $paginate->getLimit());
	} elseif (isset($records)) {
		return $records; 
	}
}
//add classifieds options
function addOption($option, $table)
{
	//check if empty if empty return no good
	if (empty($option))
		return false;
 
	//check if option already exists if it does return an error
	$sql = "SELECT * FROM $table WHERE $table = '" . $option ."'";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$num = sqlNumRows($res);
	if ($num > 0) {
		return 1;
	} else {
		//if the option is not empty and does not exist then add it
		$sql = "INSERT INTO $table ($table) VALUES ('" . $option . "')"; 
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		return 99;
	}
}
//get search list data for search page
function getSearchList($table)
{
	global $use_listing_activation;
	if (!empty($use_listing_activation))
			$approved = "WHERE approved = 1";
 
	$sql = "SELECT DISTINCT $table FROM listings $approved ORDER by $table"; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		 $searchlist[$c]["$table"] = $a_row["$table"];
	$c++;
    }
	if (isset($searchlist))
		return $searchlist;
}
//Get option information lists
function getStatesList()
{
	$sql = "SELECT * FROM states ORDER by state_name"; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		 $stateslist[$c]["state_prefix"] = $a_row["state_prefix"];
		 $stateslist[$c]["state_name"] = $a_row["state_name"];
	$c++;
    }
	if (isset($stateslist))
		return $stateslist;
}
function getTableDataList($table)
{
	$sql = "SELECT * FROM $table ORDER by '" . $table ."'"; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		 $records[$c]["id"] = $a_row["id"];
		 $records[$c]["$table"] = $a_row["$table"];
	$c++;
    }
	if (isset($records))
		return $records;
}
function getFeaturesList()
{
	$sql = "SELECT * FROM features ORDER by features"; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		 $featurelist[$c]["id"] = $a_row["id"];
		 $featurelist[$c]["features"] = $a_row["features"];
		 $featurelist[$c]["lists_default"] = $a_row["lists_default"];
	$c++;
    }
	if (isset($featurelist))
		return $featurelist;
}
function getSingleOption($table, $id)
{
	$sql = "SELECT * FROM $table WHERE id = " . $id . ""; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$row = sqlFetchRow($res);
	if (isset($row)) 
		return $row;
	return false;
}
function updateSingleOption($table, $data, $id, $lists_default)
{
	//check if var for default list is set
	if (isset($lists_default)) {
		$sql = "UPDATE $table SET lists_default = '" . $lists_default . "', $table = '" . $data . "' WHERE id = " . $id . "";		
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		return 99;
	//otherwise update without it
	} else {
		$sql = "UPDATE $table SET $table = '" . $data . "' WHERE id = " . $id . "";		
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		return 99;
	}
}
function deleteOption($table, $id)
{
		$sql = "DELETE FROM $table WHERE id = " . $id . "";		
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		return 99;
}
//gotta do something different here its getting out of hand
function updateListing($id, $ad_title, $make, $model, $vehicle_type, $doors, $color, $mileage, $year, $listing_condition, $engine, $trans, $drive_train, $mpg, $fuel_type, $price, $adddesc, $features, $vin, $stock, $state, $zip, $sold, $sellerid, $seller)
{
	if (empty($model))
		return false;
 
	if (strpos($adddesc, "&") !== false) {
    	return false;
	} elseif (strlen(strip_tags($adddesc)) < strlen($adddesc)) {
    	return false;
	}
 
	//set activation status to not approved since listing was updated
	$approved = 0;
 
	if (!empty($model)) {
		$sql = "UPDATE listings SET approved = '" . $approved . "', ad_title = '" . $ad_title . "', make = '" . $make . "', model = '" . $model . "', vehicle_type = '" . $vehicle_type . "', doors = '" . $doors . "', color = '" . $color . "', mileage = '" . $mileage . "', year = '" . $year . "', listing_condition = '" . $listing_condition . "', engine = '" . $engine . "', trans = '" . $trans . "', drive_train = '" . $drive_train . "', mpg = '" . $mpg . "', fuel_type = '" . $fuel_type . "', price = '" . $price . "', adddesc = '" . $adddesc . "', features = '" . $features . "', vin = '" . $vin . "', stock = '" . $stock . "', state = '" . $state . "', zip = '" . $zip . "', sold = '" . $sold . "', sellerid = '" . $sellerid . "', seller = '" . $seller . "' WHERE id = " . $id . "";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		return 99;
	}
	return false;
}
function addListing($ad_title, $make, $model, $vehicle_type, $doors, $color, $mileage, $year, $listing_condition, $engine, $trans, $drive_train, $mpg, $fuel_type, $price, $adddesc, $features, $vin, $stock, $state, $zip, $sellerid, $seller)
{
	if (empty($model))
		return false;
 
	if (strpos($adddesc, "&") !== false) {
    	return false;
	} elseif (strlen(strip_tags($adddesc)) < strlen($adddesc)) {
    	return false;
	}
 
	//set default activation status
	$approved = 0;
 
	$added_on = date('Y-m-d h:i');
 
	if (!empty($model)) {
		$sql = "INSERT INTO listings (approved, ad_title, make, model, vehicle_type, doors, color, mileage, year, listing_condition, engine, trans, drive_train, mpg, fuel_type, price, adddesc, features, vin, stock, state, zip, sellerid, seller, added_on) VALUES ('" . $approved . "', '" . $ad_title . "', '" . $make . "', '" . $model . "', '" . $vehicle_type . "', '" . $doors . "', '" . $color . "', '" . $mileage . "', '" . $year . "', '" . $listing_condition . "', '" . $engine . "', '" . $trans . "', '" . $drive_train . "', '" . $mpg . "', '" . $fuel_type . "', '" . $price . "', '" . $adddesc . "', '" . $features . "', '" . $vin . "', '" . $stock . "', '" . $state . "', '" . $zip . "', '" . $sellerid . "', '" . $seller . "', '" . $added_on . "')";
		$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		return 99;
	}
	return false;
}
function getUserId($user)
{
	$sql = "SELECT id FROM users WHERE user = '" . $user . "' LIMIT 1";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	if (!empty($res)) {
		$row = sqlFetchAssoc($res);
		$id = $row["id"];
		//$id = sqlResult($res,0,"id");
		return $id;
	} else {
		return false;
	}
}
function getSellerId($user)
{
	$sql = "SELECT id FROM users WHERE user = '" . $user . "' AND user_level = 2 LIMIT 1";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	if (!empty($res)) {
		$row = sqlFetchAssoc($res);
		$id = $row["id"];
		//$id = sqlResult($res,0,"id");
		return $id;
	} else {
		return false;
	}
}
function getSellers()
{
	$sql = "SELECT * FROM users WHERE user_level = 2"; 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		$records[$c]["id"] = $a_row["id"];
		$records[$c]["user"] = $a_row["user"];
		$records[$c]["first_name"] = $a_row["first_name"];
		$records[$c]["last_name"] = $a_row["last_name"];
	$c++;
    }
	if (isset($records))
		return $records;
}
function getSellerEmail($seller)
{
	$sql = "SELECT email FROM users WHERE id = " . $seller . " AND user_level = 2 LIMIT 1";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	if (!empty($res)) {
		$row = sqlFetchAssoc($res);
		$id = $row["email"];
		//$email = sqlResult($res,0,"email");
		return $email;
	} else {
		return false;
	}
}
//Statistics functions used for counting all vehicles, sold vehicles etc...
function getTotalUserCountStatistics($active_status)
{
	global $visitor_tracking;
 
	//check online status of listings
	if (!empty($active_status) && $active_status == 'active') {
		$sql = "SELECT user FROM users WHERE activated = 1";
	} elseif (!empty($active_status) && $active_status == 'pending') {
		$sql = "SELECT user FROM users WHERE activated !=1";
 
	//check online status of guests or registered users
	} elseif (!empty($active_status) && $active_status == 'sellers') {
		$sql = "SELECT user FROM users WHERE user_level = 2";
	} 
	if (!empty($visitor_tracking)) {
		if (!empty($active_status) && $active_status == 'online') {
			$sql = "SELECT * FROM onlineusers WHERE user != 'guest'";
		} elseif (!empty($active_status) && $active_status == 'guest') {
			$sql = "SELECT * FROM onlineusers WHERE user = 'guest'";
		}
	}
 
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$num = sqlNumRows($res);
 
	if (isset($num))
		return $num;
}
function getVehicleCountStats()
{
	$sql = "SELECT DISTINCT make FROM listings";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		$inner_sql = "SELECT make FROM listings WHERE make = '" . $a_row["make"] . "'";
		$inner_res = sqlQuery($inner_sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
		$inner_num = sqlNumRows($inner_res);
 
		$records[$c]["make"] = $a_row["make"];
		$records[$c]["num"] = $inner_num;
	$c++;
	}
 
	if (!empty($records))
	    return $records;
}
function getVehiclePriceStats($min_price, $max_price)
{
	$sql = "SELECT * FROM listings WHERE price >= '" . number_format($min_price, 2, ".", "") . "' AND price <= '" . number_format($max_price, 2, ".", "") . "'";
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
 
	$c=0;
	while ($a_row = sqlFetchArray($res)) {
		$records[$c]["min_price"] = $min_price;
		$records[$c]["max_price"] = $max_price;
		$records[$c]["num"] = sqlNumRows($res);
	$c++;
	}
 
	if (!empty($records))
	    return $records;
}
function getTotalVehicleCount($active_status)
{
	if (!empty($active_status) && $active_status == 'sold') {
		$sql = "SELECT * FROM listings WHERE sold =1";
	} else {
		$sql = "SELECT * FROM listings";
	}
	$res = sqlQuery($sql); if(sqlErrorReturn()) sqlDebug(__FILE__,__LINE__,sqlErrorReturn());
	$num = sqlNumRows($res);
 
	if (isset($num))
		return $num;
}

Is Required by

The following pages include this page as a required include.

  • addlisting.php
  • contact.php
  • editlisting.php
  • index.php
  • listings.php
  • FIXME
 
Structure/Files/functions.php.txt · Last modified: 2011/12/30 02:56 (external edit)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki