Location: PHPKode > projects > Uiga Personal Portal > library/functions.php
<?php

function dologin()
{
	global $msg;
	$username = mysql_real_escape_string($_POST['username']);
	$password = mysql_real_escape_string($_POST['password']);
		
	// first, make sure the username & password are not empty
	if ($username == '') {
		$msg = 'You must enter your username';
	} else if ($password == '') {
		$msg = 'You must enter your password';
	} else {
		
		$sql = "SELECT *
				FROM tbl_user 
				WHERE username = '$username' 
				AND password = '$password'
				AND is_active = '1'";
				
		$result = dbQuery($sql);
		
		if (dbNumRows($result) == 1) {
			$row = dbFetchAssoc($result);
			
			$sql = "UPDATE tbl_user
					SET lastlogin  = NOW() 
					WHERE user_id = '{$row['user_id']}'";
			dbQuery($sql);
			
			
			if($row['user_id'])
			{
			$_SESSION['user_id']=$row['user_id'];
			//if (isset($_SESSION['login_return_url'])) {
				//header('Location: ' . $_SESSION['login_return_url']);
			echo "<script>location.href='index.php?view=home'</script>";
			exit;
			}
			} 
			else 
			{
			$msg = 'Wrong username or password';
		}		
			
	}
	
	return $msg;
}

				
				

function checkUser()
{
	// if the session id is not set, redirect to login page
	if (!isset($_SESSION['user_id'])) {
		header('Location: index.php?view=login');
		exit;
	}
	
	// the user want to logout
	if (isset($_GET['logout'])) {
		doLogout();
	}
}

function checkIfLoggedOn()
{
	// if the session id is not set, redirect to login page
	if (!isset($_SESSION['user_id'])) {
		//header('Location: index.php?view=login');
		echo "<script>location.href='index.php?view=please_log_in'</script>";
		exit;
	}
	
	// the user want to logout
	if (isset($_GET['logout'])) {
		doLogout();
	}
}

	

function doLogout()
{
	if (isset($_SESSION['user_id'])) {
		unset($_SESSION['user_id']);
		session_unregister('user_id');
	}
		
		echo "<script>location.href='index.php?view=home'</script>";
	//exit;
}







//end




/*
	Logout an administrator
*/

function LogoutAdmin()
{
	if (isset($_SESSION['picmu_admin_id'])) {
		unset($_SESSION['picmu_admin_id']);
		session_unregister('picmu_admin_id');
	}
		
	header('Location: adminlogin.php');
	exit;
}

function getPagingQueryBlog($sql, $itemPerPage = 4)
{
	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$page = (int)$_GET['page'];
	} else {
		$page = 1;
	}
	
	// start fetching from this row number
	$offset = ($page - 1) * $itemPerPage;
	
	return $sql . " LIMIT $offset, $itemPerPage";
}

/*
	Get the links to navigate between one result page to another.
	Supply a value for $strGet if the page url already contain some
	GET values for example if the original page url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php?c=12
	
	use "c=12" as the value for $strGet. But if the url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php
	
	then there's no need to set a value for $strGet
	
	
*/
function checkAdmin()
{
	// if the session id is not set, redirect to login page
	if (!isset($_SESSION['admin_id'])) {
		header('Location:'. WEB_ROOT. 'admin/admin_login.php');
		exit;
	}
	
	// the user want to logout
	if (isset($_GET['adminlogout'])) {
	AdminLogout();

		
	}
}
/*function checkUser()
{
	// if the session id is not set, redirect to login page
	if (!isset($_SESSION['user_id'])) {
		header('Location: ' .SRV_ROOT . ADMIN_PAGES . 'admin_login.php');
		$report="You must login first!";
		exit;
	}
	
	// the user want to logout
	if (isset($_GET['adminlogout'])) {
		AdminLogout();
	}
}


	
*/

function LoginAdmin()
{

	// if we found an error save the error message in this variable
	$errorMessage = '';
	
	$admin_name = $_POST['admin_name'];
	$admin_password = $_POST['admin_password'];
	
	// first, make sure the username & password are not empty
	if ($admin_name == '') {
		$errorMessage =warning. 'You must enter your username';
	} else if ($admin_password == '') {
		$errorMessage = warning.'You must enter your password';
	} else {
		// check the database and see if the username and password combo do match
		$sql = "SELECT *
		        FROM admin 
				WHERE admin_name = '$admin_name' AND admin_password = '$admin_password'";
		$result = dbQuery($sql);
	
		if (dbNumRows($result) == 1) {
			$row = dbFetchAssoc($result);
			$_SESSION['admin_id'] = $row['admin_id'];
			
			// log the time when the user last login
			$sql = "UPDATE admin
			        SET last_login = NOW() 
					WHERE admin_id = '{$row['admin_id']}'";
			dbQuery($sql);

			// now that the user is verified, we move on to the next page
            // if the user had been in the user page before we move to
			// the last page visited
			
			if (isset($_SESSION['login_return_url'])) {
                header('Location: ' . $_SESSION['login_return_url']);
                exit;
            } else {
                header('Location: index.php');
                exit;
            }
        } else {
            $errorMessage =warning. 'Wrong username or password';
        }        
            
    }
    
    return $errorMessage;
}


/*
	Logout a user
*/
function AdminLogout()
{
	if (isset($_SESSION['admin_id']))
	 {
		unset($_SESSION['admin_id']);
		session_unregister('admin_id');
	 }
        
  header('Location:' . WEB_ROOT .'admin/admin_login.php');

	/*echo"<script location.href= WEB_ROOT . 'admin_login.php';'></script>";*/
   // exit;
}

//pagination for users
function getPagingQueryUsers($sql, $itemPerPage = 4)
{
	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$page = (int)$_GET['page'];
	} else {
		$page = 1;
	}
	
	// start fetching from this row number
	$offset = ($page - 1) * $itemPerPage;
	
	return $sql . " LIMIT $offset, $itemPerPage";
}

/*
	Get the links to navigate between one result page to another.
	Supply a value for $strGet if the page url already contain some
	GET values for example if the original page url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php?c=12
	
	use "c=12" as the value for $strGet. But if the url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php
	
	then there's no need to set a value for $strGet
	
	
*/

function getPagingLinkUsers($sql, $itemPerPage = 10, $strGet='view=users')
{
	$result        = dbQuery($sql);
	$pagingLink    = '';
	$totalResults  = dbNumRows($result);
	$totalPages    = ceil($totalResults / $itemPerPage);
	
	// how many link pages to show
	$numLinks      = 10;

		
	// create the paging links only if we have more than one page of results
	if ($totalPages > 1) {
	
		$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
		

		if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
			$pageNumber = (int)$_GET['page'];
		} else {
			$pageNumber = 1;
		}
		
		// print 'previous' link only if we're not
		// on page one
		if ($pageNumber > 1) {
			$page = $pageNumber - 1;
			if ($page > 1) {
				$prev = " <a href=\"$self?page=$page&$strGet\">[Prev]</a> ";
			} else {
				$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
			}	
				
			$first = " <a href=\"$self?$strGet\">[First]</a> ";
		} else {
			$prev  = ''; // we're on page one, don't show 'previous' link
			$first = ''; // nor 'first page' link
		}
	
		// print 'next' link only if we're not
		// on the last page
		if ($pageNumber < $totalPages) {
			$page = $pageNumber + 1;
			$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
			$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
		} else {
			$next = ''; // we're on the last page, don't show 'next' link
			$last = ''; // nor 'last page' link
		}

		$start = $pageNumber - ($pageNumber % $numLinks) + 1;
		$end   = $start + $numLinks - 1;		
		
		$end   = min($totalPages, $end);
		
		$pagingLink = array();
		for($page = $start; $page <= $end; $page++)	{
			if ($page == $pageNumber) {
				$pagingLink[] = " $page ";   // no need to create a link to current page
			} else {
				if ($page == 1) {
					$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
				} else {	
					$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
				}	
			}
	
		}
		
		$pagingLink = implode(' | ', $pagingLink);
		
		// return the page navigation link
		$pagingLink = $first . $prev . $pagingLink . $next . $last;
	}
	
	return $pagingLink;
}


			
//pagination for girls
function getPagingQueryGirls($sql, $itemPerPage = 4)
{
	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$page = (int)$_GET['page'];
	} else {
		$page = 1;
	}
	
	// start fetching from this row number
	$offset = ($page - 1) * $itemPerPage;
	
	return $sql . " LIMIT $offset, $itemPerPage";
}

/*
	Get the links to navigate between one result page to another.
	Supply a value for $strGet if the page url already contain some
	GET values for example if the original page url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php?c=12
	
	use "c=12" as the value for $strGet. But if the url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php
	
	then there's no need to set a value for $strGet
	
	
*/

function getPagingLinkGirls($sql, $itemPerPage = 10, $strGet='view=girls')
{
	$result        = dbQuery($sql);
	$pagingLink    = '';
	$totalResults  = dbNumRows($result);
	$totalPages    = ceil($totalResults / $itemPerPage);
	
	// how many link pages to show
	$numLinks      = 10;

		
	// create the paging links only if we have more than one page of results
	if ($totalPages > 1) {
	
		$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
		

		if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
			$pageNumber = (int)$_GET['page'];
		} else {
			$pageNumber = 1;
		}
		
		// print 'previous' link only if we're not
		// on page one
		if ($pageNumber > 1) {
			$page = $pageNumber - 1;
			if ($page > 1) {
				$prev = " <a href=\"$self?page=$page&$strGet\">[Prev]</a> ";
			} else {
				$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
			}	
				
			$first = " <a href=\"$self?$strGet\">[First]</a> ";
		} else {
			$prev  = ''; // we're on page one, don't show 'previous' link
			$first = ''; // nor 'first page' link
		}
	
		// print 'next' link only if we're not
		// on the last page
		if ($pageNumber < $totalPages) {
			$page = $pageNumber + 1;
			$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
			$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
		} else {
			$next = ''; // we're on the last page, don't show 'next' link
			$last = ''; // nor 'last page' link
		}

		$start = $pageNumber - ($pageNumber % $numLinks) + 1;
		$end   = $start + $numLinks - 1;		
		
		$end   = min($totalPages, $end);
		
		$pagingLink = array();
		for($page = $start; $page <= $end; $page++)	{
			if ($page == $pageNumber) {
				$pagingLink[] = " $page ";   // no need to create a link to current page
			} else {
				if ($page == 1) {
					$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
				} else {	
					$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
				}	
			}
	
		}
		
		$pagingLink = implode(' | ', $pagingLink);
		
		// return the page navigation link
		$pagingLink = $first . $prev . $pagingLink . $next . $last;
	}
	
	return $pagingLink;
}

//pagination for girls in front-end
function getPagingQueryUserGirls($sql, $itemPerPage = 4)
{
	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$page = (int)$_GET['page'];
	} else {
		$page = 1;
	}
	
	// start fetching from this row number
	$offset = ($page - 1) * $itemPerPage;
	
	return $sql . " LIMIT $offset, $itemPerPage";
}

/*
	Get the links to navigate between one result page to another.
	Supply a value for $strGet if the page url already contain some
	GET values for example if the original page url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php?c=12
	
	use "c=12" as the value for $strGet. But if the url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php
	
	then there's no need to set a value for $strGet
	
	
*/

function getPagingLinkUserGirls($sql, $itemPerPage = 10, $strGet='view=girls')
{
	$result        = dbQuery($sql);
	$pagingLink    = '';
	$totalResults  = dbNumRows($result);
	$totalPages    = ceil($totalResults / $itemPerPage);
	
	// how many link pages to show
	$numLinks      = 10;

		
	// create the paging links only if we have more than one page of results
	if ($totalPages > 1) {
	
		$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
		

		if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
			$pageNumber = (int)$_GET['page'];
		} else {
			$pageNumber = 1;
		}
		
		// print 'previous' link only if we're not
		// on page one
		if ($pageNumber > 1) {
			$page = $pageNumber - 1;
			if ($page > 1) {
				$prev = " <a href=\"$self?page=$page&$strGet\">[Prev]</a> ";
			} else {
				$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
			}	
				
			$first = " <a href=\"$self?$strGet\">[First]</a> ";
		} else {
			$prev  = ''; // we're on page one, don't show 'previous' link
			$first = ''; // nor 'first page' link
		}
	
		// print 'next' link only if we're not
		// on the last page
		if ($pageNumber < $totalPages) {
			$page = $pageNumber + 1;
			$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
			$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
		} else {
			$next = ''; // we're on the last page, don't show 'next' link
			$last = ''; // nor 'last page' link
		}

		$start = $pageNumber - ($pageNumber % $numLinks) + 1;
		$end   = $start + $numLinks - 1;		
		
		$end   = min($totalPages, $end);
		
		$pagingLink = array();
		for($page = $start; $page <= $end; $page++)	{
			if ($page == $pageNumber) {
				$pagingLink[] = " $page ";   // no need to create a link to current page
			} else {
				if ($page == 1) {
					$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
				} else {	
					$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
				}	
			}
	
		}
		
		$pagingLink = implode(' | ', $pagingLink);
		
		// return the page navigation link
		$pagingLink = $first . $prev . $pagingLink . $next . $last;
	}
	
	return $pagingLink;
}


//end

//pagination for girls gallery
function getPagingQueryGirlsGal($sql, $itemPerPage = 4)
{
	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$page = (int)$_GET['page'];
	} else {
		$page = 1;
	}
	
	// start fetching from this row number
	$offset = ($page - 1) * $itemPerPage;
	
	return $sql . " LIMIT $offset, $itemPerPage";
}

/*
	Get the links to navigate between one result page to another.
	Supply a value for $strGet if the page url already contain some
	GET values for example if the original page url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php?c=12
	
	use "c=12" as the value for $strGet. But if the url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php
	
	then there's no need to set a value for $strGet
	
	
*/

function getPagingLinkGirlsGal($sql, $itemPerPage = 10, $strGet='view=girlsgal')
{
	$result        = dbQuery($sql);
	$pagingLink    = '';
	$totalResults  = dbNumRows($result);
	$totalPages    = ceil($totalResults / $itemPerPage);
	
	// how many link pages to show
	$numLinks      = 10;

		
	// create the paging links only if we have more than one page of results
	if ($totalPages > 1) {
	
		$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
		

		if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
			$pageNumber = (int)$_GET['page'];
		} else {
			$pageNumber = 1;
		}
		
		// print 'previous' link only if we're not
		// on page one
		if ($pageNumber > 1) {
			$page = $pageNumber - 1;
			if ($page > 1) {
				$prev = " <a href=\"$self?page=$page&$strGet\">[Prev]</a> ";
			} else {
				$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
			}	
				
			$first = " <a href=\"$self?$strGet\">[First]</a> ";
		} else {
			$prev  = ''; // we're on page one, don't show 'previous' link
			$first = ''; // nor 'first page' link
		}
	
		// print 'next' link only if we're not
		// on the last page
		if ($pageNumber < $totalPages) {
			$page = $pageNumber + 1;
			$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
			$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
		} else {
			$next = ''; // we're on the last page, don't show 'next' link
			$last = ''; // nor 'last page' link
		}

		$start = $pageNumber - ($pageNumber % $numLinks) + 1;
		$end   = $start + $numLinks - 1;		
		
		$end   = min($totalPages, $end);
		
		$pagingLink = array();
		for($page = $start; $page <= $end; $page++)	{
			if ($page == $pageNumber) {
				$pagingLink[] = " $page ";   // no need to create a link to current page
			} else {
				if ($page == 1) {
					$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
				} else {	
					$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
				}	
			}
	
		}
		
		$pagingLink = implode(' | ', $pagingLink);
		
		// return the page navigation link
		$pagingLink = $first . $prev . $pagingLink . $next . $last;
	}
	
	return $pagingLink;
}


			






//end			







function getPagingLinkBlog($sql, $itemPerPage = 10, $strGet='view=blogs')
{
	$result        = dbQuery($sql);
	$pagingLink    = '';
	$totalResults  = dbNumRows($result);
	$totalPages    = ceil($totalResults / $itemPerPage);
	
	// how many link pages to show
	$numLinks      = 10;

		
	// create the paging links only if we have more than one page of results
	if ($totalPages > 1) {
	
		$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
		

		if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
			$pageNumber = (int)$_GET['page'];
		} else {
			$pageNumber = 1;
		}
		
		// print 'previous' link only if we're not
		// on page one
		if ($pageNumber > 1) {
			$page = $pageNumber - 1;
			if ($page > 1) {
				$prev = " <a href=\"$self?page=$page&$strGet\">[Prev]</a> ";
			} else {
				$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
			}	
				
			$first = " <a href=\"$self?$strGet\">[First]</a> ";
		} else {
			$prev  = ''; // we're on page one, don't show 'previous' link
			$first = ''; // nor 'first page' link
		}
	
		// print 'next' link only if we're not
		// on the last page
		if ($pageNumber < $totalPages) {
			$page = $pageNumber + 1;
			$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
			$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
		} else {
			$next = ''; // we're on the last page, don't show 'next' link
			$last = ''; // nor 'last page' link
		}

		$start = $pageNumber - ($pageNumber % $numLinks) + 1;
		$end   = $start + $numLinks - 1;		
		
		$end   = min($totalPages, $end);
		
		$pagingLink = array();
		for($page = $start; $page <= $end; $page++)	{
			if ($page == $pageNumber) {
				$pagingLink[] = " $page ";   // no need to create a link to current page
			} else {
				if ($page == 1) {
					$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
				} else {	
					$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
				}	
			}
	
		}
		
		$pagingLink = implode(' | ', $pagingLink);
		
		// return the page navigation link
		$pagingLink = $first . $prev . $pagingLink . $next . $last;
	}
	
	return $pagingLink;
}

//SHIT PAGING
function SearchPaging(){
		$tag="";
	   	global $from;
		$sql="SELECT *
	          FROM music
              WHERE music_artist LIKE '$tag%' or music_title LIKE '$tag%' or music_filename LIKE '$tag%' or music_tag LIKE '$tag%'";

		$result=dbQuery($sql);
		echo mysql_error();
		$totalpage=dbNumRows($result);
		$from1=0;
		$to1=20;
		$pageview="";
		$pageprev="";		
		$pagenext="";	
		$page= "";
		if($totalpage>20){			
			$page= "Pages: ";			
			$pagecount=$totalpage/20;
			$remainder=$totalpage%20;
			$pagecnt=(int)$pagecount;
			if($remainder>0)				
				$pagecnt++;
			
			
			$cnt=1;
			while($cnt<=$pagecnt)
			{			
				if($from==$from1)
					$pageview .= "<strong><em><font color=#CCCCCC>$cnt</font</em></strong> ";
				else
					$pageview .= "<strong><a href=" . $_SERVER['PHP_SELF'] . "?view=category&from=$from1&to=$to1>$cnt</a></strong> ";
				$cnt++;
				$from1 +=20;				
			}
			if($from<$from1-20){
				$next=$from+20;
				$from1 -= 20;
				$pagenext=" <a href=" . $_SERVER['PHP_SELF'] . "?view=category&from=$next&to=$to1 class=blacktext>[Next >]</a> <a href=" . $_SERVER['PHP_SELF'] . "?view=category&from=$from1&to=$to1 class=blacktext>[Last >>]</a>";
			}
			if($from>0){
				$prev=$from-20;
				$pageprev="<a href=" . $_SERVER['PHP_SELF'] . "?view=category&from=0&to=$to1 class=blacktext>[<< First]</a> <a href=" . $_SERVER['PHP_SELF'] . "?view=category&from=$prev&to=$to1 class=blacktext>[< Previous]</a> ";
			}
		}
		echo  $pageprev . $pageview . $pagenext;
	}

function check_email($email) {
    #characters allowed on name: 0-9a-Z-._ on host: 0-9a-Z-. on between: @
    if (!preg_match('/^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/', $email))
        return false;

    #must start or end with alpha or num
    if ( preg_match('/^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/', $email))
        return false;

    #name must end with alpha or num
    if (!preg_match('/([0-9a-zA-Z_]{1})\@./',$email) )                    
        return false;

    #host must start with alpha or num
    if (!preg_match('/.\@([0-9a-zA-Z_]{1})/',$email) )                    
        return false;

    #pair .- or -. or -- or .. not allowed
    if ( preg_match('/.\.\-.|.\-\..|.\.\..|.\-\-./',$email) )
        return false;

    #pair ._ or -_ or _. or _- or __ not allowed
    if ( preg_match('/.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./',$email) )
        return false;

    #host must end with '.' plus 2-5 alpha for TopLevelDomain
    if (!preg_match('/\.([a-zA-Z]{2,5})$/',$email) )
        return false;

    return true;
}

function check_yahoo($yahoo) {
    #characters allowed on name: 0-9a-Z-._ on host: 0-9a-Z-. on between: @
    if (!preg_match('/^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/', $yahoo))
        return false;

    #must start or end with alpha or num
    if ( preg_match('/^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/', $yahoo))
        return false;

    #name must end with alpha or num
    if (!preg_match('/([0-9a-zA-Z_]{1})\@./',$yahoo) )                    
        return false;

    #host must start with alpha or num
    if (!preg_match('/.\@([0-9a-zA-Z_]{1})/',$yahoo) )                    
        return false;

    #pair .- or -. or -- or .. not allowed
    if ( preg_match('/.\.\-.|.\-\..|.\.\..|.\-\-./',$yahoo) )
        return false;

    #pair ._ or -_ or _. or _- or __ not allowed
    if ( preg_match('/.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./',$yahoo) )
        return false;

    #host must end with '.' plus 2-5 alpha for TopLevelDomain
    if (!preg_match('/\.([a-zA-Z]{2,5})$/',$yahoo) )
        return false;

    return true;
}

function check_friendster($friendster) {
    #characters allowed on name: 0-9a-Z-._ on host: 0-9a-Z-. on between: @
    if (!preg_match('/^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/', $friendster))
        return false;

    #must start or end with alpha or num
    if ( preg_match('/^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/', $friendster))
        return false;

    #name must end with alpha or num
    if (!preg_match('/([0-9a-zA-Z_]{1})\@./',$friendster) )                    
        return false;

    #host must start with alpha or num
    if (!preg_match('/.\@([0-9a-zA-Z_]{1})/',$friendster) )                    
        return false;

    #pair .- or -. or -- or .. not allowed
    if ( preg_match('/.\.\-.|.\-\..|.\.\..|.\-\-./',$friendster) )
        return false;

    #pair ._ or -_ or _. or _- or __ not allowed
    if ( preg_match('/.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./',$friendster) )
        return false;

    #host must end with '.' plus 2-5 alpha for TopLevelDomain
    if (!preg_match('/\.([a-zA-Z]{2,5})$/',$friendster) )
        return false;

    return true;
}


/*  function getCategoryList()
{
	$sql = "SELECT cat_id, cat_name, cat_image
	        FROM tbl_category
			WHERE cat_parent_id = 0
			ORDER BY cat_name";
    $result = dbQuery($sql);
    echo mysql_error();
    $cat = array();
    while ($row = dbFetchAssoc($result)) {
		extract($row);
		
		if ($cat_image) {
			$cat_image = WEB_ROOT . 'images/category/' . $cat_image;
		} else {
			$cat_image = WEB_ROOT . 'images/no-image-small.png';
		}
		
		$cat[] = array('url'   => 'index.php?view=shop&c=' . $cat_id,
		               'image' => $cat_image,
					   'name'  => $cat_name);

    }
	
	return $cat;			
}  */

function save_form($vars){
    global $database_file, $database_fields;
    $f = fopen($database_file, 'a');
    if (!$f){
        die("Cannot open db file for save");
    }
    foreach ($vars as $k=>$v) {
        $vars[$k] = str_replace(array("|", "\r","\n"), array('_',' ',' '), $v);
    }
    if (is_array($database_fields)) {
        $vars_orig = $vars; 
        $vars = array();
        foreach ($database_fields as $k)
            $vars[$k] = $vars_orig[$k];
    }
    $str = join('|', $vars);
    fwrite($f, $str."\n");
    fclose($f);
}

function random() {
	$num = rand(111111, 999999);
	return $num;
}

function do_formmail(){
    global $autoresponder_enabled, $database_enabled;
    $form      = get_form_data();
    $errors    = check_form($form);
    if ($errors) {
        display_errors($errors);
        return;
    }
    send_mail($form);
    if ($autoresponder_enabled) 
        auto_respond($form);
    if ($database_enabled)
        save_form($form);
    redirect();
}

function send_mail($vars){

    global $send_to, $send_cc;
    global $subject;
    global $attachment_enabled;
    global $REMOTE_ADDR;

    global $HTTP_POST_FILES;
    $files = array(); //files (field names) to attach in mail
    if (count($HTTP_POST_FILES) && $attachment_enabled){
        $files = array_keys($HTTP_POST_FILES);
    }

    // build mail
    $date_time = date('Y-m-d H:i:s');
    $mime_delimiter = md5(time());
    $fields = _build_fields($vars);
    $mail = <<<EOF
This is a MIME-encapsulated message
    
--$mime_delimiter
Content-type: text/plain
Content-Transfer-Encoding: 8bit

$fields 
--------------------
REMOTE IP : $REMOTE_ADDR
DATE/TIME : $date_time
EOF;

    if (count($files)){
        foreach ($files as $file){
            $file_name     = $HTTP_POST_FILES[$file]['name'];
            $file_type     = $HTTP_POST_FILES[$file]['type'];
            $file_tmp_name = $HTTP_POST_FILES[$file]['tmp_name'];
            $file_cnt = "";
            $f=@fopen($file_tmp_name, "rb");
            if (!$f) 
                continue;
            while($f && !feof($f))
                $file_cnt .= fread($f, 4096);
            fclose($f);
            if (!strlen($file_type)) $file_type="applicaton/octet-stream";
            if ($file_type == 'application/x-msdownload')
                $file_type = "applicaton/octet-stream";

            $mail .= "\n--$mime_delimiter\n";
            $mail .= "Content-type: $file_type\n";
            $mail .= "Content-Disposition: attachment; filename=\"$file_name\"\n";
            $mail .= "Content-Transfer-Encoding: base64\n\n";
            $mail .= chunk_split(base64_encode($file_cnt));
        }
    }
    $mail .= "\n--$mime_delimiter--";


    //send to
    $_send_to = $send_to ? $send_to : "$vars[name_to] <".$vars[email_to].">";
    $_send_from = "$vars[name_from] <".$vars['email_from'].">";
    $_subject = $subject ? $subject : $vars['subject'];

    mail($_send_to, $_subject, $mail, 
    "Mime-Version: 1.0\r\nFrom: $_send_from\r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline");

    foreach ($send_cc as $v){
      mail($v, $_subject, $mail, 
      "Mime-Version: 1.0\r\nFrom: $_send_from\r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline");
    }

}

function get_form_data(){
    global $REQUEST_METHOD;
    global $HTTP_POST_VARS;
    global $HTTP_GET_VARS;
    
    $vars = ($REQUEST_METHOD == 'GET') ? $HTTP_GET_VARS : $HTTP_POST_VARS;
    //strip spaces from all fields
    foreach ($vars as $k=>$v) $vars[$k] = trim($v);
    return $vars;
}

function check_form($vars){
    global $referrers;
    global $send_to;
    global $subject;
    global $HTTP_REFERER;

    $errors = array();

    // check from email set
    if (!strlen($vars['email_from'])){
        $errors[] = "<b>From Email address</b> empty";
    } else if (!check_email($vars['email_from'])){
        $errors[] = "<b>From Email address</b> incorrect";        
    }                 
    if (!strlen($send_to) && !strlen($vars['email_to'])){
        $errors[] = "<b>To Email</b> address empty (possible configuration error)";
    } else if (!strlen($send_to) && !check_email($vars['email_to'])){
        //if to email specified in form, check it and display error
        $errors[] = "<b>To Email address</b> incorrect";        
    }
    if (!strlen($vars['subject']) && !strlen($subject)){
        $errors[] = "<b>Subject</b> empty (possible configuration error)";
    }
    foreach ($vars as $k=>$v){
        // check for required fields (end with _req)
        if (preg_match('/^(.+?)_req$/i', $k, $m) && !strlen($v)){
            $field_name = ucfirst($m[1]);
            $errors[] = "Required field <b>$field_name</b> empty";
        }
        // check for number fields (end with _num)
        if (preg_match('/^(.+?)_num$/i', $k, $m) && strlen($v) && !is_numeric($v)){
            $field_name = ucfirst($m[1]);
            $errors[] = "Field <b>$field_name</b> must contain only digits or be empty";
        }
        // check for number & required fields (end with _reqnum)
        if (preg_match('/^(.+?)_reqnum$/i', $k, $m) && !is_numeric($v)){
            $field_name = ucfirst($m[1]);
            $errors[] = "Field <b>$field_name</b> must contain digits and only digits";
        }
    }

    //check referrer
    if (is_array($referrers) && count($referrers)){
        $ref = parse_url($HTTP_REFERER);
        $host = $ref['host'];
        $host_found = 0;
        foreach ($referrers as $r){
            if (strstr($host, $r)) 
                $host_found++;
        }
        if (!$host_found){
            $errors[] = "Unknown Referrer: <b>$host</b>";
        }
    }
    return $errors;
}

function _build_fields($vars){
    $skip_fields = array(
        'name_from', 
        'email_from', 
        'email_to', 
        'name_to', 
        'subject');
    // order by numeric begin, if it exists
    $is_ordered = 0;
    foreach ($vars as $k=>$v) 
        if (in_array($k, $skip_fields)) unset($vars[$k]);

    $new_vars = array();
    foreach ($vars as $k=>$v){
        // remove _num, _reqnum, _req from end of field names
        $k = preg_replace('/_(req|num|reqnum)$/', '', $k);
        // check if the fields is ordered
        if (preg_match('/^\d+[ \:_-]/', $k)) $is_ordered++;
        //remove number from begin of fields
        $k = preg_replace('/^\d+[ \:_-]/', '', $k);
        $new_vars[$k] = $v;
    }
    $vars = $new_vars;

    $max_length = 10; // max length of key field 
    foreach ($vars as $k=>$v) {
        $klen = strlen($k);
        if (($klen > $max_length) && ($klen < 40))
            $max_length = $klen;
    }

    if ($is_ordered)
        ksort($vars);

    // make output text
    $out = "";
    foreach ($vars as $k=>$v){
        $k = str_replace('_', ' ', $k);
        $k = ucfirst($k);
        $len_diff = $max_length - strlen($k);
        if ($len_diff > 0) 
            $fill = str_repeat('.', $len_diff);
        else 
            $fill = '';
        $out .= $k."$fill...: $v\n";
    }
    return $out;
}

function auto_respond($vars){
    global $autoresponder_from, $autoresponder_message, $autoresponder_subject;
    /// replace all vars in message
    $msg = $autoresponder_message;
    preg_match_all('/%(.+?)%/', $msg, $out);
    $s_vars = $out[1]; //field list to substitute
    foreach ($s_vars as $k)
        $msg = str_replace("%$k%", $vars[$k], $msg);
    /// replace all vars in subject
    $subj = $autoresponder_subject;
    preg_match_all('/%(.+?)%/', $subj, $out);
    $s_vars = $out[1]; //field list to substitute
    foreach ($s_vars as $k)
        $subj = str_replace("%$k%", $vars[$k], $subj);
    //
    $_send_to = "$vars[name_from] <".$vars['email_from'].">";
    $_send_from = $autoresponder_from;
    mail($_send_to, $subj, $msg, "From: $_send_from");
}

function redirect(){
    echo "<script>location.href='index.php'</script>";
}

function displayError()
{		
}
//skin color
function setSkinBGI($sc_bgi)
{
	$skins=array('Gray','Blue','Brown','Green','Red','Purple');
	$numskins=count($skins);
	for($i=0; $i<$numskins; $i++)
	{
		if($sc_bgi==$skins[$i])
			$selected='selected';
		else
			$selected='';
			
		echo "<option $selected>" . $skins[$i] . "</option>";
	}
}

function getSkinBGIDIR()
{
	$sql = "SELECT *
			FROM tbl_shop_config";
	$result = dbQuery($sql);
	$row    = dbFetchAssoc($result);
	return $row['sc_bgi'];
}
//countries
function getCountrySelected($country)
{
	$listCountry=array('Singapore ',
				'Canada ',
				'Afghanistan ',
				'Albania ',
				'Algeria ',
				'American Samoa ',
				'Andorra ',
				'Angola ',
				'Anguilla ',
				'Antarctica ',
				'Antigua and Barbuda ',
				'Argentina ',
				'Armenia ',
				'Aruba ',
				'Australia ',
				'Austria ',
				'Azerbaijan ',
				'Bahamas ',
				'Bahrain ',
				'Bangladesh ',
				'Barbados ',
				'Belarus ',
				'Belgium ',
				'Belize ',
				'Benin ',
				'Bermuda ',
				'Bhutan ',
				'Bolivia ',
				'Bosnia and Herzegovina ',
				'Botswana ',
				'Bouvet Island ',
				'Brazil ',
				'British Indian Ocean Territory ',
				'British Virgin Islands ',
				'Brunei ',
				'Bulgaria ',
				'Burkina Faso ',
				'Burundi ',
				'Cambodia ',
				'Cameroon ',
				'Cape Verde ',
				'Cayman Islands ',
				'Central African Republic ',
				'Chad ',
				'Chile ',
				'China ',
				'Christmas Island ',
				'Cocos Islands ',
				'Colombia ',
				'Comoros ',
				'Congo ',
				'Cook Islands ',
				'Costa Rica ',
				'Croatia ',
				'Cuba ',
				'Cyprus ',
				'Czech Republic ',
				'Denmark ',
				'Djibouti ',
				'Dominica ',
				'Dominican Republic ',
				'East Timor ',
				'Ecuador ',
				'Egypt ',
				'El Salvador ',
				'Equatorial Guinea ',
				'Eritrea ',
				'Estonia ',
				'Ethiopia ',
				'Falkland Islands ',
				'Faroe Islands ',
				'Fiji ',
				'Finland ',
				'France ',
				'French Guiana ',
				'French Polynesia ',
				'French Southern Territories ',
				'Gabon ',
				'Gambia ',
				'Georgia ',
				'Germany ',
				'Ghana ',
				'Gibraltar ',
				'Greece ',
				'Greenland ',
				'Grenada ',
				'Guadeloupe ',
				'Guam ',
				'Guatemala ',
				'Guinea ',
				'Guinea-Bissau ',
				'Guyana ',
				'Haiti ',
				'Heard and McDonald Islands ',
				'Honduras ',
				'Hong Kong ',
				'Hungary ',
				'Iceland ',
				'India ',
				'Indonesia ',
				'Iran ',
				'Iraq ',
				'Ireland ',
				'Israel ',
				'Italy ',
				'Ivory Coast ',
				'Jamaica ',
				'Japan ',
				'Jordan ',
				'Kazakhstan ',
				'Kenya ',
				'Kiribati ',
				'North Korea ',
				'South Korea ',
				'Kuwait ',
				'Kyrgyzstan ',
				'Laos ',
				'Latvia ',
				'Lebanon ',
				'Lesotho ',
				'Liberia ',
				'Libya ',
				'Liechtenstein ',
				'Lithuania ',
				'Luxembourg ',
				'Macau ',
				'Macedonia ',
				'Madagascar ',
				'Malawi ',
				'Malaysia ',
				'Maldives ',
				'Mali ',
				'Malta ',
				'Marshall Islands ',
				'Martinique ',
				'Mauritania ',
				'Mauritius ',
				'Mayotte ',
				'Mexico ',
				'Micronesia ',
				'Moldova ',
				'Monaco ',
				'Mongolia ',
				'Montserrat ',
				'Morocco ',
				'Mozambique ',
				'Myanmar ',
				'Namibia ',
				'Nauru ',
				'Nepal ',
				'Netherlands ',
				'Netherlands Antilles ',
				'New Caledonia ',
				'New Zealand ',
				'Nicaragua ',
				'Niger ',
				'Nigeria ',
				'Niue ',
				'Norfolk Island ',
				'Northern Mariana Islands ',
				'Norway ',
				'Oman ',
				'Pakistan ',
				'Palau ',
				'Panama ',
				'Papua New Guinea ',
				'Paraguay ',
				'Peru ',
				'Philippines ',
				'Pitcairn Island ',
				'Poland ',
				'Portugal ',
				'Puerto Rico ',
				'Qatar ',
				'Reunion ',
				'Romania ',
				'Russia ',
				'Rwanda ',
				'S. Georgia and S. Sandwich Isls. ',
				'Saint Kitts &amp; Nevis ',
				'Saint Lucia ',
				'Saint Vincent and The Grenadines ',
				'Samoa ',
				'San Marino ',
				'Sao Tome and Principe ',
				'Saudi Arabia ',
				'Senegal ',
				'Seychelles ',
				'Sierra Leone ',
				'Slovakia ',
				'Slovenia ',
				'Solomon Islands ',
				'Somalia ',
				'South Africa ',
				'Spain ',
				'Sri Lanka ',
				'St. Helena ',
				'St. Pierre and Miquelon ',
				'Sudan ',
				'Suriname ',
				'Svalbard and Jan Mayen Islands ',
				'Swaziland ',
				'Sweden ',
				'Switzerland ',
				'Syria ',
				'Taiwan ',
				'Tajikistan ',
				'Tanzania ',
				'Thailand ',
				'Togo ',
				'Tokelau ',
				'Tonga ',
				'Trinidad and Tobago ',
				'Tunisia ',
				'Turkey ',
				'Turkmenistan ',
				'Turks and Caicos Islands ',
				'Tuvalu ',
				'U.S. Minor Outlying Islands ',
				'Uganda ',
				'Ukraine ',
				'United Arab Emirates ',
				'United Kingdom ',
				'United States',
				'Uruguay ',
				'Uzbekistan ',
				'Vanuatu ',
				'Vatican City ',
				'Venezuela ',
				'Vietnam ',
				'Virgin Islands ',
				'Wallis and Futuna Islands ',
				'Western Sahara ',
				'Yemen ',
				'Serbia and Montenegro ',
				'Zaire ',
				'Zambia ',
				'Zimbabwe ');
		$numList =count($listCountry);
		$i=0;
		$selected='';
		for($i=0; $i<$numList; $i++)
		{
			if($country==trim($listCountry[$i]))
				$selected='selected';
			else
				$selected='';
			echo "<option $selected>" . trim($listCountry[$i]) . "</option>";
		}
}

function findexts($file)
{
$file = strtolower($file) ;
$exts = split("[/\\.]", $file) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}

//function for date
function getDay($user_b_day)
{
$Day=array('1', 
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'17',
'18',
'19',
'20',
'21',
'22',
'23',
'24',
'25',
'26',
'27',
'28',
'29',
'30',
'31',);

$dayList=count($Day);
$i=0;
$selected='';
for($i=0;$i<$dayList; $i++)
{

if($user_b_day==trim($Day[$i]))
$selected='selected';
else
$selected='';
echo"<option $selected>".trim($Day[$i])."</option>";
}

}

//function for year
function getYear($user_b_year)
{
$Year=array('1919', 
'1920',
'1921',
'1922',
'1923',
'1924',
'1925',
'1926',
'1927',
'1928',
'1929',
'1930',
'1931',
'1932',
'1933',
'1934',
'1935',
'1936',
'1937',
'1938',
'1939',
'1940',
'1941',
'1942',
'1943',
'1944',
'1945',
'1946',
'1946',
'1947',
'1948',
'1949',
'1950',
'1951',
'1952',
'1953',
'1954',
'1955',
'1956',
'1957',
'1958',
'1959',
'1960',
'1961',
'1962',
'1963',
'1964',
'1965',
'1966',
'1967',
'1968',
'1969',
'1970',
'1971',
'1972',
'1973',
'1974',
'1975',
'1976',
'1977',
'1978',
'1979',
'1980',
'1981',
'1982',
'1983',
'1984',
'1985',
'1986',
'1987',
'1988',
'1989',
'1990',
'1991',
'1992',
'1993',
'1994',
'1995',
'1996',
'1997',
'1998',
'1999',
'2000',
'2001',
'2002',
'2003',
'2004',
'2005',
'2006',
'2007'
);

$yearList=count($Year);
$i=0;
$selected='';
for($i=0;$i<$yearList; $i++)
{

if($user_b_year==trim($Year[$i]))
$selected='selected';
else
$selected='';
echo"<option $selected>".trim($Year[$i])."</option>";
}

}


//BACK UP FUNCTION
function listBackup() {
	
		global $backupRoot, $backup_array;

		$mydir = opendir($backupRoot);
		$i = 0;
		
		while($fn = readdir($mydir)) {
		
			if ( ereg("backup.sql", $fn) ) {
				$backup_array[$i]["name"] = $fn;
				$backup_array[$i]["fullpath"] = $backupRoot . "/" . $fn;
			//echo $backup_array[$i]["name"] . " ".  $backup_array[$i]["fullpath"] . " <BR>\n";
				$i++;
			}
		}
		closedir($mydir);
	}
	
	function getBackupDate( $filename ) {
		$t = split("_backup.sql", $filename) ;
		return getDateStr( $t[0] ) . " - " . getTimeStr( $t[0] );
	}
	
	function getDateStr($in_stamp)

  {

  	$date = getDate($in_stamp);

    $day = $date['mday'];

    $month = $date['month'];

    $year = $date['year'];

    return $day." ".$month." ".$year;

  }



  function getTimeStr($in_stamp)
  {
  	$time = getDate($in_stamp);
    $hrs = $time['hours'];
    $mins = (strlen($time['minutes']) == 1) ? "0".$time['minutes'] : $time['minutes'];
    $secs = (strlen($time['seconds']) == 1) ? "0".$time['seconds'] : $time['seconds'];
    return $hrs.":".$mins.":".$secs;
  }
  
  function listTbl() {
		
	    $result = mysql_list_tables(MYSQL_DB);
    
    	if (!$result) {
        	print "DB Error, could not list tables\n";
	        print 'MySQL Error: ' . mysql_error();
	        exit;
    	}
    
	    while ($row = mysql_fetch_row($result)) {
				$query = "select * from " .$row[0] ;	
				$tables_array[] = $row[0];
	    }

		echo "<TR><TD class=normaltext>";		
		echo "<select name=\"select_tables[]\" size=\"10\"  class=\"textbox\" multiple>";
        for($i=0; $i < count($tables_array); $i++ ) {
			echo "<option value=\"" .$tables_array[$i] ."\" selected>" . $tables_array[$i] ."</option>\n";				
		}
		echo "</select>";
		echo "</TD></TR>\n";

	}
	
	function listTblField() {
	
		global $select_tables;
		echo "\n<form action=\"index.php?view=backup_export\" method=get>";
		echo "<input name=view type=hidden id=view value=backup_export>";
		for ($i=0; $i < count($select_tables); $i++) {

			echo "<tr>";
			echo "<td class=boldblacktext width=24%> $select_tables[$i] </td>";
					
			$fields = mysql_list_fields(MYSQL_DB, $select_tables[$i]);
			$columns = mysql_num_fields($fields);
			
			echo "<td> ";
			echo "<select name=\"select_fields".$i."[]\" size=\"10\" class=\"textbox\" multiple>\n";	


			for ($j = 0; $j < $columns; $j++)
	      	{
				echo "<option value=\"" .mysql_field_name($fields, $j)."\" selected>" . mysql_field_name($fields, $j) ."</option>\n";
			}
			echo "</select>";
			echo "</td>\n";
			echo "<td class=boldblacktext> ";
			echo "<input type=hidden name=\"table_name".$i."\" value=\"$select_tables[$i]\">\n";			
			echo "</td>\n";
							
			echo "</tr>\n";
  
		}
		//display the delimited field
		echo "<tr><td class=boldblacktext>";
		echo "Delimiter";
		echo "<td>";		
		echo "<select name=delim class=\"textbox\" >";
		echo "<option value=></option>";
		echo "<option value=comma selected>Comma (,)</option>";
		echo "<option value=tab>Tab</option></select>";
		echo "</tr>\n";
		
		//display the file format
		echo "<tr><td class=boldblacktext>";
		echo "File Format";
		echo "<td>";		
		echo "<select  class=\"textbox\" name=format>";
		echo "<option value=csv>CSV</option>";
		echo "<option value=txt>Text File</option></select>";
		echo "</tr>\n";
		
		//display the enclosed by
		echo "<tr><td class=boldblacktext>";
		echo "Enclosed by";
		echo "<td>";		
		echo "<select  class=\"textbox\" name=enc>";
		echo "<option value=0></option>";
		echo "<option value=1>Single quote</option>";
		echo "<option value=2 selected>Double quote</option></select>";
		echo "</tr>\n";		
		
		//display export button
		echo "<tr>\n";
		
		echo "<td colspan=2 align=left><input type=submit name=export value=export class=btn> </td>";
		echo "</tr>\n";

		echo "<input type=hidden name=action value=export_table>\n";		
		echo "<input type=hidden name=total_tables value=". count($select_tables) ." >\n";
		echo "</form>\n";  
						
	}
 function ProcessTables() {
	
		global $total_tables;
		global $HTTP_GET_VARS;
		global $backupRoot;
		
		$format = $HTTP_GET_VARS["format"];
		$export_file = $backupRoot . "/export_" .time() . "." . $format;


		//find the delimiter			
		$delim = $HTTP_GET_VARS["delim"];
		if ($delim == "comma") {
			$delim = ",";
		}
		else if ($delim == "tab") {
			$delim = "\t";
		}
		
		//find the enclosed by 
		$enc = $HTTP_GET_VARS["enc"];
		if ($enc == "1") {
			$enc = "'";
		}
		else if ($enc == "2") {
			$enc = "\"";
		}

		$out = fopen($export_file, "w");

		for ($i=0; $i<$total_tables; $i++) {
	
			//print the table
			$table = $HTTP_GET_VARS["table_name".$i];
			fwrite($out, "<--- Table: ". $table . " --->\n");
			
			//print the fields
			$select_fields = $HTTP_GET_VARS["select_fields".$i];						
			$fieldStr = "";
			for ($j=0; $j<count($select_fields); $j++) {
				$fieldStr .= $select_fields[$j]  . " ,";
			}
			$fieldStr = substr($fieldStr, 0, strlen($fieldStr)-1);			
			fwrite($out, $fieldStr . "\n");


			$query = " Select ";
			for ($j=0; $j<count($select_fields); $j++) {
				$query .= $select_fields[$j]  . ",";
			}
			
			$query = substr($query, 0, strlen($query)-1);
			$query .= " from $table";
			
			$result = mysql_query($query);
		
			if (!$result) {
				print "DB Error, could not list tables\n";
				print 'MySQL Error: ' . mysql_error();
				exit;
			}

		
			// display the field
			while ($row = mysql_fetch_row($result)) {
				$t = "";
				for($j=0; $j<count($row); $j++) {
					$t .= $enc. $row[$j] .$enc. $delim;
				}
				$t = substr($t, 0, strlen($t)-1);
				fwrite($out, $t. "\n");							
			}
		}
		fclose($out);

		echo "<tr><td  height=\"20\"><span class=\"normaltext\" id=boldlink><a href=" .$export_file.">Download Exported File Here</a></span></td></tr>\n";
	}
//end

//send email confirmation 
function SendEmailConfirmation()
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$uid=dbInsertId();

//These are the variables for the email
global $email, $fname, $lname;
$name = $fname." ".$lname;
$link ="http://www.uigaportal/index.php?view=account_verification&id=$uid";
$heading ="Uiga Personal Portal REGISTRATION";

$sendto = $_POST['email'];; // this is the email address collected from the form
$ccto = "hide@address.com"; //you can cc it to yourself
$subject = "Uiga Personal Portal Email Confirmation"; // Subject
$message = "$heading\n\nHello, $name!\n\nThank you so much for signing up at Uiga Personal Portal. Please click the link below to verify your registration.\n\n$link";
$header = "From: Uiga Personal Portal <hide@address.com>\r\n";
$header .= "Reply-to: hide@address.com\r\n";
// This is the function to send the email
mail($sendto, $subject, $message, $header); 
//mail($ccto);
}

//end

//send email confirmation 
function SendEmailConfirmation2()
{
$email	= 	$_GET['email'];
$id		=	$_GET['id'];

$sql = "SELECT *
        FROM tbl_user tu, tbl_userdetail tud
		WHERE tu.user_id = '$id'
		AND tu.email = '$email'
		AND tud.user_id = tu.user_id";
$result = dbQuery($sql);
$User = dbFetchAssoc($result);

//These are the variables for the email
$name = $User['firstname']." ".$User['lastname'];
$link ="http://www.uigaportal/index.php?view=account_verification&id=$id";
$heading ="Uiga Personal Portal REGISTRATION";

$sendto = $_GET['email'];; // this is the email address collected from the form
$ccto = "hide@address.com"; //you can cc it to yourself
$subject = "Uiga Personal Portal Email Confirmation"; // Subject
$message = "$heading\n\nHello, $name!\n\nThank you so much for signing up at Uiga Personal Portal. Please click the link below to verify your registration.\n\n$link";
$header = "From: Uiga Personal Portal <hide@address.com>\r\n";
$header .= "Reply-to: hide@address.com\r\n";
// This is the function to send the email
mail($sendto, $subject, $message, $header); 
//mail($ccto);
}

//end

//order info

//send email confirmation 


//end

//send email confirmation 
function ForgotPassword()
{
global $msg;
$username = mysql_real_escape_string($_POST['username']);
$email = $_POST['email'];


$sqlCheck = "SELECT *
             FROM tbl_user, tbl_userdetail
			 WHERE username = '$username'
			 AND email = '$email'
			 AND tbl_user.user_id = tbl_userdetail.user_id";
$result = dbQuery($sqlCheck) or die (mysql_error());
$row = dbNumRows($result);
$Pass = dbFetchAssoc($result);

if(empty($username))
{
$msg = "Please enter your username.";
}
elseif(empty($email)){
$msg = "Please provide your e-mail address.";
}
elseif(!$row)
{
$msg = "Wrong username and password!";
}else{

//These are the variables for the email
global $email, $fname, $lname;
$name = $Pass['firstname']." ".$Pass['lastname'];
$password = $Pass['password'];
//$link ="http://www.Uiga Personal Portal/index.php?view=account_verification&id=$uid";
$heading ="Uiga Personal Portal (Forgot Password)";

$sendto = $_POST['email'];; // this is the email address collected from the form
$ccto = "hide@address.com"; //you can cc it to yourself
$subject = "Uiga Personal Portal Password Request"; // Subject
$message = "$heading\n\nHello, $name!\n\nHere's your password as requested\n\nPassword : $password.";
$header = "From: Uiga Personal Portal <hide@address.com>\r\n";
$header .= "Reply-to: hide@address.com\r\n";
// This is the function to send the email
mail($sendto, $subject, $message, $header); 
//mail($ccto);
$msg = "Your password request was sent to your e-mail address.";
}
}

/* 
//upload photo during registration
function RegisterPhoto()
{
    global $msg;
	global $resultAccount;
	$fname		=	$_POST['firstname'];
	$lname		=	$_POST['lastname'];
	$photo		= 	$_FILES['image_filename']['name'];
	$b_month	=	$_POST['b_month'];
	$b_day		=	$_POST['b_day'];
	$b_year		=	$_POST['b_year'];
	$address1	=	$_POST['address1'];
	$address2	=	$_POST['address2'];
	$city		=	$_POST['city'];	
	$state		=	$_POST['state'];
	$country	=	$_POST['country'];
	$mobileno	=	$_POST['mobileno'];
	$desc		=	$_POST['desc'];
$images = uploadProductImage('image_filename', SRV_ROOT . PHOTO_GIRL);

	$mainImage = $images['image'];
	$thumbnail = $images['thumbnail'];


	$girl_id = dbInsertId();
			
$sqlInfo = "INSERT INTO tbl_girls_details(girl_id, photo_main, photo_main_thumb, firstname, lastname, b_month, b_day, b_year, add1, add2, town_city, state_prov, country, mobile, description, flag)VALUES('$girl_id', '$mainImage', '$thumbnail', '$fname', '$lname','$b_month' ,'$b_day', '$b_year','$address1', '$address2', '$city', '$state', '$country', '$mobileno', '$desc', '1')";
$resultInfo = dbQuery($sqlInfo) or die (mysql_error());

if($resultInfo && $resultAccount)
{
$msg = "Girl was added successfully.";
}else
{
$msg = "Error Adding";
}

 } */
 //end code for registration upload photo
 
 //edit girls
/*  function EditGirl()
{
    global $msg;
	global $resultAccount;
    $girl_id	= 	$_GET['girl_id'];
	$fname		=	$_POST['firstname'];
	$lname		=	$_POST['lastname'];
	$photo		= 	$_FILES['image_filename']['name'];
	$b_month	=	$_POST['b_month'];
	$b_day		=	$_POST['b_day'];
	$b_year		=	$_POST['b_year'];
	$address1	=	$_POST['address1'];
	$address2	=	$_POST['address2'];
	$city		=	$_POST['city'];	
	$state		=	$_POST['state'];
	$country	=	$_POST['country'];
	$mobileno	=	$_POST['mobileno'];
	$desc		=	$_POST['desc'];
	
$images = uploadProductImage('image_filename', SRV_ROOT . PHOTO_GIRL);

	$mainImage = $images['image'];
	$thumbnail = $images['thumbnail'];


	$sql = "SELECT *
	        FROM tbl_girls_details
			WHERE girl_id = '$girl_id'";
	$result = dbQuery($sql) or die (mysql_error());
	$Image = dbFetchAssoc($result);
	$Image1 = $Image['photo_main'];
	$Image2 = $Image['photo_main_thumb'];
	$name = $Image['firstname'] ."&nbsp;".$Image['lastname'];
	
	
	
	if(empty($_FILES['image_filename']['name']))
	{

	
   $sqlInfo = "UPDATE tbl_girls_details
            SET photo_main = '$Image1', 
			photo_main_thumb = '$Image2', 
			firstname = '$fname', 
			lastname = '$lname', 
			b_month = '$b_month', 
			b_day = '$b_day', 
			b_year = '$b_year', 
			add1 = '$address1', 
			add2 = '$address2', 
			town_city = '$city', 
			state_prov = '$state', 
			country = '$country', 
			mobile = '$mobileno', 
			description = '$desc'
			WHERE girl_id = '$girl_id'";
$resultInfo = dbQuery($sqlInfo) or die (mysql_error());

		if($resultInfo && $resultAccount)
		{
		$msg = "$name 's Account was updated successfully."; 
				}else
		{
		$msg = "Error updating";
		}	
			

   }else{
   
   


		@unlink(SRV_ROOT . PHOTO_GIRL . $Image['photo_main']);
		@unlink(SRV_ROOT . PHOTO_GIRL . $Image['photo_main_thumb']);

	$sqlInfo2 = "UPDATE tbl_girls_details
            SET photo_main = '$mainImage', 
			photo_main_thumb = '$thumbnail', 
			firstname = '$fname', 
			lastname = '$lname', 
			b_month = '$b_month', 
			b_day = '$b_day', 
			b_year = '$b_year', 
			add1 = '$address1', 
			add2 = '$address2', 
			town_city = '$city', 
			state_prov = '$state', 
			country = '$country', 
			mobile = '$mobileno', 
			description = '$desc'
			WHERE girl_id = '$girl_id'";
$resultInfo2 = dbQuery($sqlInfo2) or die (mysql_error());

		if($resultInfo2 && $resultAccount)
		{
		$msg = "$name 's Account was updated successfully."; 
		}else
		{
		$msg = "Error updating";
		}
	

   
   
   
}
 }
 
 //end edit girls
 
 
//upload girl pictures
function UploadGirlPictures()
{
    global $msg;
	$id		=		$_GET['id'];
	
$images = uploadProductImage('file', SRV_ROOT . PHOTO_GGIRL);

	$mainImage = $images['image'];
	$thumbnail = $images['thumbnail'];

	$girl_id = dbInsertId();
			
$sqlAddPhoto = "INSERT INTO tbl_gphotos(girl_id, photo_main, photo_main_thumb)
				VALUES('$id' , '$mainImage', '$thumbnail')";
$resultAddPhoto = dbQuery($sqlAddPhoto) or die (mysql_error());

if($resultAddPhoto)
{
$msg = "Photo was uploaded successfully.";
}else
{
$msg = "Error Adding";
}

 }
 */
//end upload girl pictures function

//upload category for gallery
function UploadCat()
{
    global $msg;
	$file		=	$_FILES['file']['name'];
	$cat_name 	= 	$_POST['cat_name'];
	$cat_desc 	= 	$_POST['cat_desc'];
	
    $images = uploadProductImage('file', SRV_ROOT . CATEGORY_IMAGE_DIR);

	$mainImage = $images['image'];
	$thumbnail = $images['thumbnail'];

			
$sqlAddCat = "INSERT INTO tbl_photo_cat(cat_name, cat_desc, main, thumb, date_created)
				VALUES('$cat_name' ,'$cat_desc' , '$mainImage', '$thumbnail', NOW())";
$resultAddCat = dbQuery($sqlAddCat) or die (mysql_error());

if($resultAddCat)
{
$msg = "Category was created successfully.";
}else
{
$msg = "Error Adding";
}

 }

//edit category
function EditCat()
{
    global $msg;
	$file		=	$_FILES['file']['name'];
	$cat_name 	= 	$_POST['cat_name'];
	$cat_desc 	= 	$_POST['cat_desc'];
	$cat_id		=	$_GET['cat_id'];
	
    $images = uploadProductImage('file', SRV_ROOT . CATEGORY_IMAGE_DIR);

	$mainImage = $images['image'];
	$thumbnail = $images['thumbnail'];


	//query to retain photo if no file uploaded
	$sql = "SELECT *
	        FROM tbl_photo_cat
			WHERE cat_id = '$cat_id'";
	$result = dbQuery($sql);
	$file = dbFetchAssoc($result)or die(mysql_error());
	$file1 = $file['main'];
	$file2 = $file['thumb'];
	
	
	if(empty($_FILES['file']['name']))
	{
	$sql = "UPDATE tbl_photo_cat
	        SET cat_name = '$cat_name',
			cat_desc = '$cat_desc',
			main = '$file1',
			thumb = '$file2',
			date_modified = NOW()
			WHERE cat_id = '$cat_id'";
	$result = dbQuery($sql)or die(mysql_error());
		if($result)
		{
		$msg = "Category was updated successfully.";
		}else
		{
		$msg = "Error updating";
		}
	
	}else{
	
	@unlink(SRV_ROOT . CATEGORY_IMAGE_DIR . $file['main']);
	@unlink(SRV_ROOT . CATEGORY_IMAGE_DIR . $file['thumb']);

		$sql = "UPDATE tbl_photo_cat
	        SET cat_name = '$cat_name',
			cat_desc = '$cat_desc',
			main = '$mainImage',
			thumb = '$thumbnail',
			date_modified = NOW()
			WHERE cat_id = '$cat_id'";
	$result = dbQuery($sql) or die(mysql_error());


if($result)
{
$msg = "Category was updated successfully.";
}else
{
$msg = "Error updating";
}
}
 }



//end

//upload category for gallery
function UploadPhotosCat()
{
    global $msg;
	$file			=	$_FILES['file']['name'];
	$cat_id 		= 	$_GET['cat'];
	$photo_name 	= 	$_POST['photo_name'];
    $images = uploadProductImage('file', SRV_ROOT . PHOTO_DIR);

	$mainImage = $images['image'];
	$thumbnail = $images['thumbnail'];

			
$sqlAddCat = "INSERT INTO tbl_photos(cat_id, photo_name, photo_main_thumb, photo_main)
				VALUES('$cat_id', '$photo_name', '$thumbnail' ,'$mainImage')";
$resultAddCat = dbQuery($sqlAddCat) or die (mysql_error());

if($resultAddCat)
{
$msg = "Photo was uploaded successfully.";
}else
{
$msg = "Error Adding";
}

 }

//end upload category for gallery
 function uploadProductImage($inputName, $uploadDir)
{
	$image     = $_FILES[$inputName];
	$imagePath = '';
	$thumbnailPath = '';
	
	// if a file is given
	if (trim($image['tmp_name']) != '') {
		$ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];

		// generate a random new file name to avoid name conflict
		$imagePath = md5(rand() * time()) . ".$ext";
		
		list($width, $height, $type, $attr) = getimagesize($image['tmp_name']); 

		// make sure the image width does not exceed the
		// maximum allowed width
		if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
			$result    = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH);
			$imagePath = $result;
		} else {
			$result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
		}	
		
		if ($result) {
			// create thumbnail
			$thumbnailPath =  md5(rand() * time()) . ".$ext";
			$result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH);
			
			// create thumbnail failed, delete the image
			if (!$result) {
				unlink($uploadDir . $imagePath);
				$imagePath = $thumbnailPath = '';
			} else {
				$thumbnailPath = $result;
			}	
		} else {
			// the product cannot be upload / resized
			$imagePath = $thumbnailPath = '';
		}
		
	}

	
	return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}

/*
	Create a thumbnail of $srcFile and save it to $destFile.
	The thumbnail will be $width pixels.
*/
function createThumbnail($srcFile, $destFile, $width, $quality = 100)
{
	$thumbnail = '';
	
	if (file_exists($srcFile)  && isset($destFile))
	{
		$size        = getimagesize($srcFile);
		$w           = number_format($width, 0, ',', '');
		$h           = number_format(($size[1] / $size[0]) * $width, 0, ',', '');
		
		$thumbnail =  copyImage($srcFile, $destFile, $w, $h, $quality);
	}
	
	// return the thumbnail file name on sucess or blank on fail
	return basename($thumbnail);
}

/*
	Copy an image to a destination file. The destination
	image size will be $w X $h pixels
*/
function copyImage($srcFile, $destFile, $w, $h, $quality = 100)
{
    $tmpSrc     = pathinfo(strtolower($srcFile));
    $tmpDest    = pathinfo(strtolower($destFile));
    $size       = getimagesize($srcFile);

    if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg")
    {
       $destFile  = substr_replace($destFile, 'jpg', -3);
       $dest      = imagecreatetruecolor($w, $h);
       imageantialias($dest, TRUE);
    } elseif ($tmpDest['extension'] == "png") {
       $dest = imagecreatetruecolor($w, $h);
       imageantialias($dest, TRUE);
    } else {
      return false;
    }

    switch($size[2])
    {
       case 1:       //GIF
           $src = imagecreatefromgif($srcFile);
           break;
       case 2:       //JPEG
           $src = imagecreatefromjpeg($srcFile);
           break;
       case 3:       //PNG
           $src = imagecreatefrompng($srcFile);
           break;
       default:
           return false;
           break;
    }

    imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

    switch($size[2])
    {
       case 1:
       case 2:
           imagejpeg($dest,$destFile, $quality);
           break;
       case 3:
           imagepng($dest,$destFile);
    }
    return $destFile;

}

//check extension

function photoexts($file)
{
$file = strtolower($file) ;
$exts = split("[/\\.]", $file) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}


//pagination in gallery
function getPagingQueryGallery($sql, $itemPerPage = 4)
{
	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$page = (int)$_GET['page'];
	} else {
		$page = 1;
	}
	
	// start fetching from this row number
	$offset = ($page - 1) * $itemPerPage;
	
	return $sql . " LIMIT $offset, $itemPerPage";
}

/*
	Get the links to navigate between one result page to another.
	Supply a value for $strGet if the page url already contain some
	GET values for example if the original page url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php?c=12
	
	use "c=12" as the value for $strGet. But if the url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php
	
	then there's no need to set a value for $strGet
	
	
*/

function getPagingLinkGallery($sql, $itemPerPage = 10, $strGet='view=girls')
{
	$result        = dbQuery($sql);
	$pagingLink    = '';
	$totalResults  = dbNumRows($result);
	$totalPages    = ceil($totalResults / $itemPerPage);
	
	// how many link pages to show
	$numLinks      = 10;

		
	// create the paging links only if we have more than one page of results
	if ($totalPages > 1) {
	
		$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
		

		if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
			$pageNumber = (int)$_GET['page'];
		} else {
			$pageNumber = 1;
		}
		
		// print 'previous' link only if we're not
		// on page one
		if ($pageNumber > 1) {
			$page = $pageNumber - 1;
			if ($page > 1) {
				$prev = " <a href=\"$self?page=$page&$strGet\">[Prev]</a> ";
			} else {
				$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
			}	
				
			$first = " <a href=\"$self?$strGet\">[First]</a> ";
		} else {
			$prev  = ''; // we're on page one, don't show 'previous' link
			$first = ''; // nor 'first page' link
		}
	
		// print 'next' link only if we're not
		// on the last page
		if ($pageNumber < $totalPages) {
			$page = $pageNumber + 1;
			$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
			$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
		} else {
			$next = ''; // we're on the last page, don't show 'next' link
			$last = ''; // nor 'last page' link
		}

		$start = $pageNumber - ($pageNumber % $numLinks) + 1;
		$end   = $start + $numLinks - 1;		
		
		$end   = min($totalPages, $end);
		
		$pagingLink = array();
		for($page = $start; $page <= $end; $page++)	{
			if ($page == $pageNumber) {
				$pagingLink[] = " $page ";   // no need to create a link to current page
			} else {
				if ($page == 1) {
					$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
				} else {	
					$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
				}	
			}
	
		}
		
		$pagingLink = implode(' | ', $pagingLink);
		
		// return the page navigation link
		$pagingLink = $first . $prev . $pagingLink . $next . $last;
	}
	
	return $pagingLink;
}


//end pagination in gallery


//pagination in user gallery
function getPagingQueryUserGallery($sql, $itemPerPage = 4)
{
	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$page = (int)$_GET['page'];
	} else {
		$page = 1;
	}
	
	// start fetching from this row number
	$offset = ($page - 1) * $itemPerPage;
	
	return $sql . " LIMIT $offset, $itemPerPage";
}

/*
	Get the links to navigate between one result page to another.
	Supply a value for $strGet if the page url already contain some
	GET values for example if the original page url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php?c=12
	
	use "c=12" as the value for $strGet. But if the url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php
	
	then there's no need to set a value for $strGet
	
	
*/

function getPagingLinkUserGallery($sql, $itemPerPage = 10, $strGet='view=gallery')
{
	$result        = dbQuery($sql);
	$pagingLink    = '';
	$totalResults  = dbNumRows($result);
	$totalPages    = ceil($totalResults / $itemPerPage);
	
	// how many link pages to show
	$numLinks      = 10;

		
	// create the paging links only if we have more than one page of results
	if ($totalPages > 1) {
	
		$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
		

		if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
			$pageNumber = (int)$_GET['page'];
		} else {
			$pageNumber = 1;
		}
		
		// print 'previous' link only if we're not
		// on page one
		if ($pageNumber > 1) {
			$page = $pageNumber - 1;
			if ($page > 1) {
				$prev = " <a href=\"$self?page=$page&$strGet\">[Prev]</a> ";
			} else {
				$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
			}	
				
			$first = " <a href=\"$self?$strGet\">[First]</a> ";
		} else {
			$prev  = ''; // we're on page one, don't show 'previous' link
			$first = ''; // nor 'first page' link
		}
	
		// print 'next' link only if we're not
		// on the last page
		if ($pageNumber < $totalPages) {
			$page = $pageNumber + 1;
			$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
			$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
		} else {
			$next = ''; // we're on the last page, don't show 'next' link
			$last = ''; // nor 'last page' link
		}

		$start = $pageNumber - ($pageNumber % $numLinks) + 1;
		$end   = $start + $numLinks - 1;		
		
		$end   = min($totalPages, $end);
		
		$pagingLink = array();
		for($page = $start; $page <= $end; $page++)	{
			if ($page == $pageNumber) {
				$pagingLink[] = " $page ";   // no need to create a link to current page
			} else {
				if ($page == 1) {
					$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
				} else {	
					$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
				}	
			}
	
		}
		
		$pagingLink = implode(' | ', $pagingLink);
		
		// return the page navigation link
		$pagingLink = $first . $prev . $pagingLink . $next . $last;
	}
	
	return $pagingLink;
}


//pagination in user gallery photos
function getPagingQueryUserGalleryPhotos($sql, $itemPerPage = 4)
{
	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$page = (int)$_GET['page'];
	} else {
		$page = 1;
	}
	
	// start fetching from this row number
	$offset = ($page - 1) * $itemPerPage;
	
	return $sql . " LIMIT $offset, $itemPerPage";
}

/*
	Get the links to navigate between one result page to another.
	Supply a value for $strGet if the page url already contain some
	GET values for example if the original page url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php?c=12
	
	use "c=12" as the value for $strGet. But if the url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php
	
	then there's no need to set a value for $strGet
	
	
*/

function getPagingLinkUserGalleryPhotos($sql, $itemPerPage = 10, 
$strGet='$strGet')
{
	global $strGet;
	$id	= $_GET['id'];
    $strGet = "view=photos&id=$id";
	$result        = dbQuery($sql);
	$pagingLink    = '';
	$totalResults  = dbNumRows($result);
	$totalPages    = ceil($totalResults / $itemPerPage);
	
	// how many link pages to show
	$numLinks      = 10;

		
	// create the paging links only if we have more than one page of results
	if ($totalPages > 1) {
	
		$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
		

		if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
			$pageNumber = (int)$_GET['page'];
		} else {
			$pageNumber = 1;
		}
		
		// print 'previous' link only if we're not
		// on page one
		if ($pageNumber > 1) {
			$page = $pageNumber - 1;
			if ($page > 1) {
				$prev = " <a href=\"$self?page=$page&$strGet\">[Prev]</a> ";
			} else {
				$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
			}	
				
			$first = " <a href=\"$self?$strGet\">[First]</a> ";
		} else {
			$prev  = ''; // we're on page one, don't show 'previous' link
			$first = ''; // nor 'first page' link
		}
	
		// print 'next' link only if we're not
		// on the last page
		if ($pageNumber < $totalPages) {
			$page = $pageNumber + 1;
			$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
			$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
		} else {
			$next = ''; // we're on the last page, don't show 'next' link
			$last = ''; // nor 'last page' link
		}

		$start = $pageNumber - ($pageNumber % $numLinks) + 1;
		$end   = $start + $numLinks - 1;		
		
		$end   = min($totalPages, $end);
		
		$pagingLink = array();
		for($page = $start; $page <= $end; $page++)	{
			if ($page == $pageNumber) {
				$pagingLink[] = " $page ";   // no need to create a link to current page
			} else {
				if ($page == 1) {
					$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
				} else {	
					$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
				}	
			}
	
		}
		
		$pagingLink = implode(' | ', $pagingLink);
		
		// return the page navigation link
		$pagingLink = $first . $prev . $pagingLink . $next . $last;
	}
	
	return $pagingLink;
}

function buildCategoryOptions($catId = 0)
{
	$sql = "SELECT cat_id, cat_parent_id, cat_name
			FROM tbl_category
			ORDER BY cat_id";
	$result =& dbQuery($sql) or die('Cannot get Product. ' . mysql_error());

	$categories = array();
	while($row =& dbFetchArray($result)) {
		list($id, $parentId, $name) = $row;

		if ($parentId == 0) {
			// we create a new array for each top level categories
			$categories[$id] = array('name' => $name, 'children' => array());
		} else {
			// the child categories are put int the parent category's array
			$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
		}
	}

	// build combo box options
	$list = '';
	foreach ($categories as $key => $value) {
		$name     = $value['name'];
		$children = $value['children'];

		$list .= "<optgroup label=\"$name\">";

		foreach ($children as $child) {
			$list .= "<option value=\"{$child['id']}\"";
			if ($child['id'] == $catId) {
				$list.= " selected";
			}

			$list .= ">{$child['name']}</option>\r\n";
		}

		$list .= "</optgroup>";
	}

	return $list;
}

/* function displayAmount($amount)
{
	global $shopConfig;
	return $shopConfig['currency'] . number_format($amount,2);
}
 */

//pagination for order list
function getPagingQueryOrders($sql, $itemPerPage = 4)
{
	if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
		$page = (int)$_GET['page'];
	} else {
		$page = 1;
	}
	
	// start fetching from this row number
	$offset = ($page - 1) * $itemPerPage;
	
	return $sql . " LIMIT $offset, $itemPerPage";
}

/*
	Get the links to navigate between one result page to another.
	Supply a value for $strGet if the page url already contain some
	GET values for example if the original page url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php?c=12
	
	use "c=12" as the value for $strGet. But if the url is like this :
	
	http://www.phpwebcommerce.com/plaincart/index.php
	
	then there's no need to set a value for $strGet
	
	
*/

function getPagingLinkOrders($sql, $itemPerPage = 10, $strGet='view=order')
{
	$result        = dbQuery($sql);
	$pagingLink    = '';
	$totalResults  = dbNumRows($result);
	$totalPages    = ceil($totalResults / $itemPerPage);
	
	// how many link pages to show
	$numLinks      = 10;

		
	// create the paging links only if we have more than one page of results
	if ($totalPages > 1) {
	
		$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
		

		if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
			$pageNumber = (int)$_GET['page'];
		} else {
			$pageNumber = 1;
		}
		
		// print 'previous' link only if we're not
		// on page one
		if ($pageNumber > 1) {
			$page = $pageNumber - 1;
			if ($page > 1) {
				$prev = " <a href=\"$self?page=$page&$strGet\">[Prev]</a> ";
			} else {
				$prev = " <a href=\"$self?$strGet\">[Prev]</a> ";
			}	
				
			$first = " <a href=\"$self?$strGet\">[First]</a> ";
		} else {
			$prev  = ''; // we're on page one, don't show 'previous' link
			$first = ''; // nor 'first page' link
		}
	
		// print 'next' link only if we're not
		// on the last page
		if ($pageNumber < $totalPages) {
			$page = $pageNumber + 1;
			$next = " <a href=\"$self?page=$page&$strGet\">[Next]</a> ";
			$last = " <a href=\"$self?page=$totalPages&$strGet\">[Last]</a> ";
		} else {
			$next = ''; // we're on the last page, don't show 'next' link
			$last = ''; // nor 'last page' link
		}

		$start = $pageNumber - ($pageNumber % $numLinks) + 1;
		$end   = $start + $numLinks - 1;		
		
		$end   = min($totalPages, $end);
		
		$pagingLink = array();
		for($page = $start; $page <= $end; $page++)	{
			if ($page == $pageNumber) {
				$pagingLink[] = " $page ";   // no need to create a link to current page
			} else {
				if ($page == 1) {
					$pagingLink[] = " <a href=\"$self?$strGet\">$page</a> ";
				} else {	
					$pagingLink[] = " <a href=\"$self?page=$page&$strGet\">$page</a> ";
				}	
			}
	
		}
		
		$pagingLink = implode(' | ', $pagingLink);
		
		// return the page navigation link
		$pagingLink = $first . $prev . $pagingLink . $next . $last;
	}
	
	return $pagingLink;
}

?>
Return current item: Uiga Personal Portal