<?php

function Build_session_expired_page($task,$session_expired_header,$submit_value,$powby,$gbook_title="The guestbook",$wrong_pass="Session Expired",$post_id="none")
{
    if ($task=="delete" or $task=="edit" or $task=="modify"){$task="del_edit";}
    if ($task=="edit_config"){$task="configure";}
    #$focus="<script>document.body.OnLoad=\"document.adminlogin.adpass.focus();\"</script>";
    $chunk1=$session_expired_header.'<span style="color:red;">'.$gbook_title."</span>\n";    
    $chunk2="<br><hr class=\"adminlogin\" align=\"left\">".
    "<b>$wrong_pass</b>
    <p>
    <form action=\"\" method=\"post\" name=\"adminlogin\" id=\"adminlogin\">
    Password: <input type=\"password\" name=adpass>
    <br>    
    <input type=\"hidden\" name=\"task\" value=".$task.">\n<br>\n";
    if ($post_id!="none")
    {
      $chunk3='<input type="hidden" name="post_id" value="'.$post_id.'">';
    }
    else{$chunk3='';}          
    $chunk4='<input type="submit" value="'.$submit_value.'">'."\n</form>\n";
    $chunk5='<hr class="adminlogin" align="left">'."\n".$powby."\n</body>\n</html>";    
    return ($chunk1.$chunk2.$chunk3.$chunk4.$chunk5);
}

function strleft($s1, $s2) { return substr($s1, 0, strpos($s1, $s2)); } 
function selfURL() { $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : ""; $protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s; $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI']; }

#function file_get_contents($filename)
#{
#  return implode('', file($filename));
#} 

function EncodeMessage($message){
$message=preg_split('/;/',$message);
$message=implode("##semicolon##",$message);
$message=preg_split("/'/",$message);
$message=implode("##prime##",$message);
$message=preg_split('/"/',$message);
$message=implode("##apostrophe##",$message);
$message=preg_split('/:/',$message); // added0.52
$message=implode("##colon##",$message); 
$message=preg_split('/\$/',$message);
$message=implode("##dollarsign##",$message); 
return ($message);
}

function DecodeMessage ($message){
$message=preg_split('/##semicolon##/',$message);
$message=implode(";",$message);
$message=preg_split('/##prime##/',$message);
$message=implode("'",$message);
$message=preg_split('/##apostrophe##/',$message);
$message=implode('"',$message);
$message=preg_split('/##colon##/',$message);
$message=implode(':',$message); // added0.52
$message=preg_split('/##dollarsign##/',$message);
$message=implode('&#36;',$message);  
return ($message);
}

# a function to replace new lines with breaks
function ConvertToHtml ($message){

 $fmess1=preg_split('/\\r\\n|\\n|\\r/',$message);  
 $fmess=implode("<BR>",$fmess1);
 $fmess2=stripslashes($fmess);
 return ($fmess2);

}


function RemoveBreaks($message){
 $fmess1=preg_split('/<BR>/',$message);  
 $fmess=implode("\n",$fmess1);
 $fmess1=preg_split('/<P>/',$message);  
 $fmess=implode("\n\n",$fmess1); 
 $fmess2=stripslashes($fmess);
 return ($fmess2);
}


function CleanName($name){
  $name = trim($name);
  $name=preg_split('/;/',$name);
  $name=implode("",$name);
  $name=preg_split('/"/',$name);
  $name=implode("",$name);
  $name=preg_split('/\'/',$name);
  $name=implode("",$name);  
  $name=preg_split('/:/',$name);
  $name=implode("",$name); 
  $name=stripslashes($name); 
  return $name;
}

function FlatfileToArray($posts_file){
  $posts=file($posts_file);
  $post_array=array();
  $posts2=array();
  foreach ($posts as $post)
  {
    $post2=preg_split('/;/',$post);
    foreach ($post2 as $post_item)
      {
        $temp=preg_split('/:/',$post_item);
        $post_array[$temp[0]]=trim($temp[1]);
      }
    $posts2[]=$post_array;
  }
  return $posts2;
}

function PostArrayToLine($post_array){
  $line='';
  $i=0;
  foreach ($post_array as $key => $val)
  {
    if ($i==0){$line=$key.':'.$val; $i=$i+1;}
    else {$line=$line.';'.$key.':'.$val;$i=$i+1;}
  }
  $line=$line."\n";
  return $line;
}


function ArrayToFlatfile($posts_array,$posts_file){
  $tofile='';
  foreach ($posts_array as $post)
  {
    $line=PostArrayToLine($post);
    $tofile=$tofile.$line;
  }
  $fp = fopen($posts_file, "w");
  $write = fputs($fp, $tofile);
  fclose($fp);
}

function GetNextAvailableId($posts_file){
  $posts_array=FlatfileToArray($posts_file);
  if (count($posts_array)==0){return "1";exit;}
  else{
  $max_id=0;
  foreach ($posts_array as $post)
  {
    $post_id=$post["post_id"];
    if ($post_id>$max_id){$max_id=$post_id;}
  }
  $nai=$max_id+1; //next available id
  return $nai;
  }
}


# A function to check if a message contain words that are too long and could disrupt the web page design
function CheckLongWords($message, $max_word_length){
  $ok=1;
  $mescheck1=preg_split('/ /',$message); 
  foreach($mescheck1 as $value)
  {
  if (strlen($value)>$max_word_length){$ok=0;}
  }
  return ($ok);

}

function CheckForForbidden($stringa,$forbidden_list){

$check=1; # check 1 means that the post is OK as far as forbidden strings and IP are OK. We start by setting this to OK and then make it =0 if something goes wrong
foreach($forbidden_list as $value)
{
if (preg_match('/'.$value.'/'.i,$stringa)==1){$check=0;}
}
return ($check);

}


function CreateCaptchaImage2 (){ # creates a captcha image and returns the value written on it
  #$im = ImageCreate(100, 30);
  $im = ImageCreate(55, 20);
  srand((double)microtime()*1000000);
  $selbgcol=rand(1,5);
  if($selbgcol==1){
  $captcha_bg_color = ImageColorAllocate($im, 198, 24, 0);#RED
  }
  elseif($selbgcol==2){
  $captcha_bg_color  = ImageColorAllocate($im, 0, 0, 0);#BLACK
  }
  elseif($selbgcol==3){
  $captcha_bg_color  = ImageColorAllocate($im, 43, 130, 26);#GREEN
  }
  elseif($selbgcol==4){
  $captcha_bg_color  = ImageColorAllocate($im, 255, 153, 0);#ORANGE
  }
  elseif($selbgcol==5){
  $captcha_bg_color  = ImageColorAllocate($im, 0, 88, 238);#BLUE   
  }
  
  $white = ImageColorAllocate($im, 255, 255, 255);
  #$black = ImageColorAllocate($im, 0, 0, 0);
  /*random string generator.*/
  /*The seed for the random number*/
  srand((double)microtime()*1000000); 
  /*Runs the string through the md5 function*/
  $string = md5(rand(0,9999)); 
  /*creates the new string. */
  $new_string = substr($string, 17, 5);
  /*fill image with background color*/
  ImageFill($im, 0, 0, $captcha_bg_color);
  /*writes string */
  ImageString($im, 9, 6, 2, $new_string, $white); 
  /* output to browser*/
  ImagePNG($im, "verify.png");
  #ImageDestroy($im); 
  session_unset();session_start();
  $_SESSION['new_string'] = $new_string;
  #echo "<img src=\"verify.png\">";
  header("Content-type:  image/png");
  imagePNG($im);
  echo $im;
  #echo "pluto<p>";
  ImageDestroy($im); 
}

# A little function to send an e-mail
function msendmail ($from,$to,$subj,$mess){
  mail($to,$subj,$mess,"From: $from\n");
}

# fuction to write to the log file
function writelog($filename,$text){
  $fp = fopen($filename, "a");
  $write = fputs($fp, $text);
  fclose($fp);
} # end function definition writelog

function ip_to_numerical($ip)
{
    $ips=preg_split("/\./",$ip);
    $ipnum=(int)$ips[3]+((int)$ips[2]*256)+((int)$ips[1]*256*256)+((int)$ips[0]*256*256*256);
    return ($ipnum);
}

function locate_ip_2($ip,$needed_info="name")
{
    $ipn=ip_to_numerical($ip);
    #echo "<p>IP: $ip</p>";
    #echo "<p>Numerical: $ipn</p>";
    
    $db="include/IpToCountry.csv";
    #$db="test.txt";
    $lines_num = count(file($db));
    #echo "<p>There are $lines_num lines in the file</p>";
    $fh = fopen($db, "r"); # file handle
    $range_start='';
    $range_end='';
    $country_name='';
    $country_code='';
    $matches=array();
    $i=0;
    $j=0;
    while($i<(int)$lines_num)
    {
      $i=$i+1;
      $line=fgets($fh);
      if (preg_match("/\"(\d+)\",\"(\d+)\",\"(\w+)\",\"(\d+)\",\"(\w+)\",\"(\w+)\",\"([\w\s\(\);]+)\"/",$line,$matches)==1)
      {
        #if ($j==1){next;}
        #echo "<p>line found<p>";
        #echo "the line:<br>".$line."<p>";
        $j++;
        $range_start=(int)$matches[1];
        if ($range_start==0){next;}
        $range_end=(int)$matches[2];
        $country_code=$matches[5];
        $country_name=$matches[7];
        #if ($i<800){echo "range start: $range_start, range end: $range_end, country code: $country_code, country name: $country_name";}
        
        if (($ipn>$range_start && $ipn<$range_end) or $ipn==$range_start or $ipn==$range_end)
        {
            #echo "<p>Country found!</p>";
            if ($needed_info=="name")
            {
                $result=$country_name;
            }
            elseif ($needed_info=="code")
            {
                $result=$country_code;
            }
            break;
        }
      }
    }
    fclose($fh);
    if (!$result){$result="unknown";}
    return ($result);
}


?>
