<?php
#####################################
#	Convert IP to Location			#
#####################################
if(!function_exists('ip2location')) {
	function ip2location($ipaddress,$db)
	{
		$location = array();
		$ipnum = Dot2LongIP($ipaddress);
		$selectsql = "SELECT countryLONG,ipREGION,ipCITY,ipLATITUDE,ipLONGITUDE FROM IPCITYLATLONG WHERE (ipFROM <= $ipnum) ORDER BY ipFROM DESC LIMIT 1";

		if ($result = mysql_query($selectsql,$db))
			if($row=mysql_fetch_assoc($result))
				$location=array("Country" => $row["countryLONG"],"Region"=>$row["ipREGION"],"City"=>$row["ipCITY"],"Latitude"=>$row["ipLATITUDE"],"Longitude"=>$row["ipLONGITUDE"]);

		if(count($location) > 0)
			return $location;
		else
			return 0;
	}
}

if (!function_exists('ip2location_V2')) {

    function ip2location_V2($ipaddress, $db)
    {
        $location = array();
        $ipnum = Dot2LongIP($ipaddress);
        $selectsql = "SELECT countryLONG, ipREGION, ipCITY, ipLATITUDE, ipLONGITUDE 
                      FROM IPCITYLATLONG 
                      WHERE (ipFROM <= $ipnum) 
                      ORDER BY ipFROM DESC 
                      LIMIT 1";

        if ($result = mysqli_query($db, $selectsql)) {
            if ($row = mysqli_fetch_assoc($result)) {
                $location = array(
                    "Country"   => $row["countryLONG"],
                    "Region"    => $row["ipREGION"],
                    "City"      => $row["ipCITY"],
                    "Latitude"  => $row["ipLATITUDE"],
                    "Longitude" => $row["ipLONGITUDE"]
                );
            }

        }
        if (count($location) > 0) {
            return $location;
        } else {
            return 0;
        }
    }
}

if(!function_exists('EnvoyIp2location')) {
	function EnvoyIp2location($ipaddress,$db)
	{
		if(stristr($ipaddress,"192.168.") || $ipaddress=="74.62.32.106"){
			$ipaddress = "66.214.191.226";
		}
		$location=array();
		$selectsql="select country,state,city, latitude, longitude, metro_code from envoyip where inet_aton('$ipaddress') <= endip limit 1;";
		if ($result = mysql_query($selectsql,$db)){
			if($row=mysql_fetch_assoc($result)){
				$location=array("country"=>$row["country"],"state"=>$row["state"],"city"=>$row["city"], "latitude"=>$row["latitude"], "longitude"=>$row["longitude"], "metro_code"=>$row['metro_code']);
			}
		}
		if(count($location)>0)
			return $location;
		else
			return 0;
	}
}

#####################################
#	Convert IP to Long format		#
#####################################
if(!function_exists('Dot2LongIP')) {
	function Dot2LongIP ($IPaddr)
	{
		if ($IPaddr == "")
			return 0;
		else {
			$ips = explode ("\.", "$IPaddr");
			return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
		}
	}
}

#####################################
#			Curl URL				#
#####################################
if(!function_exists('curl_get_contents')) {
	function curl_get_contents($CurlData)
	{
		##### FETCH INPUT #####
		if (is_array($CurlData))
			$URL = $CurlData['url'];
		else
			$URL = $CurlData;
		
		if ($CurlData['timeout'])
			$Timeout = $CurlData['timeout'];
		else
			$Timeout = 5;
				
		###### INIT ############
		$ch = curl_init($URL);
		###### CURL & OPTION #####
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_TIMEOUT, $Timeout);
		if($CurlData['login'])
			curl_setopt($ch, CURLOPT_USERPWD, $CurlData['login']);
		if($CurlData['ua'])
			curl_setopt($ch, CURLOPT_USERAGENT, $CurlData['ua']);
		if($CurlData['Authorization'])
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$CurlData['Authorization']));
		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}
}

###########################################
#	Get Cities within a provided State	  #
###########################################
if(!function_exists('GetCitiesFromState')) {
	function GetCitiesFromState($ShortState,$db)
	{
		$query = "select city FROM us_city_state WHERE state = '$ShortState'
		ORDER BY city
		limit 600 ";
		$result = mysql_query($query, $db);
		while($row = mysql_fetch_assoc($result))
			$Data[] = $row['city'];
			
		return $Data;
	}
}

/**********************************
///Get long state from short//
**********************************/
if(!function_exists('StateShort2Long')) {
	function StateShort2Long($ShortState,$dbd){

		$query = "select state_name FROM zip_codes WHERE state_abbr like '$ShortState' OR state_name like '$ShortState' LIMIT 1";
		$result = mysql_query($query, $dbd);
		$row=mysql_fetch_assoc($result);

		if ($row['state_name'])
			return $row['state_name'];
		else
			return $ShortState;

	}
}

/**********************************
///Get long state from short//
**********************************/
if(!function_exists('StateLong2Short')) {
	function StateLong2Short($LongState,$dbd){

		$query = "select state_abbr  FROM zip_codes WHERE  state_abbr like '$LongState' OR state_name like '$LongState' LIMIT 1";
		$result = mysql_query($query, $dbd);
		$row=mysql_fetch_assoc($result);

		if ($row['state_abbr'])
			return $row['state_abbr'];
		else
			return $LongState;
	}
}
/**********************************
//// City/state From Zipcode//
**********************************/
if(!function_exists('getCityFromZip')) {
	function getCityFromZip($zip,$dbd){

		$query = "select zipcode,lat,lon,state_abbr,city_name from zip_codes where zipcode like '$zip' limit 1";
		$result = mysql_query($query, $dbd);
		$row=mysql_fetch_assoc($result);
		
		if ($row)
			return $row;
	}
}
/**********************************
//// City/state From Zipcode//
**********************************/
if(!function_exists('getZipFromCity')) {
	function getZipFromCity($city, $state, $dbd){

		$query = "select zipcode,lat,lon,state_abbr,city_name from zip_codes where city_name = '$city' AND state_abbr = '$state' limit 1";
		$result = mysql_query($query, $dbd);
		$row=mysql_fetch_assoc($result);

		if ($row)
			return $row;
	}
}
/**********************************
////city to lat,long conversion////
**********************************/
if(!function_exists('place2latlon')) {
	function place2latlon($place,$dbd)
	{
		if (   strlen($place) == 5 && is_number($place)){
			 	return (zip2latlon($place, $dbd));
		} elseif ((strlen($place)==3) && is_number($place)){
				return(area2latlon($place, $dbd));
		}

		$locationarray = array();
		$locationarray = explode(",",$place);
		$count = count($locationarray);
		
		if ($count >= 2){
			$city = trim($locationarray[$count-2]);
			$state = trim($locationarray[$count-1]);
		} else {
			$city = trim($locationarray[$count-1]);
		}

		if ($state){
			$query = "select zipcode, lat,lon,state_abbr,city_name from zip_codes where city_name like '$city' and (state_abbr like '$state' or state_name like '$state') limit 1";
		} else {
			$query =  "select zipcode, lat, lon, state_abbr, city_name, count(*) from zip_codes where city_name like '$city' group by state_abbr order by count(*) desc limit 1";
		}
		$result = mysql_query($query, $dbd);
		$row=mysql_fetch_assoc($result);

		if ($row)
			return $row;
	}
}
/**********************************
///////latitude to distance ///////
**********************************/
if(!function_exists('latmin')) {
	function latmin($latitude,$distance = 5){
		
		$latmin = ($latitude - $distance/69.1);
		return $latmin;
	}
}
/**********************************
///////latitude to distance ///////
**********************************/
if(!function_exists('latmax')) {
	function latmax($latitude,$distance = 5){

		$latmax = ($latitude + $distance/69.1);
		return $latmax;
	}
}
/***********************************
///////longitude to distance ///////
**********************************/
if(!function_exists('lonmin')) {
	function lonmin($longitude,$distance = 5)
	{
		$lonmin = ($longitude - $distance/53.0 );
		return $lonmin;
	}
}
/***********************************
///////longitude to distance ///////
**********************************/
if(!function_exists('lonmax')) {
	function lonmax($longitude,$distance = 5){
		
		$lonmax = ($longitude + $distance/53.0);
		return $lonmax;
	}
}
/**********************************
////Get List of City close to a specific city//
**********************************/
if(!function_exists('GetNearCity')) {
	function GetNearCity($city,$state,$dbd){

		$query = "SELECT distinct(ipCITY) as NearCity  FROM `IPCITYLATLONG` WHERE ipREGION = '$state' limit 25";
		$result = mysql_query($query, $dbd);
		
		if ($result)
			return $result;
	}
}
/************************************
////search businesses using lat long//
************************************/
if(!function_exists('SearchLocalListing')) {
	function SearchLocalListing($search,$dbd,$latmin,$latmax,$lonmin,$lonmax,$resultcount = 10){

	        $searchresult = array();
			
			$search_query = $search;
			$terms = explode(' ', trim($search_query));
			$like = '';
			foreach($terms as $term) {
				$like .= 'bname like \'%'.$term.'%\' or ';
			}
			$like = rtrim($like, ' or ');

	        $searchq = str_replace (' ','%',$search);
	        $searchq = str_replace ("'","''",$searchq);
	        //$query = "select lat,lon,biz_id from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax and bname like '%$searchq%' limit 150";
			//$query = "select lat,lon,biz_id from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax and match(bname) against('$searchq' in boolean mode) limit 150";
			$query = "select SQL_NO_CACHE * from local_pages_lat_lon_updated WHERE MBRCONTAINS(LINESTRING(point($latmin,$lonmin), point($latmax,$lonmax)), pnt) and duplicate=0 and ($like) limit 150";
			
			$result = mysql_query($query, $dbd);

	        while ($row = mysql_fetch_assoc($result)) {
	                $searchresult[] = $row;
	        }

	      if (count($searchresult) > 10){
	              return $searchresult;
	      } else {
							$terms = explode(' ', trim($search_query));
							$like = '';
							foreach($terms as $term) {
								$like .= 'keywords like \'%'.$term.'%\' or ';
							}
							$like = rtrim($like, ' or ');
	                        //$query = "select lat,lon,biz_id from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax and  keywords like '%$searchq%' limit 50";
							//$query = "select lat,lon,biz_id from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax and match(keywords) against('$searchq' in boolean mode) limit 50";
	                        $query = "select SQL_NO_CACHE * from local_pages_lat_lon_updated WHERE MBRCONTAINS(LINESTRING(point($latmin,$lonmin), point($latmax,$lonmax)), pnt) and duplicate=0 and ($like) limit 50;";
							$result = mysql_query($query, $dbd);
	                        while ($row = mysql_fetch_assoc($result)) {
	                                $searchresult[] = $row;
	                        }
	      }

	#        $splitkeyword = array();
	#        $splitkeyword = explode(" ", $search);
	#
	#        if (count($searchresult) > 100){
	#                return $searchresult;
	#        } else {
	#                        $query1 = "select lat,lon,biz_id from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax  ";
	#                        for ($j=0; $j < count($splitkeyword);$j++){
	#                                $query1 .= " and bname like '%";
	#                                $query1 .= $splitkeyword[$j];
	#                                $query1 .=      "%'";
	#                        }
	#                        $query1 .= " limit 50";
	#                        $result = mysql_query($query1, $dbd);
	#                        while ($row = mysql_fetch_assoc($result)) {
	#                                $searchresult[] = $row;
	#                        }
	#        }
	#
	#        if (count($searchresult) > 100){
	#                return $searchresult;
	#        } else {                        $query1 = "select lat,lon,biz_id from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax  ";
	#                        for ($j=0; $j < count($splitkeyword);$j++){
	#                                $query1 .= " and keywords like '%";
	#                                $query1 .= $splitkeyword[$j];
	#                                $query1 .=      "%'";
	#                        }
	#                        $query1 .= " limit 50";
	#                        $result = mysql_query($query1, $dbd);
	#                        while ($row = mysql_fetch_assoc($result)) {
	#                                $searchresult[] = $row;
	#                        }
	#        }
	#
	#        if (count($searchresult) > 100){
	#                return $searchresult;
	#        } elseif ($splitkeyword[0]) {                        $query2 = "select lat,lon,biz_id from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax and  bname like '$splitkeyword[0]%'";
	#                        $query2 .= " limit 50";
	#                        $result = mysql_query($query2, $dbd);
	#                        while ($row = mysql_fetch_assoc($result)) {
	#                                $searchresult[] = $row;                        }
	#        }
	#
	#        if (count($searchresult) > 100){
	#                return $searchresult;
	#        } elseif ($splitkeyword[1]) {                        $query2 = "select lat,lon,biz_id from local_pages_lat_lon_updated where lat between $latmin and $latmax and lon between $lonmin and $lonmax and  bname like '$splitkeyword[1]%'";
	#                        $query2 .= " limit 50";
	#
	#                        $result = mysql_query($query2, $dbd);
	#                        while ($row = mysql_fetch_assoc($result)) {
	#                                $searchresult[] = $row;
	#                        }
	#        }

	//      if (count($searchresult) > $resultcount){
	//              return $searchresult;
	//      } elseif ($splitkeyword[1]){//                      $query3 = "select lat,lon,biz_id from local_pages_lat_lon_updated where lat between $latmin and $latmax and abs(lon) between abs($lonmax) and abs($lonmin) and keywords like '%$splitkeyword[1]%'";
	//                      $query2 .= " limit $resultcount";
	//                      $result = mysql_query($query3);
	//                      while ($row = mysql_fetch_assoc($result)) {
	//                              $searchresult[] = $row;
	//                      }
	//
	//      }
	        return $searchresult;
	}
}
/**********************************
////////lookup business ids////////
**********************************/
if(!function_exists('SearchLocalListingBusiness')) {
	function SearchLocalListingBusiness($results, $start, $count, $dbd){

		$bizresult = array();
		$searchresult = array();
		
		if($start == 1)
			$start = 0;
		else
			$start = $start*$count;
				
		for ($i=$start, $inc = 0;$i< $count+$start && $results[$i] ;$i++, $inc++)
		{
			//$startLoop = microtime(true);

			//echo $results[$i]['biz_id']." - ";
			$query = "select id, business_name,full_address,city,state,zip,phone,phone_code, LAT, LON from local_pages_biz_updated where id = ". $results[$i]['biz_id']." limit 1";

			$result = mysql_query($query,  $dbd);

			while ($row = mysql_fetch_assoc($result))
			{
				$searchresult[$inc]['business_name'] = $row['business_name'];
				$searchresult[$inc]['address1'] = $row['full_address'];

				$searchresult[$inc]['biz_id'] = $row['id'];
				$searchresult[$inc]['city'] = $row['city'];
				$searchresult[$inc]['state'] = $row['state'];
				$searchresult[$inc]['zip'] = $row['zip'];
				$searchresult[$inc]['lat'] = $row['LAT'];//$results[$i]['lat'];
				$searchresult[$inc]['lon'] = $row['LON'];//$results[$i]['lon'];
				$searchresult[$inc]['area_code'] = $row['phone_code'];
				$searchresult[$inc]['phone_number'] = $row['phone_number'];
				if ($row['phone'])
				{
					$searchresult[$inc]['phone'] = "(".substr($row['phone'],0,3).") ".substr($row['phone'],3,3).'-'.substr($row['phone'],6,4);
				}
				$searchresult[$inc]['web_url_address'] = $row['web_address'];
			
				$BusinessRating = getLocalBusinessRating($row['id'], $dbd);
				$searchresult[$inc]['total_rating'] = $BusinessRating['total_rating'];
				$searchresult[$inc]['rating'] = $BusinessRating['rating'];

				$query = "select * from local_review where biz_id = '".$row['id']."' limit 1";
				$result = mysql_query($query,$dbd);
				$ReviewsRow = mysql_fetch_assoc($result);
				$searchresult[$inc]['ReviewPreview'] = $ReviewsRow['comments'];
			}
			
			$QueryPremium = "select id from premium where id = ".$results[$i]['biz_id']." limit 1"; ;
			$ResultPremium = mysql_query($QueryPremium, $dbd);
			
			if(mysql_num_rows($ResultPremium))
				$searchresult[$inc]['premium'] = 1;
			else
				$searchresult[$inc]['premium'] = 0;

		//echo  microtime(true) - $startLoop.'<br>\r\n';
		}
		if ($searchresult)
			return $searchresult;
	}
}
/**********************************
////////get business Review////////
**********************************/
if(!function_exists('getLocalBusinessRating')) {
	function getLocalBusinessRating($biz_id, $dbd, $source = '')
	{
		$query = "SELECT count(*) as total_rating, round(avg(`rating`)) as rating FROM `local_review` WHERE biz_id = ".$biz_id." limit 1";
		$result = mysql_query($query, $dbd);
		if($row=mysql_fetch_assoc($result)){
			$BusinessRating['total_rating'] = $row['total_rating'];
			if($row['rating'])
				$BusinessRating['rating'] = $row['rating'];
			else
				$BusinessRating['rating'] = 0;
		}
		return $BusinessRating;
	}
}

if(!function_exists('generateSlug')) {
	function generateSlug($slug){
		$result = strtolower($slug);
		$result = preg_replace('/[^a-z0-9\s-]/', '', $result);
		$result = trim(preg_replace('/[\s-]+/', ' ', $result));
		$result = preg_replace('/\s/', '-', $result);

		return $result;
	}
}

if(!function_exists('clean_strings')) {
	function clean_strings($s) {
		return str_replace(array(chr(133), chr(145), chr(146), chr(147), chr(148), chr(226).chr(128).chr(157), chr(226).chr(128).chr(153), '<p>&nbsp;</p>'), array('...', "'", "'", '"', '"', '"', "'", ''), $s);
	}
}
/**********************************
////////get videos////////
**********************************/
if(!function_exists('searchAdminVideos')) {
	function searchAdminVideos($search, $db, $number = 10, $start = 0) {
		$result = array();

		$sql = "select *, match(keywords) against('".$search."') as score from rep_videos where match(keywords) against('".$search."') order by score, id desc";
		$res = mysql_query($sql, $db);
		
		while($row = mysql_fetch_assoc($res))
		{
			if($row['id'] < 10) {
				$row['id'] = '00'.$row['id'];
			} else if($row['id'] >= 10 && $row['id'] < 100) {
				$row['id'] = '0'.$row['id'];
			}
			$result[] = $row;
		}
		
		if(is_array($result)) {
			$result = array_slice($result, $start, $number);
		}

		return $result;
	}
}
/**
 * 
 * @param comma separated $cat_id values
 * @param unknown_type $db
 * @param unknown_type $number
 * @param unknown_type $start
 * @return Ambigous <multitype:, multitype:string >
 */
if(!function_exists('searchAdminVideosByCatID')) {
	function searchAdminVideosByCatID($cat_id, $db, $number = 50, $start = 0) {
		$result = array();

		$sql = "select * from rep_videos where cat_id in ($cat_id)";
		$res = mysql_query($sql, $db);

		while($row = mysql_fetch_assoc($res))
		{
			if($row['id'] < 10) {
				$row['id'] = '00'.$row['id'];
			} else if($row['id'] >= 10 && $row['id'] < 100) {
				$row['id'] = '0'.$row['id'];
			}
			$result[] = $row;
		}

		if(is_array($result)) {
			$result = array_slice($result, $start, $number);
		}

		return $result;
	}
}

if(!function_exists('searchAdminVideosBySiteID')) {
	function searchAdminVideosBySiteID($site_id, $db, $number = 50, $start = 0) {
		$result = array();

		$sql = "select * from rep_videos where site_id = $site_id";
		$res = mysql_query($sql, $db);

		while($row = mysql_fetch_assoc($res))
		{
			if($row['id'] < 10) {
				$row['id'] = '00'.$row['id'];
			} else if($row['id'] >= 10 && $row['id'] < 100) {
				$row['id'] = '0'.$row['id'];
			}
			$result[] = $row;
		}

		if(is_array($result)) {
			$result = array_slice($result, $start, $number);
		}

		return $result;
	}
}

if(!function_exists('getAdminVideoDetail')) {
	function getAdminVideoDetail($id, $db) {
		$row = array();
		$sql = "select * from rep_videos where id = ".$id;

		$res = mysql_query($sql, $db);
		if($res)
		{
			$row = mysql_fetch_assoc($res);
			if(isset($row['id']))
			{
				if($row['id'] < 10) {
					$row['id'] = '00'.$row['id'];
				} else if($row['id'] >= 10 && $row['id'] < 100) {
					$row['id'] = '0'.$row['id'];
				}
			}
		}

		//$row = $query->row_array();
		//$row = array_map('replaceChars', $row);

		if($_SERVER['HTTP_X_FORWARDED_FOR']=="199.27.174.35"){
			print "<!-- Got the row";
			print "select * from rep_videos where id = ".$id."<br>";
			print_r($row);
			print "-->";				
		}

		return $row;
	}
}

if(!function_exists('shuffle_assoc')) {
	function shuffle_assoc($list) { 
	  if (!is_array($list)) return $list; 

	  $keys = array_keys($list); 
	  shuffle($keys); 
	  $random = array(); 
	  foreach ($keys as $key) { 
		$random[$key] = $list[$key]; 
	  }
	  return $random; 
	} 
}

if(!function_exists('getAnyclipVideoNonCI')) {
	function getAnyclipVideoNonCI($search, $num = 3)
	{
		$videos = array();

		$count = 0;
		
		$mkey = md5("coloVideos_2_");
		$expire = 900;
		$videosArr = array();
		class AnyClipVideoNonCICache extends Memcache {
	    static private $instance = null;
	    static private $port = 11211;
	    static function AnyClipVmGet() {
	        if (self::$instance == null) {
	            self::$instance = new Memcache;
				self::$instance->addServer("192.168.30.51", self::$port);
	        }
	        return self::$instance;
			}
		}
		if(!$videosArr = AnyClipVideoNonCICache::AnyClipVmGet()->get($mkey)) {
			include_once("lib/php/include/db.php");
			$db = ConnectToRead();

			$sql = "select * from rep_videos";
			$res = mysql_query($sql, $db);
			while($row = mysql_fetch_assoc($res))
			{
				$title = trim($row['title']);
				$desc = trim($row['description']);
				$id = $row['id'];

				if($id < 10)
					$vidId = "00".$id;
				else if($id >= 10 && $id < 100)
					$vidId = "0".$id;
				else
					$vidId = $id;

				$thumb = "http://b36df47b3d.site.internapcdn.net/video/".$vidId.".jpeg";
				$videosArr[$id] = array($title, $desc, $thumb);
			}
		
			AnyClipVideoNonCICache::AnyClipVmGet()->set($mkey, $videosArr, 0, $expire);
		}
		$videosArr = shuffle_assoc($videosArr);
		foreach($videosArr as $vid=>$vArr)
		{
			if($count < $num)
			{
				if($vid < 10)
					$vidId = "00".$vid;
				else if($vid >= 10 && $vid < 100)
					$vidId = "0".$vid;
				else
					$vidId = $vid;
				
				array_push($videos,
					array('Thumbnail' => $vArr[2],
						'Title' => $vArr[0],
						'Description' => $vArr[1],
						'ID' => $vidId
					)
				);
				$count++;
			}
			else
				break;
		}
		return $videos;

	}
}

?>