Location: PHPKode > projects > phpMyPrepaid > phpmyprepaid/www/include/divers/functions.php
<?php


function check_access($oreon,$status) {
	if (!isset($oreon->user)) {
	 print '<p class="error">Error user not set';
	 exit();
	 return False;
	}

	if ($oreon->user->get_status()<$status) {
	print '<p class="error">Error ! you have no access to this features </p>';
	return False;
	}
return True;
}

// get_conversion: convert a integer $val to the specific type Conversion 1 Go 1000 Mo .... every to second if of type time and octet if of type octets
function get_conversion($val,$typec,$oftype) {
	if ($oftype=='Time') {
		switch ($typec) {
			Case 'Minutes' :
				return $val*60;
				break;
			Case 'Hours' :
				return $val*3600;
				break;
			Case 'Years' :
				return $val*365*24*3600;
				break;
			Case 'Days' :
				return $val*24*3600;
				break;
			Case 'Months' :
				return $val*31*24*3600;
				break;
	 }	 
	}
	else if ($oftype=='Octet') 
	{
		switch ($typec) {
			Case 'Mo' :
				return $val*1000*1000;
				break;
			Case 'Go' :
				return $val*1000*1000*1000;
				break;
			Case 'To' :
				return $val*1000*1000*1000*1000;
				break;
	}
	}
}

function crypt_acct_passwd($type,$passwd) 
{
	switch($type) 
	{
		CASE 'clear' :
			return $passwd;
			break;
		CASE 'crypt' :
			return crypt($passwd);
			break;
		CASE 'md5' :
			return md5($passwd);
			break;
	}
}

function array_to_json_string($arraydata) {
     $output = "";
     $output .= "{";
     foreach($arraydata as $key=>$val){
     if (is_array($val)) {
	  $output .= "\"".$key."\" : [{";
          foreach($val as $subkey=>$subval){
           $output .= "\"".$subkey."\" : \"".$subval."\",";
           }
           $output .= "}],";
      } else {
         $output .= "\"".$key."\" : \"".$val."\",";
      }							        }
     $output .= "}";
     return $output;
}


function file_replace ($search, $replace, $filename) {
	 if (file_exists($filename)) {
		 $cnt = file_get_contents($filename);
		 if (strstr($cnt, $search)) {
			 $cnt = str_replace($search, $replace, $cnt);
			 return file_put_contents("/tmp/".$filename.".tmp", $cnt);
		 }
		 return true;
	 }
	 return false;
 }

function cdateformat_calendar($dateF)
{
	$ch1=str_replace("d","%d",$dateF);
	$ch1=str_replace("m","%m",$ch1);
	$ch1=str_replace("Y","%Y",$ch1);
	$ch1=str_replace("H","%l",$ch1);
	$ch1=str_replace("i","%M",$ch1);
return $ch1;
}

function generate_salt()
{
  // Declare $salt
  $localsalt = '';

  // And create it with random chars
  for ($i = 0; $i < 3; $i++)
    { 
      $localsalt .= chr(rand(35, 126));
    }
  return $localsalt;
}


function getLoc($locID)
{
  $oreon=$_SESSION['oreon'];
  $query="SELECT LocationName FROM locations where ID='$locID' ";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  while ($row = $oreon->database->database->fetch_object($result)) {
    $array[] = $row;
    
    $location = ($row->LocationName);
  }
}

function getLocDomain($locID)
{
  $oreon=$_SESSION['oreon'];
  $query="SELECT LocationDomain FROM locations where ID='$locID' ";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  while ($row = $oreon->database->database->fetch_object($result)) {
    $array[] = $row;
    $location = ($row->LocationDomain);
  }
  return $location;
}

function getLocationNameHeader($user)
{
	$oreon=$_SESSION['oreon'];
  if ( $user->get_status()=='3')
	  $query="SELECT ID, LocationName,LocationDomain,LocationState,LocationCity,LocationCountry FROM locations";
  else 
  $query="SELECT ID, LocationName,LocationDomain,LocationState,LocationCity,LocationCountry FROM locations,user_location WHERE locations.ID=user_location.locationid and userid='".$user->get_id()."'";
    $result = $oreon->database->database->query($query) or die("Query database error !");
return $result;
}

function getLocationName($user)
{
  $oreon=$_SESSION['oreon'];
  if ($user->get_status()=='3')
	  $query="SELECT ID, LocationName,LocationDomain,LocationState,LocationCity,LocationCountry FROM locations";
  else
	  $query="SELECT ID, LocationName,LocationDomain,LocationState,LocationCity,LocationCountry FROM locations,user_location WHERE locations.ID=user_location.locationid and userid='".$user->get_id()."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
return $result;
}

function getLocation($locID)
{
  $oreon=$_SESSION['oreon'];
	  $query="SELECT ID, LocationName,LocationDomain,LocationState,LocationCity,LocationCountry FROM locations where ID='".$locID."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
	 
return $result;
}

function existLocationName($locName)
{
  $oreon=$_SESSION['oreon'];
	  $query="SELECT ID, LocationName FROM locations where LocationName='".$locName."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
	  $row = $oreon->database->database->fetch_object($result);
	  if ($row and $row->LocationName!='') return 1;
	  return 0;
}

function getLocationID($loc_name)
{
  $oreon=$_SESSION['oreon'];
  $query="SELECT ID FROM locations WHERE LocationName='".$loc_name."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $row = $oreon->database->database->fetch_object($result);
return $row->ID;
}

function getLocationUser($user)
{
  $oreon=$_SESSION['oreon'];
	$query="SELECT locationid FROM user_location WHERE userid='".$user."'";
	$result = $oreon->database->database->query($query) or die("Query database error !");
	while ($row = $oreon->database->database->fetch_object($result)) {
		$array[] = $row;
		$location = ($row->locationid);
	}
	return $location;
}

function get_local_name($location_id)
{
  $oreon=$_SESSION['oreon'];
	    $search = "SELECT LocationName FROM locations WHERE ID='$location_id'";
	        $result = $oreon->database->database->query($search) or die("Query database error !");
	        $row = $oreon->database->database->fetch_object($result);
		    $resf= $row->LocationName;
		    return $resf;
}




function getCountryCodeE164($iso_code)
{
  $oreon=$_SESSION['oreon'];
	$query="SELECT iso_name FROM isocode WHERE iso_code='$iso_code'";
	$result = $oreon->database->database->query($query) or die("Query database error !");
	$row = $oreon->database->database->fetch_object($result);
	$country=$row->iso_name;

	if ($country!="") {
		$query="SELECT country_code FROM countrycode WHERE country_name REGEXP('$country')";
		$result = $oreon->database->database->query($query) or die("Query database error !");
		$row = $oreon->database->database->fetch_object($result);
	}
	if (isset($row->country_code))
	return $row->country_code;
  return '';
}

function keygen($lgth,$type,$use_caps,$use_numeric) {
	
	$lgthp=$lgth;
	if ($lgthp<3) $lgthp=3;
	$pass="";
	$tempstring ="abcdefghijklmnopqrstuvwxyz";
	if ($use_caps==1)
			$tempstring=$tempstring."ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	if ($use_numeric)
			$tempstring=$tempstring."0123456789";
		
	if ($type=="username"){
		for($length = 0; $length < $lgthp; $length++) {
			$temp = str_shuffle($tempstring);
			$char = mt_rand(0, strlen($temp));
			if (isset($temp[$char]))
			$pass .= $temp[$char];

		}
	}
	else
		for($length = 0; $length < $lgthp; $length++) {
			$temp = str_shuffle($tempstring);
			$char = mt_rand(0, strlen($temp));
			if (isset($temp[$char]))
				$pass .= $temp[$char];
		}
	
	return $pass;
}

function user_register($username, $password, $location, $priv) {
  // Get a salt using our function
  $oreon=$_SESSION['oreon'];
  $salt = generate_salt();

  // Now encrypt the password using that salt
  $encrypted = md5(md5($password).$salt);

  // And lastly, store the information in the database
  //DEBUG
  //echo('DEBUG' );
  //echo($username );
 // echo($encrypted );
 // echo($salt );
  //echo($priv );
  if ($priv=='Admin')
  {
   admin_register($username,$password);
  }  
  $query="SELECT ID, LocationName FROM locations where ID='$location' ";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  while ($row = $oreon->database->database->fetch_object($result)) {
    $array[] = $row;
    $location = ($row->LocationName);
  }
  //echo($location ); DEBUG
  $query = "insert into $location (username, password, salt, priv) values ('$username', '$encrypted', '$salt', '$priv')";
  $oreon->database->database->query ($query) or die("Query database error !");
}

function admin_register($username, $password) {
  $oreon=$_SESSION['oreon'];
  // Get a salt using our function
  $salt = generate_salt();
  // Now encrypt the password using that salt
  $encrypted = md5(md5($password).$salt);
  // And lastly, store the information in the database
  $query = "insert into admin (username, password, salt) values ('$username', '$encrypted', '$salt')";
  $oreon->database->database->query ($query) or die("Query database error !");
}

function user_login($username, $password, $locID)
{
  $oreon=$_SESSION['oreon'];
  // Try and get the salt from the database using the username
  $query = "select salt from users where username='$username' and Location='$locID' limit 1";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $user = $oreon->database->database->fetch_array($result);

  // Using the salt, encrypt the given password to see if it
  // matches the one in the database
  $encrypted_pass = md5(md5($password).$user['salt']);

  // Try and get the user using the username & encrypted pass
  $query = "select userid, username, password, priv from users where username='$username' and password='$encrypted_pass' and Location='$locID'";
	
  $result = $oreon->database->database->query($query);
  while ($row = $oreon->database->database->fetch_object($result)) {
    $array[] = $row;
    $username = ($row->username);
    $userid = ($row->userid);
    $pswd = ($row->password);
    $priv = ($row->priv);
  }
		 
  $user = $oreon->database->database->fetch_array($resUlt);
  $numrows = $oreon->database->database->result_num_rows($result);

  // Now encrypt the data to be stored in the session
  $encrypted_id = md5($user['userid']);
  $encrypted_name = md5($user['username']);
	
  // Store the data in the session
  if($encrypted_pass == $pswd){
    $_SESSION['priv'] = $priv;
    $_SESSION['locationID'] = $locID;
    $_SESSION['userid'] = $userid;
    $_SESSION['usernamel'] = $username;
    $_SESSION['encrypted_id'] = $encrypted_id;
    $_SESSION['encrypted_name'] = $encrypted_name;  }

  if ($numrows == 1)
    {
      return 'Correct';
    }
  else
    {
      return false;
    }
}

function admin_login($username, $password)
{
  $oreon=$_SESSION['oreon'];
  $query = "select salt from admin where username='$username'limit 1";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $user = $oreon->database->database->fetch_array($result);
  // Using the salt, encrypt the given password to see if it
  // matches the one in the database
  $encrypted_pass = md5(md5($password).$user['salt']);

  // Try and get the user using the username & encrypted pass
  $query = "select ID, username, password from admin where username='$username' and password='$encrypted_pass'";
  $result = $oreon->database->database->query($query);
  while ($row = $oreon->database->database->fetch_object($result)) {
    $array[] = $row;
    $username = ($row->username);
    $adminid = ($row->ID);
    $pswd = ($row->password);
  }

  $user = $oreon->database->database->fetch_array($result);
  $numrows = $oreon->database->database->result_num_rows($result);

  // Now encrypt the data to be stored in the session
  $encrypted_id = md5($adminid);
  $encrypted_name = md5($user['username']);

  if($encrypted_pass == $pswd){
    $_SESSION['adminid'] = $adminid;
    $_SESSION['usernamel'] = $username;
    $_SESSION['encrypted_id'] = $encrypted_id;
    $_SESSION['encrypted_name'] = $encrypted_name;
	
  }

  if ($numrows == 1)
    {
      return 'Correct';
    }
  else
    {
      return false;
    }
}

function user_logout()
{
	// End the session and unset all vars
	global $_SESSION;
	Session::stop();
	Session::destroy();
	$_SESSION["oreon"]->database->database->close();
	unset($_SESSION["oreon"]);
}

function is_authed()
{
  // Check if the encrypted username is the same
  // as the unencrypted one, if it is, it hasn't been changed
  if (isset($_SESSION['usernamel']) && (md5($_SESSION['usernamel']) == $_SESSION['encrypted_name']))
    {
      return true;
    }
  else
    {
      return false;
    }
}

function is_admin()
{
  if(isset($_SESSION['adminid']) && (md5($_SESSION['adminid']) == $_SESSION['encrypted_id'])){
    return true;
  }else{
    return false;
  }
}

function add_loc($location, $domain, $state, $city, $country,$userid)
{
  $oreon=$_SESSION['oreon'];
	 if (existLocationName($location))
		 return "Error location already exist !";
  // first add the new location to the locations table
  $ct=getCountryCodeE164($country);
$query = "insert into locations (LocationName, LocationDomain, LocationState, LocationCity, LocationCountry,locationE164Country ) values ('$location', '$domain', '$state', '$city', '$country','$ct')";
  $oreon->database->database->query ($query) or die("Query database error !");
											
  
  // we don't know the ID of the location we just added so we query for it
   $query="select ID from locations where LocationName='$location'";
   $result= $oreon->database->database->query ($query) or die("Query database error !");
   while ($row = $oreon->database->database->fetch_object($result)) {
  	$array[] = $row;
  	$ID = ($row->ID);
   }

   $query = "insert into user_location (locationid, userid,statusid) values ('$ID', '$userid',$oreon->user->get_status())";
   $oreon->database->database->query ($query) or die("Query database error !");

}

function del_loc($location) 
{
  $oreon=$_SESSION['oreon'];
  $q1="DELETE  From locations WHERE locationName='". $location ."'";
  $insert1 = $oreon->database->database->query($q1) or die("Query database error !");
  $locationID=get_location_id($location);
  del_all_ap($locationID);
  $q2="DELETE From AP WHERE locationID='". $locationID ."'";
  $insert1 = $oreon->database->database->query($q2) or die("Query database error !");
  $q3="DELETE From ap_config WHERE location_id='". $locationID ."'";
  $insert3 = $oreon->database->database->query($q3) or die("Query database error !");
  $q4="DELETE From chillispot WHERE location_id='". $locationID ."'";
  $insert4 = $oreon->database->database->query($q4) or die("Query database error !");
  $q5="DELETE From phpmyprepaid WHERE location_id='". $locationID ."'";
  $insert5 = $oreon->database->database->query($q5) or die("Query database error !");
  $q6="DELETE From ssh_config WHERE location_id='". $locationID ."'";
  $insert6 = $oreon->database->database->query($q6) or die("Query database error !");
  $q7="DELETE From BillingPlan WHERE LocationId='". $locationID ."'";
  $insert7 = $oreon->database->database->query($q7) or die("Query database error !");
  $q8="DELETE From radius_config WHERE location_id='". $locationID ."'";
  $insert8 = $oreon->database->database->query($q8) or die("Query database error !");
  $q9="DELETE From user_location WHERE locationid='". $locationID ."'";
  $insert9 = $oreon->database->database->query($q9) or die("Query database error !");
  $q2="DROP TABLE IF EXISTS ". $location; 
  $insert1 = $oreon->database->database->query($q2) or die("Query database error !");
  //DELETE ALL USER FROM THIS LOCATION
  $query="select UserName from  userinfo where LocationID='$locationID'";
  $result= $oreon->database->database->query ($query) or die("Query database error !");
  while ($row = $oreon->database->database->fetch_object($result)) {
	  $array[] = $row;
	  $uname = ($row->UserName);
	  delete_user(uname);
  }

  echo "<p class=\"information\">Successfully deleted Location ".$location." </p>";
 unset($_SESSION['locID']);
 unset($_SESSION['LocName']);
}

function del_all_ap($locid) 
{
  $oreon=$_SESSION['oreon'];
	$q="SELECT ID FROM AP WHERE locationid='$locid'"; 
	$result = $oreon->database->database->query($q) or die("Query database error !");
	while ($row = $oreon->database->database->fetch_object($result)) {
		del_ap($row->ID);
	}

}

function del_ap($apid) 
{
  $oreon=$_SESSION['oreon'];
	$nasid=get_nasid($apid);	
	$q1="DELETE  From AP Where ID='". $apid ."'";
	$insert1 = $oreon->database->database->query($q1) or die("Query database error !");
	$q2="DELETE  From nas Where ID='". $nasid ."'";
	$insert1 = $oreon->database->database->query($q1) or die("Query database error !");
}

function is_belong_group($username,$gpname,$locid) 
{

  $oreon=$_SESSION['oreon'];
  $query = "SELECT id from usergroup where UserName='".$username."' and GroupName='".$gpname."' AND location_id='".$locid."'";
  $result = $_SESSION["oreon"]->database->database->query($query);
  $numrows = $oreon->database->database->result_num_rows($result);
  print $query;
  if ($numrows==1) return true;
  
  return 0;
}

function get_group_name($gpid) 
{

  $oreon=$_SESSION['oreon'];
  $query = "SELECT gp_name from group_template where ID='".$gpid."'";
  $result = $_SESSION["oreon"]->database->database->query($query);
  $row = $oreon->database->database->fetch_array($result);
  return $name=$row['gp_name'];
}

function del_group($gpid,$locID) 
{
  $oreon=$_SESSION['oreon'];
	$gpname=get_group_name($gpid);	
	$q1="DELETE  From group_template Where ID='". $gpid ."'";
	$result = $_SESSION["oreon"]->database->database->query($q1);
	$q1="DELETE  From radgroupcheck Where GroupName='".$gpname."' AND location_id='". $locID ."'";
	$result = $_SESSION["oreon"]->database->database->query($q1);
	$q1="DELETE  From radgroupreply Where GroupName='".$gpname."' AND location_id='". $locID ."'";
	$result = $_SESSION["oreon"]->database->database->query($q1);
	$q1="DELETE  From usergroup Where GroupName='".$gpname."' AND location_id='". $locID ."'";
	$result = $_SESSION["oreon"]->database->database->query($q1);
}

function insert_group($username,$gp_name,$lid)
{
  $oreon=$_SESSION['oreon'];
	$req  = "INSERT INTO `usergroup` ( ";
	             $req  .= "`GroupName`, `UserName`,`location_id`)";
	             $req  .= " VALUES (";
		     $req  .= "'".addslashes($gp_name)."', ";
		     $req  .= "'".addslashes($username)."', ";
		     $req  .= "'".addslashes($lid)."')";
	$_SESSION["oreon"]->database->database->query($req);

}

//RADIUS PROFILE
//
function insert_radius_profile($username,$bpname,$lid)
{
  $oreon=$_SESSION['oreon'];
	$q1="SELECT RadiusProfileName From  bpradiusprofile  Where BpName='".$bpname."' AND location_id='". $lid ."'";
	$result = $_SESSION["oreon"]->database->database->query($q1);
	while ($row = $oreon->database->database->fetch_object($result)) {
		echo " RADIUS PROFILE ".$row->RadiusProfileName;
		$q2="SELECT Attribute,op,Value,db From  radiusprofile  Where RadiusProfileName='".$row->RadiusProfileName."' AND location_id='". $lid ."'";
		
		$result2 = $_SESSION["oreon"]->database->database->query($q2);
		while ($row2 = $oreon->database->database->fetch_object($result2)) {
			 $q3= "INSERT INTO ".$row2->db." (UserName, " .
				                     " Attribute, op, Value)" .
				                     " VALUES('$username', " .
			                             " '".$row2->Attribute."', '".$row2->op."', '".$row2->Value."' )";
			      $_SESSION["oreon"]->database->database->query($q3);

		}  	
	}
	
}

function insert_user_radius_profile($username,$bpname,$lid)
{
  $oreon=$_SESSION['oreon'];
		echo " RADIUS PROFILE ".$bpname;
		$q2="SELECT Attribute,op,Value,db From  radiusprofile  Where RadiusProfileName='".$bpname."' AND location_id='". $lid ."'";
		
		$result2 = $_SESSION["oreon"]->database->database->query($q2);
		while ($row2 = $oreon->database->database->fetch_object($result2)) {
			 $q3= "INSERT INTO ".$row2->db." (UserName, " .
				                     " Attribute, op, Value)" .
				                     " VALUES('$username', " .
			                             " '".$row2->Attribute."', '".$row2->op."', '".$row2->Value."' )";
			      $_SESSION["oreon"]->database->database->query($q3);

		}  	
	
}

function get_radiusprofile_id($rpname) 
{
  $oreon=$_SESSION['oreon'];

  $query = "SELECT ID from radiusprofile_template where rp_name='".$rpname."'";
  $result = $_SESSION["oreon"]->database->database->query($query);
  $row = $oreon->database->database->fetch_array($result);
  return $name=$row['ID'];
}

function get_radiusprofile_name($rpid) 
{

  $oreon=$_SESSION['oreon'];
  $query = "SELECT rp_name from radiusprofile_template where ID='".$rpid."'";
  $result = $_SESSION["oreon"]->database->database->query($query);
  $row = $oreon->database->database->fetch_array($result);
  return $name=$row['rp_name'];
}

function del_radiusprofile($rpid,$locID) 
{
  $oreon=$_SESSION['oreon'];
	$rpname=get_radiusprofile_name($rpid);	
	$q1="DELETE  From radiusprofile_template Where ID='". $rpid ."'";
	$result = $_SESSION["oreon"]->database->database->query($q1);
	$q1="DELETE  From radiusprofile Where RadiusProfileName='".$rpname."' AND location_id='". $locID ."'";
	$result = $_SESSION["oreon"]->database->database->query($q1);
}


function modify_loc($location, $domain, $state, $city, $country)
{
  $oreon=$_SESSION['oreon'];
  $ct=getCountryCodeE164($country);
  // first add the new location to the locations table
  $query = "UPDATE locations SET LocationDomain='$domain',LocationState='$state',LocationCity='$city',LocationCountry='$country',locationE164Country='$ct' WHERE LocationName='$location';";
  $oreon->database->database->query ($query) or die("Query database error !");
}

function show_AP()
{
  $oreon=$_SESSION['oreon'];
  echo('<table>');
  $id=$_SESSION['locID'];
  $query="SELECT ID, ipaddress, dnsname FROM AP WHERE LocationID ='$id'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $nr = $oreon->database->database->result_num_rows($result);
  if ($nr==0){
	  echo "<tr><td><b>No access point associated with this location.</td></tr></table><br><hr>";
	  return;
  }
  
  //if (!isset($count)) $count=-1;
  if (!isset($count)) $count=0;
 
  while ($row = $oreon->database->database->fetch_object($result)) {
    //THREE AP per table row
    if($count==3)
    { 
    echo('</tr>');
    $count=0; 
    }
    
    if($count==0){ echo('<tr>');}
    $array[] = $row;
    $ID = ($row->ID);
    $IP = ($row->ipaddress);
    $dnsname = ($row->dnsname);

    // PING TEST TO SEE IF THE AP is really up disabled  

    $pipes = array();
       $descriptorspec = array(
	                    0 => array("pipe", "r"),
			                 1 => array("pipe", "w"),
					              2 => array("file", "/tmp/errorpingphpmyprepaid", "w"),
						                  );
    $process = proc_open('ping '.$IP.' -c1', $descriptorspec, $pipes); 
    $contents = stream_get_contents($pipes[1]);
    proc_close($process);
    if (ereg("100%",$contents) or $contents=="")

    printf('<td><input class="image"  type="image" value="submit" name="submit" alt="Inactive" title="Inactive" src="images/redled.png" ></td>');
    else
    printf('<td><input class="image"  type="image" value="submit" name="submit" alt="Active" title="Active" src="images/greenled.png" ></td>');

    $ct = 0;
    //	while (list(,$val) = each($output)) :
    //		unset($down);
    //$ct = $ct+1;
    //		print"<p>";
    //	if($val =="Note: Host seems down. If it is really up, but blocking our ping probes, try -P0"){
    //		$down=1;
    //	}
    //		print"$ct";
    //	if($ct==4 && $down !=1){
    //			print "$val";
    //		print"<a href=\"http://$IP\">$IP</a>";
    //		}
    //		print"</p>";
    $ct++;
    //	endwhile;
		
		
			
    echo('<td class="imagesap" >');
    //printf('</form>'); // debug
    //DISABLE CAUSE IT DOESNT SEEMS TO WORK OR WORK FOR ONE TYPE OF AP SWONG
    printf('<form action="phpmyprepaid.php" method="post">');
   echo("<input type=\"hidden\" name=\"buttonID\" value=\"AP_selected\">");
   echo("<input type=\"hidden\" name=\"APID\" value=\"$ID\">");
   echo("<input type=\"hidden\" name=\"dnsname\" value=\"$dnsname\">");
   echo("<input type=\"hidden\" name=\"LocationID\" value=\"$id\">");
   echo("<input type=\"submit\" class=\"smallButtonLoc\" name=\"submit\" value=\"$dnsname\">");
   printf('</form>');
   // echo "$dnsname";
    echo('</td>');
    $count=($count + 1);
  }
  if($count==1){ echo('<td></td><td></td><td></td></tr>');} // this cleans
  if($count==2){ echo('<td></td><td></td></tr>'); }         // up the end
  if($count==3){ echo('<td></td></tr>'); }                  // of the table
  if($count==4){ echo('</tr>'); }                           // depending on count
  echo "</table>";
  echo('<br><hr>');
	 
}

function get_usg($url, $user, $pass)
{
  require_once(dirname(__FILE__).'/class_http.php');
	
  // first we pull the usg data
  $h = new http();
  $h->fetch($url, 0, null, "$user","$pass");
  if (!$h->fetch($url)) {
    $usg="error";
  }else{
    $usg = http::table_into_array($h->body,"MAC",1, null);
  }
  return $usg;
}

function get_ap_clients($url, $user, $pass)
{
  require_once(dirname(__FILE__).'/class_http.php');
  $h = new http();
  $h->fetch($url, 0, null, "$user","$pass");
  if (!$h->fetch($url)) {
    $clients="error";
  }else{
    $clients = http::APclients2($h->body,"No.", 1, null);
  }
  return $clients;
}



function show_loc($user)
{
  $oreon=$_SESSION['oreon'];
 	
  $result=getLocationName($user);
  //if (!isset($count)) $count=-1;
  if (!isset($count)) $count=0; //FIXED - SWong
  $i=0;
  $count=0;
  print '<style type="text/css">
	  .dragme { cursor: move }
  </style>
  ';
  print '<script type="text/javascript">
  var ie = document.all;
  var nn6 = document.getElementById &&! document.all;

  var isdrag = false;
  var x, y;
  var dobj;
  
  function movemouse( e ) {
      if( isdrag ) {
        dobj.style.left = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
        dobj.style.top  = nn6 ? ty + e.clientY - y : ty + event.clientY - y;
        return false;
     }
}

function selectmouse( e ) {
  var fobj = nn6 ? e.target : event.srcElement;
  var topelement = nn6 ? "HTML" : "BODY";

  while (fobj.tagName != topelement && fobj.className != "dragme") {
        fobj = nn6 ? fobj.parentNode : fobj.parentElement;
  }

  if (fobj.className=="dragme") {
      isdrag = true;
      dobj = document.getElementById("styled_popup");
      tx = parseInt(dobj.style.left+0);
      ty = parseInt(dobj.style.top+0);
      x = nn6 ? e.clientX : event.clientX;
      y = nn6 ? e.clientY : event.clientY;
      document.onmousemove=movemouse;
      return false;
    }
}


function styledPopupClose() {
	  document.getElementById("styled_popup").style.display = "none";
}

document.onmousedown=selectmouse;
document.onmouseup=new Function("isdrag=false");


function  showGoogle(loc,city,state,country) {
   document.getElementById("styled_popup").style.display="block";
}

function  closeGoogle(loc,city,state,country) {
	document.getElementById("styled_popup").style.display = "none";
}
</script>
';
  echo "<table style=\"width: 678px;\"><tr><td>";
  while ($row = $oreon->database->database->fetch_object($result)) {
	  if ($count==3)
	  {
		  echo '</tr><tr><td>';
		  $count=0;
	  }

	 //BEGIN OF TABLE DEFINITION 
	  echo "<table  border=\"5\" cellpadding=\"3\" cellspacing=\"3\"> <tbody><tr>";
	  $array[] = $row;
	  $id = ($row->ID);
	  $loc = ($row->LocationName);
	  $domain=$row->LocationDomain;
	  $city=$row->LocationCity;
	  $state=$row->LocationState;
	  $country=$row->LocationCountry;
	  $q="select area_short_name from areacode where area_code='".$state."'";
	  $insert1 = $oreon->database->database->query($q) or die("Query database error !");
	  $res=$oreon->database->database->fetch_object($insert1);
	  $state=$res->area_short_name;

print '<a href="#" onmouseover="showGoogle() return false" onmouseout="closeGoogle() return false">';
	  echo "<td ><img src=\"images/wifi_locations.png\" align=\"middle\" ALT=\"Location $state\"></td>";
	  echo "<td colspan=\"2\" rowspan=\"1\">";
	  printf('<form action="phpmyprepaid.php" method="post">');
	  echo("<div><input type=\"hidden\" name=\"buttonID\" value=\"location_selected\"></div>");
	  echo("<div><input type=\"hidden\" name=\"locID\" value=\"$id\"</div>");
	  echo("<div><input type=\"hidden\" name=\"LocationName\" value=\"$loc\"></div>");
	  echo("<div><input type=\"submit\" class=\"smallButtonLoc\" name=\"submit\" value=\"$loc\"></div>");

	  echo '</td>';
	  
	  echo '<tr>';
	  echo('<td  class="gpcell" >Domain :'); 
	  echo('</td>');
	  echo('<td class="fieldcell" >');
	  echo($domain);
	  echo('</td></tr>');
	  
	  echo '<tr>';
	  echo('<td  class="gpcell" >Country :');
	  echo('</td>');
	  echo('<td class="fieldcell" >');
	  echo($country);
	  echo('</td></tr>');
	  
	  echo '<tr>';
	  echo('<td  class="gpcell" >State :');
	  echo('</td>');
	  echo('<td class="fieldcell" >');
	  echo($state);
	  echo('</td></tr>');
	  
	  echo '<tr>';
	  echo('<td class="gpcell" >City :');
	  echo('</td>');
	  echo('<td class="fieldcell" >');
	  echo($city);
	  echo('</td></tr>');
	  
	  
	  
	  printf('</form>'); 
	  echo('</tbody></table></td><td>');
	 //END OF TABLE DEFINITION 
	  
	  $count=($count + 1);
  }
  echo '</td></tr></tbody></table>';
}



function hasSpace($input)
{
  if (preg_match("/ /", "$input")) {
    return TRUE;
  }else{
    return FALSE;
  }
}

function hasPeriod($input)
{	
  if (preg_match("/\./", "$input")) {
    return TRUE;
  } else {
    return FALSE;
  }
}

		
function time2str($time)
{
  $str='';
  $time = floor($time);
  if (!$time)
    return "0 seconds";
  $d = $time/86400;
  $d = floor($d);
  if ($d){
    $str .= "$d days, ";
    $time = $time % 86400;
  }
  $h = $time/3600;
  $h = floor($h);
  if ($h){
    $str .= "$h hours, ";
    $time = $time % 3600;
  }
  $m = $time/60;
  $m = floor($m);
  if ($m){
    $str .= "$m minutes, ";
    $time = $time % 60;
  }
  if ($time)
    $str .= "$time seconds, ";
  $str = ereg_replace(', $','',$str);

  return $str;
}

function time2strclock($time)
{
  $time = floor($time);
  if (!$time)
    return "00:00:00";

  $str["hour"] = $str["min"] = $str["sec"] = "00";
  $h = $time/3600;
  $h = floor($h);
  if ($h){
    if ($h < 10)
      $h = "0" . $h;
    $str["hour"] = "$h";
    $time = $time % 3600;
  }
  $m = $time/60;
  $m = floor($m);
  if ($m){
    if ($m < 10)
      $m = "0" . $m;
    $str["min"] = "$m";
    $time = $time % 60;
  }
  if ($time){
    if ($time < 10)
      $time = "0" . $time;
  }
  else
    $time = "00";
  $str["sec"] = "$time";
  $ret = "$str[hour]:$str[min]:$str[sec]";

  return $ret;
}


function date_display($tstamp)
{
  $cy=date('Y',$tstamp);
  $cm=date('n',$tstamp);
  $cd=date('d',$tstamp);
  $ch=date('G',$tstamp);
  $ci=date('i',$tstamp);
  $cs=date('s',$tstamp);
  //c stand for current
  // 
  //***************
  //  change value between * A/C to your needs
  $y=date('Y');
  $m=date('n');
  $d=date('d');
  $h=date('G');
  $i=date('i');
  $s=date('s');
  //
  if(is_leep($cy))
    {
      $marray=array('1'=>31,'2'=>29,'3'=>31,
		    '4'=>30,'5'=>31,'6'=>30,
		    '7'=>31,'8'=>31,'9'=>30,
		    '10'=>31,'11'=>30,'12'=>31);
    }
  else
    {
      $marray=array('1'=>31,'2'=>28,'3'=>31,
		    '4'=>30,'5'=>31,'6'=>30,
		    '7'=>31,'8'=>31,'9'=>30,
		    '10'=>31,'11'=>30,'12'=>31);
    }   
  //
  //for second
  //for minutes 
  if($ci >= $i)
    {
      $i=$ci-$i;
    }
  else
    {
      $ch--;
      $ci=$ci + 60;
      $i=$ci-$i;
    }
  //for hour
  if($ch >= $h)
    {
      $h=$ch-$h;

    }
  else
    {
      $cd--;
      $ch=$ch + 60;
      $h=$ch-$h;
    }
  //days
  if($cd >= $d)
    {
      $d=$cd-$d;
    }
  else
    {
      $temp=$marray[$cm];
      $cm--;
      $cd=$cd + $temp;
      $d=$cd-$d;
    }
  //for month
  if($cm >= $m)
    {
      $m=($cm - $m);
    }
  else
    {
      $cy--;
      $cm=$cm + 12;
      $m=$cm-$m;
    }
  //for year
  $y=$cy-$y;
  // 
  $year="";
  $mth="";
  $day="";
  if ($h<0 or $i<0 or $s<0)
    return 0; 
  if ($y>=0)
    $year=$y. " Year(s) ";
  else return 0;
  if ($m>=0)
    $mth=$m. " Month(s) ";
  else return 0;
  if ($d>=0)
    $day=$d. " Day(s) ";
  else return 0;
  $date=$year.$mth.$day." ".$h." Hours ".$i." Min";
  return $date;
}

//check whether leep year or not
function is_leep($y)
{
  if($y % 4 == 0 && $y % 100 != 0)
    {
      return 1;
    }
  if($y % 100 == 0 && $y % 400 == 0)
    {
	    return 1;

    }
  return 0;   
}

function date2timediv($date,$now)
{
  list($day,$time)=explode(' ',$date);
  $day = explode('-',$day);
  $time = explode(':',$time);
  $timest = mktime($time[0],$time[1],$time[2],$day[1],$day[2],$day[0]);
  if (!$now)
    $now = time();
  return ($now - $timest);
}

function date2time($date)
{
  list($day,$time)=explode(' ',$date);
  $day = explode('-',$day);
  $time = explode(':',$time);
  $timest = mktime($time[0],$time[1],$time[2],$day[1],$day[2],$day[0]);
  return $timest;
}

function bytes2str($bytes)
{
  $bytes=floor($bytes);
  if ($bytes > 536870912)
    $str = sprintf("%5.2f GBs", $bytes/1073741824);
  else if ($bytes > 524288)
    $str = sprintf("%5.2f MBs", $bytes/1048576);
  else
    $str = sprintf("%5.2f KBs", $bytes/1024);

  return $str;
}

function octets2str($bytes)
{
  $bytes=floor($bytes);
  if ($bytes > 512000000)
    $str = sprintf("%5.2f Go", $bytes/1000000000);
  else if ($bytes > 512000)
    $str = sprintf("%5.2f Mo", $bytes/1000000);
  else
    $str = sprintf("%5.2f Ko", $bytes/1000);
  return $str;
}


function nothing($ret)
{
  return $ret;
}

function check_defaults($val,$op,$def)
{
  for($i=0;$i<$def[count];$i++){
    if ($val == $def[$i] && ($op == '' || $op == $def[operator][$i]))
      return 1;
  }

  return 0;
}

function delete_user($name)
{
  $oreon=$_SESSION['oreon'];
  $q1="DELETE  From radcheck Where UserName='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q1);
  $q2="DELETE  From radacct Where UserName='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q2);
  $q3="DELETE  From userinfo Where UserName='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q3);
  $q4="DELETE  From radpostauth Where user='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q4);
  $q6="DELETE  From radreply Where UserName='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q6);
  $q6="DELETE  From mtotacct Where UserName='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q6);
  $q6="DELETE  From totacct Where UserName='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q6);
  $q6="DELETE  From usergroup Where UserName='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q6);
  return "Successfully deleted user : ".$name."<br><br>";
}

function delete_user_acct($name)
{
  $oreon=$_SESSION['oreon'];
  $q2="DELETE  From radacct Where UserName='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q2);
  $q6="DELETE  From mtotacct Where UserName='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q6);
  $q6="DELETE  From totacct Where UserName='". $name ."'";
  $result = $_SESSION["oreon"]->database->database->query($q6);
  return "Successfully deleted user accounting for : ".$name."<br><br>";
}


function get_location_name($id)
{
  $oreon=$_SESSION['oreon'];
  $query = "SELECT LocationName from locations where ID='".$id."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $row = $oreon->database->database->fetch_array($result);
  return $name=$row['LocationName'];
  
}

function get_location_id($id)
{
  $oreon=$_SESSION['oreon'];
  $query = "SELECT ID from locations where LocationName='".$id."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $row = $oreon->database->database->fetch_array($result);
  return $name=$row['ID'];
}  

function get_plan_name($id)
{
  $oreon=$_SESSION['oreon'];
  $query = "SELECT NameBp from BillingPlan where ID='".$id."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $row = $oreon->database->database->fetch_array($result);
  return $name=$row['NameBp'];
}  

function get_plan_type($id)
{
  $oreon=$_SESSION['oreon'];
  $query = "SELECT TypeBp from BillingPlan where ID='".$id."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $row = $oreon->database->database->fetch_array($result);
  return $name=$row['TypeBp'];
}

function get_plan_group($id)
{
  $oreon=$_SESSION['oreon'];
  $query = "SELECT GroupBp from BillingPlan where ID='".$id."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $row = $oreon->database->database->fetch_array($result);
  return $name=$row['GroupBp'];
}

function get_plan_device($id)
{
  $oreon=$_SESSION['oreon'];
  $query = "SELECT CurrencyBp from BillingPlan where ID='".$id."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $row = $oreon->database->database->fetch_array($result);
 return $name=$row['CurrencyBp'];
}
function get_plan_price($id)
{
  $oreon=$_SESSION['oreon'];
  $query = "SELECT PriceBp from BillingPlan where ID='".$id."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $row = $oreon->database->database->fetch_array($result);
 return $name=$row['PriceBp'];
}
		   
function get_plan_value($id)
{
  $oreon=$_SESSION['oreon'];
  $query = "SELECT TimeBp from BillingPlan where ID='".$id."'";
  $result = $oreon->database->database->query($query) or die("Query database error !");
  $row = $oreon->database->database->fetch_array($result);
  return $name=$row['TimeBp'];
}  

function get_plan_Id($id)
{
  $oreon=$_SESSION['oreon'];
  $query = "SELECT ID from BillingPlan where NameBp='".$id."'";
  $result = $_SESSION["oreon"]->database->database->query($query);
  $row = $oreon->database->database->fetch_array($result);
  return $name=$row['ID'];
}

function isExpiredUserTime($name,$maxallsession)
{
  $oreon=$_SESSION['oreon'];
	
  $search = "SELECT SUM(AcctSessionTime) As TotalSessionTime FROM radacct WHERE username = '$name'";
  $result = $_SESSION['oreon']->database->database->query($search);
  $row =$_SESSION['oreon']->database->database->fetch_object($result);
  $acct_sessiontime = $row->TotalSessionTime;
  if (isset( $row->TotalSessionTime))
	  if ($acct_sessiontime>=$maxallsession) 
		  return 'True';
	  else
		  return 'False';
  return 'False';
}

function expiredUser($action,$query)
{
  		      
  $oreon=$_SESSION['oreon'];
  //DELETE EXPIRED TIME
 
    
  $i=0;
  $j=0;
  $k=0;
  $finduser='False';
  $array=array();
  $result = $_SESSION['oreon']->database->database->query($query);
 
  while($row = $_SESSION['oreon']->database->database->fetch_array($result)) {
    $name=$row['UserName'];
    $attr=$row['Type'];
    //print " NNNNNNNNNNAME $name  ".$attr;
    $val=get_user_value($name,$attr);
    if ($attr=='Subscription Time' or $attr=='Hourly' )
      {
	$ieu=isExpiredUserTime($name,$val);
	if ($ieu=='True')
	  {
	    if ($action=="del")
	      {
		delete_user($name);
		echo "<br>Delete Time account ".$name;
	      }
	    $array['time'][$i]=$name;
	    $i++;
	  }
      }
    
    if ($attr=='Subscription Octets' or $attr=='Octets' )
      {
	$ieu=isExpiredUserOctet($name,$val);
	if ($ieu=='True')
	  {
	    if ($action=="del")
	      {
		delete_user($name);
		echo "<br>Delete Octet account ".$name;
	      }
	    $array['octet'][$j]=$name;
	    $j++;
	    $finduser="True";
	  }
      }
    if ($attr=='Subscription Expiration' or $attr=='Expiration')
    {
	$ieu=isExpiredUserExpiration($name,$val);
	if ($ieu=='True')
	  {
	    if ($action=="del")
	      {
		      echo "<br>Delete Expiration account ".$name;
		delete_user($name);
	      }
	    $array['expiration'][$k]=$name;
	    $k++;
	    $finduser="True";
	  }
      }
    }    
   
    return $array;
}

function existUser($name)
{
  $oreon=$_SESSION['oreon'];
 global $debug;

  $search = "SELECT * FROM userinfo
                WHERE UserName = '$name'";
  $result = $oreon->database->database->query($search) or die("Query database error !");
 if ($result){
	 if ($debug) echo "<br>Found ".$oreon->database->database->result_num_rows($result)." rows";
	 if ($oreon->database->database->result_num_rows($result) >=1 ){
	      $row2 = $oreon->database->database->fetch_array($result);
              return True;
	}
	 else
		 return False;
	 return False;
 }
}

function isExpiredUserOctet($name,$octet)
{
    global  $acctinputoctetsatt;
    global $acctoutputoctetsattr;
    $oreon=$_SESSION['oreon'];
    if ($oreon->phpmyprepaid['octet_type']=='Upload')
  $search = "SELECT SUM($acctoutputoctetsattr) AS TotalOctet FROM radacct WHERE username = '$name'";
    if ($oreon->phpmyprepaid['octet_type']=='Total')
    $search = "SELECT SUM($acctoutputoctetsattr+ $acctinputoctetsatt) AS TotalOctet FROM radacct WHERE username = '$name'";
    if ($oreon->phpmyprepaid['octet_type']=='Download')
    $search = "SELECT SUM($acctinputoctetsatt) AS TotalOctet FROM radacct WHERE username = '$name'";
  $result = $_SESSION['oreon']->database->database->query($search);

  $row = $_SESSION['oreon']->database->database->fetch_object($result);
  if (isset($row->TotalOctet))
	  $acct_sessiontime = $row->TotalOctet;
  else return False;
  if ($acct_sessiontime>=$octet) 
    return 'True';
  
  return 'False';
}

function deleteExpirationDateUser($numMonthDeleteAccount)
{
  $oreon=$_SESSION['oreon'];
  $numMonthDeleteAccount=$numMonthDeleteAccount*30;
  $search = "SELECT Username FROM userinfo WHERE TO_DAYS(NOW()) - TO_DAYS(CrDate) > $numMonthDeleteAccount";
  $result = $oreon->database->database->query($search) or die("Query database error !");
 
  if ($result)
    while ($row = $oreon->database->database->fetch_object($result)) {
      delete_user($row->Username);
    }
   
}

function isExpiredUserExpiration($name,$exp)
{

  if (date_compare(date("Y-m-d H:i:s"),date_from_attribute($exp,"Y-m-d H:i:s"))<0) 
    return 'False';
  else
    return 'True';

  return 'False';
}



function modify_user($name,$password,$max,$idtp,$attr,$Type,$gatewayType,$db,$tab,$crypt)
{
  $oreon=$_SESSION['oreon'];

  $tp="BillingPlan='".$idtp."'";
  if ($password!="")
  {
   $password=crypt_acct_passwd($crypt,$password);
   $up="Value='".$password."'";
   $search = "UPDATE radcheck SET ".$up." WHERE Attribute='User-password' and UserName = '$name';";
   $result = $oreon->database->database->query($search) or die("Query database error !");
   }
  if ($Type=="Hourly" or $Type=="Subscription Time") {
    $maxf="Value='".$max."'";
    $search = "UPDATE $db SET ".$maxf." WHERE Attribute='$attr' and UserName = '$name';";
  }
  else if ($Type=="Octets" or $Type=="Subscription Octets")
    {
      $maxf="Value='".$max."'";
      $search = "UPDATE $db SET ".$maxf." WHERE Attribute='$attr' and UserName = '$name';";
    }
  else if ($Type=="Subscription Expiration" or $Type="Expiration")
    {
      $max="Value='".date_to_attribute($max,$gatewayType)."'";
      $search = "UPDATE $db SET ".$max." WHERE Attribute='$attr' and UserName = '$name';";
    }
  else if ($Type=="Subscription Mac")
    {
      if (existUser($max))  
	      return "Error mac address already exist !";
        $search = "UPDATE $db SET ".$max." WHERE Attribute='$attr' and UserName = '$name';";
  	$result = $oreon->database->database->query($search) or die("Query database error !");
  	$q1="UPDATE radcheck SET UserName='$max Where UserName='". $name ."'";
 	$result = $_SESSION["oreon"]->database->database->query($q1);
  	$q1="UPDATE radacct SET UserName='$max Where UserName='". $name ."'";
  	$result = $_SESSION["oreon"]->database->database->query($q2);
  	$q1="UPDATE userinfo SET UserName='$max Where UserName='". $name ."'";
 	$result = $_SESSION["oreon"]->database->database->query($q3);
  	$q1="UPDATE radpostauth SET user='$max Where user='". $name ."'";
	$result = $_SESSION["oreon"]->database->database->query($q4);
  	$q1="UPDATE radreply SET UserName='$max Where UserName='". $name ."'";
  	$result = $_SESSION["oreon"]->database->database->query($q6);
  	$q1="UPDATE mtotacct SET UserName='$max Where UserName='". $name ."'";
  	$result = $_SESSION["oreon"]->database->database->query($q6);
  	$q1="UPDATE totacct SET UserName='$max Where UserName='". $name ."'";
  	$result = $_SESSION["oreon"]->database->database->query($q6);
  	$search="UPDATE usergroup SET UserName='$max Where UserName='". $name ."'";

    }
  $result = $_SESSION["oreon"]->database->database->query($search);
 if ($tab!=NULL) {
  $str='WorkPhone="'.$tab['WorkPhone'].'",CustID="'.$tab['cid'].'", Mail="'.$tab['Mail'].'", HomePhone="'.$tab['HomePhone'].'", Note="'.$tab['Note'].'", Department="'.$tab['Department'].'", Mobile="'.$tab['Mobile'].'",Address="'.$tab['Address'].'",City="'.$tab['City'].'", Country="'.$tab['Country'].'", ZipCode="'.$tab['ZipCode'].'", LastName="'.$tab['LastName'].'", FirstName="'.$tab['FirstName'].'"';
  $search = "UPDATE userinfo SET ".$str." WHERE  UserName = '$name';";
  $result = $_SESSION["oreon"]->database->database->query($search);
 }
  if ($idtp!="") { 
  $search = "UPDATE userinfo SET ".$tp." WHERE  UserName = '$name';";
  $result = $_SESSION["oreon"]->database->database->query($search);
  }
}

function sql_xlat($filter,$login)
{
  $string = $filter;
  if ($filter != ''){
    $string = preg_replace('/%u/',$login,$string);
  }

  return $string;
}


function next_month($m, $y)
{
  if(++$m > 12) {$m = 1; ++$y;}
  if ($m<10) $m="0".$m;
  return array($m, $y);
}

function get_date_x_day_after($dateFormat,$day)
{
return date($dateFormat, mktime(0, 0, 0, date("m"), date("d")+$day,  date("Y")));
}

function remove_timezone($date)
{
	$datef=substr($date,0,19);
	return $datef;
}
//FUNCTION convert a date to the attribute regarding type
//return : date converted
function date_to_attribute($date,$type)
{
 global $use_timezone;
 
  $pf=strtotime($date);
 
  if ($type=="mikrotik")
  {
	 // $datef=date('d M Y H:i:s',$pf);  	 
	  $datef=date('c',$pf);
  }
  if ($type=="freeradius")
  {
	  $datef=date('d M Y H:i:s',$pf);  	 
  }
  
  if ($type=="chillispot") //Format iso PHP5 'c' 2004-02-12T15:19:21+00:00
    {
	    $datef=date('c',$pf);
	    if (!$use_timezone) $datef=remove_timezone($datef);
	    #$datef=get_iso_8601_date($pf);
    }
 
  if ($type=="nomadix") //Y-M-d G:i:s
    {
	
      $datef=date('Y-m-d H:i:s',$pf);  	 
    }
  if ($type=="mysql") //Y-M-d G:i:s
    {	
      $datef=date('Y-m-d H:i:s',$pf);
    }
  return $datef;
}

function date_from_attribute($date,$format)
{
list($datec, $timed) = split("T", $date);
$timec = substr($timed,0,8);
$datef=$datec." ".$timec;
if ($date=='0000-00-00 00:00:00') return $date;
if (strtotime($datec)!="943956000")
$date_mod = date($format, strtotime($datef));
else
$date_mod=$datef;
return $date_mod;
}

	
	
function check_date($strDate)
{
  $isValid = false;
  if (ereg('^([0-9]{4})[/-]([0-9]{2})[/-]([0-9]{2})$', $strDate[0])) {
    $dateArr = split('[/-]', $strDate[0]);
    $y=$dateArr[0]; $m=$dateArr[1]; $d=$dateArr[2];
    $isValid = checkdate($m, $d, $y);
  }
  if (ereg('^([0-9]{2})[/-]([0-9]{2})[/-]([0-9]{4})$', $strDate[0])) {
    $dateArr = split('[/-]', $strDate[0]);
    $y=$dateArr[2]; $m=$dateArr[1]; $d=$dateArr[0];
    $isValid = checkdate($m, $d, $y);
  }
  return  $isValid ;
}

function date_compare($_date1,$_date2)
{
  $date1=strtotime($_date1);
  $date2=strtotime($_date2);
  if ($date1>=$date2)
    return 1;
  else 
    return -1;
}

function get_iso_8601_date($int_date) {
   //$int_date: current date in UNIX timestamp
   $date_mod = date('Y-m-d\TH:i:s', $int_date);
   //$pre_timezone = date('O', $int_date);
   //$time_zone = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
   //$date_mod .= $time_zone;
   return $date_mod;
}

function trans_iso_8601_date($dateFormat,$string_date) {
   //$int_date: current date in UNIX timestamp

   list($datec, $timed) = split('T', $string_date);
   if ($datec =="") {
	   return 0;
   }
   $timec = substr($timed,0,8);
   $datef=$datec." ".$timec;
   $date_mod = date($dateFormat, strtotime($datef));
   return $date_mod;
}
				

function get_user_password($username) {
  $oreon=$_SESSION['oreon'];
    $search = "SELECT Value FROM radcheck WHERE UserName='$username' and Attribute='User-Password'";
    $result = $oreon->database->database->query($search) or die("Query database error !");
    if ($result) {
      $row = $oreon->database->database->fetch_object($result);
      return $row->Value;
   }
return -1;		       
}

function get_user_id($username) {
  $oreon=$_SESSION['oreon'];
    $search = "SELECT ID FROM userinfo WHERE UserName='$username'";
    $result = $oreon->database->database->query($search) or die("Query database error !");
    if ($result) {
      $row = $oreon->database->database->fetch_object($result);
      return $row->ID;
   }
return -1;		       
}


//TYPE 0 Timed Account, 1 Octet Account, 2 Expiration ACCOUNT

function get_user_value($username,$type) {
  $oreon=$_SESSION['oreon'];
  global $oreon;
  global $sessionTimeAttr,$octet_type,$expirationWisprAttr;
  global $sessionTimeAttrdb,$expirationWisprAttrdb,$macAuthAttr,$macAuthAttrdb;
//include("include/configuration/".$_SESSION['gatewayType'].".attr");
$octet_type=$oreon->phpmyprepaid['octet_type']; 
$max=1;
	switch ($type)
	{
		case 'Hourly':
			$attr=$sessionTimeAttr;
            $db=$sessionTimeAttrdb;
			break;
  
		case 'Subscription Time':
			$attr=$sessionTimeAttr;
			$db=$sessionTimeAttrdb;
			break;
				
		case "Octets" :
			$tab= get_octet_type_attr($octet_type);
			$attr = $tab[0];
			$db= $tab[1];
			break;
		case "Subscription Octets" :
			$tab= get_octet_type_attr($octet_type);
			$attr = $tab[0];
			$db= $tab[1];
			break;
		case "Subscription Expiration" :
			$attr=$expirationWisprAttr;
			$db=$expirationWisprAttrdb;
			break;
		case "Expiration" :
			$attr=$expirationWisprAttr;
			$db=$expirationWisprAttrdb;
			break;
		case "Subscription Mac" :
			$attr=$macAuthAttr;
			$db=$macAuthAttrdb;
			break;
		default:
			$attr=-1;
	}

	$search = "SELECT Value FROM $db WHERE UserName='$username' and Attribute='$attr'";
    $result = $_SESSION["oreon"]->database->database->query($search);
    if ($result) {
      $row = $_SESSION["oreon"]->database->database->fetch_object($result);
      
      if ($type!="Subscription Expiration")
	     return $row->Value;
     else if ($type=="Subscription Expiration")
	     return $row->Value;
    }	
return -1;		       
}
				


function get_user_by_location($user)
{
  $oreon=$_SESSION['oreon'];

    if ($user->get_status()!=3)
    $search = "SELECT userid FROM user_location WHERE statusid<='".$user->get_status()."' AND locationid IN (SELECT locationid FROM user_location WHERE userid='".$user->get_id()."') GROUP BY userid";
    else
    $search = "SELECT userid FROM user_location WHERE statusid<='".$user->get_status()."' GROUP BY userid";

    $result = $oreon->database->database->query($search) or die("Query database error !");
    return $result;
}

function get_user_status_location($user,$locid)
{
  $oreon=$_SESSION['oreon'];
	
    if ($user->get_status()!=3) {
	$search = "SELECT statusid FROM user_location WHERE userid='".$user->get_id()."' AND locationid='$locid'";
  $result = $oreon->database->database->query($search) or die("Query database error !");
	$row = $oreon->database->database->fetch_object($result);
  return $row->statusid;
    }
    else return 3;
}

function get_user_crdate($user)
{
  $oreon=$_SESSION['oreon'];
	
	$search = "SELECT CrDate FROM userinfo WHERE username='".$user."'";
	$result = $oreon->database->database->query($search) or die("Query database error !");
	$row = $oreon->database->database->fetch_object($result);
	return $row->CrDate;
}


function get_location_exclude($user1,$user2)
{
  $oreon=$_SESSION['oreon'];
       if ($user1->get_status()!=3) 
	$search = "SELECT locationid,LocationName FROM user_location,locations WHERE locationid=ID AND userid='".$user1->get_id()."' AND locationid NOT IN (SELECT locationid FROM user_location WHERE userid='".$user2->get_id()."') GROUP BY locationid";
       else
	$search = "SELECT ID,LocationName FROM locations,user_location WHERE ID NOT IN (SELECT locationid FROM user_location WHERE userid='".$user2->get_id()."')  GROUP  BY LocationName";

	$result = $oreon->database->database->query($search) or die("Query database error !");
	return $result;
}

//2 TYPE LOCAL AND REMOTE SSH
function copy_file($local_path,$dst_path,$filename,$locID)
{
  $oreon=$_SESSION['oreon'];
	 $search = "SELECT server_name,server_port,server_username,server_passwd FROM ssh_config WHERE location_id='".$locID."'";

	 $result = $oreon->database->database->query($search) or die("Query database error !");
	  $row = $oreon->database->database->fetch_object($result);
       if ($row)
       {
		if ($filename!="")
			system("sudo scp -P  ".$row['server_port']." ".$local_path."/".$filename." ".$row['server_username'].":".$row['server_passwd']."@".$row['server_name'].":$dst_path");
		else
			system("sudo scp -P  ".$row['server_port']." ".$local_path." ".$row['server_username'].":".$row['server_passwd']."@".$row['server_name'].":$dst_path");

       }
       else {
		if ($filename!="")
			system("sudo cp -f $local_path/$filename $dst_path");
		else
			system("sudo cp -f $local_path $dst_path");

			echo("sudo cp -f $local_path $dst_path");

	}
}

function serialize_oreon($oreon,$path)
{
	$s = serialize($oreon);
	  // enregistrez $s où la page2.php pourra le trouver.
       $fp = fopen("$path", "w");
       fputs($fp, $s);
       fclose($fp);
}


function get_location_string($location_id)
{
  $oreon=$_SESSION['oreon'];
	
    $search = "SELECT LocationName,LocationDomain,LocationState,LocationCountry,LocationE164Country FROM locations WHERE ID='$location_id'";
    $result = $oreon->database->database->query($search) or die("Query database error !");
    $row = $oreon->database->database->fetch_object($result);
    $resf="isocc=".$row->LocationCountry.",cc=".$row->LocationE164Country.",ac=".$row->LocationState.",network=".$row->LocationName."/".$row->LocationDomain;
    return $resf;
}

function get_location_string_name($location_id)
{
  $oreon=$_SESSION['oreon'];
	
    $search = "SELECT LocationName,LocationDomain,LocationState,LocationCountry,locationE164Country FROM locations WHERE ID='$location_id'";
    $result = $oreon->database->database->query($search) or die("Query database error !");
    $row = $oreon->database->database->fetch_object($result);
    $resf="isocc=".$row->LocationCountry.",cc=".$row->LocationE164Country.",ac=".$row->LocationState.",network=".$row->LocationName."/".$row->LocationDomain;
   return $resf;
}

function get_octet_type_attr($octet_type)
{
	
	$oreon=$_SESSION['oreon'];
  	global $maxOctetsInpAttr,$maxOctetsInpAttrdb,$maxOctetsOutAttr,$maxOctetsOutAttrdb,$maxOctetsTotalAttrdb,$maxOctetsTotalAttr;
    	$tab=array(2);
	
	if ($octet_type=="Upload") {
	    $tab[0]=$maxOctetsInpAttr;
	    $tab[1]=$maxOctetsInpAttrdb;
	    return $tab;
    }
    if ($octet_type=="Download") {
	    $tab[0]=$maxOctetsOutAttr;
	    $tab[1]=$maxOctetsOutAttrdb;
	    return $tab;
    }
    if ($octet_type=="Total") {
	    $tab[0]=$maxOctetsTotalAttr;
	    $tab[1]=$maxOctetsTotalAttrdb;
	    return $tab;
    }

}

function is_last_location($userid)
{
  $oreon=$_SESSION['oreon'];
    $search = "SELECT locationid from user_location where userid='$userid'";
    $result = $oreon->database->database->query($search) or die("Query database error !");
    $numrows = $oreon->database->database->result_num_rows($result);
    if ($numrows==1) return true;
    return false;
}

function get_nasid($apid)
{
  $oreon=$_SESSION['oreon'];
	
	$query = "select nasID from AP where ID='$apid'";
	$result=$oreon->database->database->query ($query) or die("Query database error !");
	$row=$oreon->database->database->fetch_object($result);	
	$nasid=$row->nasID;	
	return $nasid;	
}

function get_naslist($locid)
{
  $oreon=$_SESSION['oreon'];
	
	$query = "select ID,nasID from AP where LocationID='$locid'";
	$result=$oreon->database->database->query ($query) or die("Query database error !");
	$i=0;
	while ($row = $oreon->database->database->fetch_object($result)) {
		$query = "select shortname from nas where id='".$row->nasID."'";
		$result2=$oreon->database->database->query ($query) or die("Query database error !");
		$row2 = $oreon->database->database->fetch_object($result2);
		$naslist[$i]['name']=$row2->shortname;

		$naslist[$i]['ip']=$row2->nasname;
		$i=$i+1;
	}
return $naslist;
}

function get_database_attribute($attr) {

  $oreon=$_SESSION['oreon'];
   $query="SELECT gp_database FROM radius_attribute WHERE attribute='".$attr."'";
   $result = $_SESSION["oreon"]->database->database->query($query);
	while ($row = $oreon->database->database->fetch_object($result)) {
		return $row->gp_database;
	}
}

function get_attributes($type,$type2,$default_attr,$octet_type) 
{
if ($type=="Time") {
	
	if ($type2=="None" and $default_attr=="") $attr="Max-All-Session";
	else $attr=$default_attr;
	if ($type2=="Hourly") $attr="Max-Hourly-Session";
	if ($type2=="Daily") $attr="Max-Daily-Session";
	if ($type2=="Monthly") $attr="Max-Monthly-Session";
	if ($type2=="Yearly") $attr="Max-Yearly-Session";
}

if ($type=="Octet" and $octet_type=="Download") {

	if ($type2=="None" and $default_attr=="") $attr="Max-Output-Octet";
	else $attr=$default_attr;
	if ($type2=="Hourly") $attr="Max-Output-Hourly-Octet";
	if ($type2=="Daily") $attr="Max-Output-Daily-Octet";
	if ($type2=="Monthly") $attr="Max-Output-Monthly-Octet";
	if ($type2=="Yearly") $attr="Max-Output-Yearly-Octet";
}

if ($type=="Octet" and $octet_type=="Upload") {
	
	if ($type2=="None" and $default_attr=="") $attr="Max-Input-Octet";
	else $attr=$default_attr;
	if ($type2=="Hourly") $gp_attr="Max-Input-Hourly-Octet";
	if ($type2=="Daily") $attr="Max-Input-Daily-Octet";
	if ($type2=="Monthly") $attr="Max-Input-Monthly-Octet";
	if ($type2=="Yearly") $attr="Max-Input-Yearly-Octet";
}

if ($type=="Octet" and $octet_type=="Total") {
	
	if ($type2=="None" and $default_attr=="") $attr="Max-Total-Octet";
	else $attr=$default_attr;
	
	if ($type2=="Hourly") $attr="Max-Total-Hourly-Octet";
	if ($type2=="Daily") $attr="Max-Total-Daily-Octet";
	if ($type2=="Monthly") $attr="Max-Total-Monthly-Octet";
	if ($type2=="Yearly") $attr="Max-Total-Yearly-Octet";
}
}
function savewloginfreeurl($name,$url,$locID) {

  $oreon=$_SESSION['oreon'];
	
   $query="DELETE FROM  wlogin_freeurl WHERE location_id='$locID'";
   $result = $_SESSION["oreon"]->database->database->query($query);
   $i=0;
   foreach($name as $selectValue){
	   $query="INSERT INTO wlogin_freeurl (name,url,location_id) VALUES('$selectValue','$url[$i]','$locID')";
	   $result = $_SESSION["oreon"]->database->database->query($query);
	   $i=$i+1;
   }
   
}

function savewpopupurl($name,$value,$logo,$locID) {

  $oreon=$_SESSION['oreon'];
	
   $query="DELETE FROM  wlogin_popup_list WHERE location_id='$locID'";
   $result = $_SESSION["oreon"]->database->database->query($query);
   $i=0;
   foreach($name as $selectValue){

   $query="INSERT INTO wlogin_popup_list (name,value,logo,location_id) VALUES('$selectValue','$value[$i]','$logo[$i]','$locID')";
   $result = $_SESSION["oreon"]->database->database->query($query);
   $i=$i+1;
   }

}

function php2js( $php_array, $js_array_name ) {
 // contrôle des parametres d'entrée
 if( !is_array( $php_array ) ) {
 trigger_error( "php2js() => 'error parameter 1, '".gettype($array)."' given !?!");
 return false;
 }
if( !is_string( $js_array_name ) ) {
 trigger_error( "php2js() => 'string' error parameter 2, '".gettype($array)."' given !?!");
 return false;
 }
 // Création du tableau en JS
 $script_js = "var $js_array_name = new Array();\n";

 // on rempli le tableau JS à partir des valeurs de son homologue PHP
 
 for($i = 0, $max = sizeof($php_array); $i < $max; $i++) {
 $php_array2=$php_array[$i];
	 $stt="[".$i."]";
	 $script_js.= "{$js_array_name}{$stt} = new Array();\n";
 foreach( $php_array2 as $key => $value ) {
	 
 // pouf, on tombe sur une dimension supplementaire
if( is_array($value) or $value=="Array" ) {
 // On va demander la création d'un tableau JS temporaire
 $temp = uniqid('temp_'); // on lui choisi un nom bien barbare
 $t = php2js( $value, $temp ); // et on creer le script JS
 // En cas d'erreur, remonter l'info aux récursions supérieures
if( $t===false ) return false;

// Ajout du script de création du tableau JS temporaire
$script_js.= $t;
// puis on applique ce tableau temporaire à celui en cours de construction
$script_js.= "{$js_array_name}{$stt}['{$key}'] = {$temp};\n";
 }

 // Si la clef est un entier, pas de guillemets
 elseif( is_int($key) ) $script_js.= "{$js_array_name}{$stt}[{$key}] = '{$value}';\n";

 // sinon avec les guillemets
 else $script_js.= "{$js_array_name}{$stt}['{$key}'] = '{$value}';\n";
 }
 }
 // Et retourn le script JS
 return $script_js;
 }

// fin de la fonction php2js 
//
//

	
//For modify usertab
function updateExpirationDate($user,$value) {
  $oreon=$_SESSION['oreon'];
   if ($value!='') {	
	   $query="SELECT Value FROM radcheck WHERE UserName='$user' AND Attribute='Expiration'";
	   $result = $_SESSION["oreon"]->database->database->query($query);
	   $row = $oreon->database->database->fetch_array($result);
	   if ($row['Value']=='') 
		   $query="INSERT INTO radcheck (UserName,Attribute,op,Value) VALUES('$user','Expiration',':=','$value')";
	   else
   $query="UPDATE radcheck SET Value='$value' WHERE Attribute='Expiration' AND UserName='$user'";
   $result = $_SESSION["oreon"]->database->database->query($query);
   }
}

function updateGroup($user,$gp) {
  $oreon=$_SESSION['oreon'];
	if ($gp!='') {
		$query="SELECT GroupName FROM usergroup WHERE UserName='$user'";
		$result = $_SESSION["oreon"]->database->database->query($query);
		$row = $oreon->database->database->fetch_array($result);
		if ($row['GroupName']=='') 
			$query="INSERT INTO usergroup (GroupName,Username) VALUES('$gp','$user')";
		else
   $query="UPDATE usergroup SET GroupName='$gp' WHERE UserName='$user'";
   $result = $_SESSION["oreon"]->database->database->query($query);
 }
}

function __serialize($object) {
        $serialized = serialize($object);
        return htmlentities($serialized,ENT_QUOTES);
}

function __unserialize($string) {
        $unserialized = stripslashes($string);
        $unserialized = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $unserialized );
        return unserialize($unserialized);
}

function dropdown($dd){
	/* this function controls the actions of dropdown
	menus in leftdiv.php.  It also contains the html
	which displays the buttons. It could also be used 
	elsewhere.
	C. C Peterson 2007 released GPL
        */
	if (sizeof($dd)>0)
	foreach($dd as $key=>$button){
		// echo "begin button $key<br>"; //debug
		
		$dd_head=$button["0"];
		// echo"begin head<br>"; //debug
		$action=($dd_head["action"]);
		$method=($dd_head["method"]);
		echo("<form action=\"$action\" method=\"$method\">");
		// echo"end head<br>"; //debug
		
		$dd_center=$button["1"];
		foreach($dd_center as $k=>$v){
			echo("<input type=\"hidden\" name=\"$k\" value=\"$v\">");
		}
		
		$dd_foot=$button["2"];
		$type=($dd_foot["type"]);
		$class=($dd_foot["class"]);
		$name=($dd_foot["name"]);
		$loc=($dd_foot["loc"]);
		$lb_stat=$button["3"];
		$LB_STATE=__serialize($lb_stat);
		echo "<input type=\"hidden\" name=\"LB_STATE\" value=\"$LB_STATE\">";
		echo("<input type=\"$type\" class=\"$class\" name=\"$name\" value=\"$loc\">");
		echo('</form>');
		
		// echo"end button $key <br>"; //debug

		
	}

	
}
function leftbutton($lb){
        /* This function displays the main buttons in the
        left div.

        C. C Peterson 2007 released GPL
        */
        foreach($lb as $key=>$button){
                $lb_head=$button["0"];
                $lb_center=$button["1"];
                $lb_img=$button["2"];
                $lb_foot=$button["3"];
                $lb_stat=$button["4"];
                $action=($lb_head["action"]);
                $method=($lb_head["method"]);
                $buttonID=($lb_center["buttonID"]);

                //foreach($lb_stat as $btn=>$state){
                //      $LB_STATE["$btn"]="$state";
                //}
                $LB_STATE=__serialize($lb_stat);

                $lb_img=($lb_img["img"]);
                $lb_img_class=($lb_img["class"]);
                $lb_foot_class=($lb_foot["class"]);
                $lb_foot_name=($lb_foot["name"]);
                $lb_foot_value=($lb_foot["value"]);
                $lb_foot_type=($lb_foot["type"]);
                // display the button
                echo"<form action=\"$action\" class=\"leftform\" method=\"$method\">";
                echo"<div><input type=\"hidden\" name=\"buttonID\" value=\"$buttonID\"></div>";
                echo"<div><input type=\"hidden\" name=\"LB_STATE\" value=\"$LB_STATE\"></div>";
                echo"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
                echo"<tr><td>";
		echo"<img class=\"$lb_img_class\" src=\"$lb_img\" WIDTH=\"32\" HEIGHT=\"29\"  ALT=\"\">";
                echo"</td><td>";
                echo"<input type=\"$lb_foot_type\" class=\"$lb_foot_class\" name=\"$lb_foot_name\" value=\"$lb_foot_value\">";
                echo"</td></tr></table>";
                echo"</form>";
        }
}

// just like include but prints nice error if the file does not exist
function include2($file){
	if (file_exists($file)) {
		include("$file");
	}else{
		echo"<p class=\"error\">The file $file does not exist.</p>";
	}
	unset($file);
										
}
function redimage($img_src,$dst_w,$dst_h) {
	// Lit les dimensions de l'image
	$size = GetImageSize($img_src);  
	$src_w = $size[0]; $src_h = $size[1];
	// Teste les dimensions tenant dans la zone
	$test_h = round(($dst_w / $src_w) * $src_h);
	$test_w = round(($dst_h / $src_h) * $src_w);
	// Si Height final non précisé (0)
	if(!$dst_h) $dst_h = $test_h;
	// Sinon si Width final non précisé (0)
	elseif(!$dst_w) $dst_w = $test_w;
	// Sinon teste quel redimensionnement tient dans la zone
	elseif($test_h>$dst_h) $dst_w = $test_w;
	else $dst_h = $test_h;
	
	// Affiche les dimensions optimales
	echo "WIDTH=".$dst_w." HEIGHT=".$dst_h;
}

function getaccountdboption($type,$acct,$octet_type)
{
  $oreon=$_SESSION['oreon'];
 if ($type=='') {
 	if ($acct=='') {
		return "Error can't get type";
	}
 	$q = "SELECT Type FROM userinfo WHERE UserName='$username'"; // get all the timed cards

	$result = $_SESSION["oreon"]->database->database->query($q);
	$row=$oreon->database->database->fetch_object($result);

	$type=$row->Type;

 }
return getaccountvalueType($type,$octet_type);
}


function getaccountvalueType($buttonID,$octet_type)
{
  $oreon=$_SESSION['oreon'];
  global $sessionTimeAttr,$octet_type,$expirationWisprAttr;
  global $sessionTimeAttrdb,$expirationWisprAttrdb,$macAuthAttr,$macAuthAttrdb;
  //include("include/configuration/".$_SESSION['gatewayType'].".attr");
    if($buttonID == "Octets" or $buttonID == "Subscription Octets"){
        $tab= get_octet_type_attr($octet_type);
        $attr = "Attribute='$tab[0]'";
        $db = $tab[1];
	    $type=$buttonID;
	$attrr=$tab[0];

    }
   
  if($buttonID == "Subscription Mac"){$attrr=$macAuthAttr;$attr="Attribute='$macAuthAttr'";$type="Subscription Mac";$db=$macAuthAttrdb;}
  if($buttonID == "Subscription Divers"){$type="Subscription Divers";$div=1;}
  if($buttonID == "Hourly"){$attrr=$sessionTimeAttr;$db=$sessionTimeAttrdb;$attr="Attribute='$sessionTimeAttr'";$type="Hourly";}
  if($buttonID == "Subscription Time"){$attrr=$sessionTimeAttr;$db=$sessionTimeAttrdb;$attr="Attribute='$sessionTimeAttr'";$type="Subscription Time";}
  if($buttonID == "Subscription Expiration"){$attrr=$expirationWisprAttr;$db=$expirationWisprAttrdb;$attr="Attribute='$expirationWisprAttr'";$type="Subscription Expiration";}
  if($buttonID == "Expiration"){$attrr=$expirationWisprAttr;$db=$expirationWisprAttrdb;$attr="Attribute='$expirationWisprAttr'";$type="Expiration";}
return array('db' => "$db",'attr' => "$attr", 'type' => "$type",'attrr' => "$attrr"); 
}

function getaccountvalueButton($buttonID,$octet_type)
{
  //	include("include/configuration/".$_SESSION['gatewayType'].".attr");
  global $sessionTimeAttr,$octet_type,$expirationWisprAttr;
  global $sessionTimeAttrdb,$expirationWisprAttrdb,$macAuthAttr,$macAuthAttrdb;
  

    if($buttonID == "subscription_octets_accounts" or $buttonID == "octets_accounts"){
        $tab= get_octet_type_attr($octet_type);
        $attr = "Attribute='$tab[0]'";
	$db = $tab[1];
	if ($buttonID == "subscription_octets_accounts") $type="Subscription Octets";
	else $type="Octets";
	$attrr=$tab[0];

    }
  if($buttonID == "subscription_mac_accounts"){$attrr=$macAuthAttr;$attr="Attribute='$macAuthAttr'";$type="Subscription Mac";$db=$macAuthAttrdb;}
  if($buttonID == "subscription_divers_accounts"){$type="Subscription Divers";}
  if($buttonID == "timed_accounts"){$attrr=$sessionTimeAttr;$db=$sessionTimeAttrdb;$attr="Attribute='$sessionTimeAttr'";$type="Hourly";}
  if($buttonID == "subscription_time_accounts"){$attrr=$sessionTimeAttr;$db=$sessionTimeAttrdb;$attr="Attribute='$sessionTimeAttr'";$type="Subscription Time";}
  if($buttonID == "subscription_expiration_accounts"){$attrr=$expirationWisprAttr;$db=$expirationWisprAttrdb;$attr="Attribute='$expirationWisprAttr'";$type="Subscription Expiration";$div=1;$ext=" Days";}
  if($buttonID == "expiration_accounts"){$attrr=$expirationWisprAttr;$db=$expirationWisprAttrdb;$attr="Attribute='$expirationWisprAttr'";$type="Expiration";}
return array('db' => "$db",'attr' => "$attr", 'type' => "$type",'attrr' => "$attrr"); 
}


function get_template_html($default_tpl,$locID) {
  $oreon=$_SESSION['oreon'];

	$query="SELECT * From cards_tpl WHERE tpl_location='".$locID."'";
	$result = $_SESSION["oreon"]->database->database->query($query);
	while ($row = $oreon->database->database->fetch_object($result)) {
	 $tab3.=$row->tpl_name.";";
	}
	if ($opt['tpl_name']=='') $opt['tpl_name']='default1';

	  echo '<select id="print_tpl" name="print_tpl">';

  if ($opt['tpl_name']=='') $opt['tpl_name']='default1';
  $tab2=split(';',$tab3);
  foreach ($tab2 as $val) {
	  if ($val!='')
	  if ($default_tpl==$val) {
		  echo "<option id=\"$val\" value='".$val."' selected=\"selected\">$val";
	  }
	  else
		  if ($val!='') echo "<option id=\"$val\" value='".$val."'>$val";
	}
  echo '</select>';
}
?>
Return current item: phpMyPrepaid