#!/usr/local/bin/perl
# The above is the standard 'magic' to inform the shell to feed this file to the
# program named after the bang (!). You may need to change this if perl is
# installed at a different location on your server.

use CGI qw (:standard);                  # Saves a lot of work
use CGI::Carp qw(fatalsToBrowser);       # Sends most fatal errors to browser
                                         # which makes it easier to debug errors

$| = 1; # Output NOT buffered - this prevents perl from buffering the script's
        # output to STDOUT. Since STDOUT is our conduit back to the user's 
        # browser, we want to ensure that our data gets out as we create it. If
        # the connection goes away while we still have it in memory, the user 
        # will never see it. This makes the output back to the user much faster.

# Server Data sub Directory for this script
$data = "readersdata\/";        
        
eval {
    require "dbengine.pl";         # DBEngine script
    require $data . "config.cgi";
};
if ($@) {
    print header(); 
    print start_html(-title=>"Error!");
    print qq(Could not find <b>dbengine.pl</b>,
             or there was an error while loading it.);
    print end_html; exit;
}
        
# Script files
$thisscript = "readers.cgi";
# Copyright footer for pages, DO NOT REMOVE or modify
$copyright = qq(Reader's Script - Copyright &copy; 2000 
                OffRoadSearch.com); 

# Data files
$database = $data."readers"; # the database engine will add ".txt"
$categoryfile = $data."categories.txt";

# Fields to use in the Database
@fields = ("key", "username", "password", "email", "realname", "website", 
           "item", "picture", "notes", "category");
$FLD_KEY      = 0;
$FLD_USERNAME = 1;
$FLD_PASSWORD = 2;
$FLD_EMAIL    = 3;
$FLD_REALNAME = 4;
$FLD_WEBSITE  = 5;
$FLD_ITEM     = 6;
$FLD_PICTURE  = 7;
$FLD_NOTES    = 8;
$FLD_CATEGORY = 9;

# HTML Files
$HTMLmain   = $data."main.html";
$HTMLnav    = $data."navigation.html";
$HTMLstyle  = $data."readers.css"; 
$HTMLnav    = $data."navigation.html";
$HTMLadd    = $data."add.html";
$HTMLedit   = $data."edit.html";
$HTMLlogin  = $data."login.html";
$HTMLheader = $data."header.html";
$HTMLfooter = $data."footer.html";
$HTMLmsg    = $data."message.html";
$HTMLmsg2   = $data."message2.html";
$HTMLsearch = $data."search.html";
$HTMLupload = $data."upload.html";
$HTMLuldone = $data."uldone.html";
$HTMLulmsg  = $data."ulmsg.html";
        
# Get Style Sheet file contents
$embeddedcss = GetFileContentsIntoString($HTMLstyle);

# Get Navigation file contents
&GetNavigationFileContents;
        
# create new CGI object
$query = new CGI;

# Gets all the form parameters passed into the script
@params = $query->param;

# For each parameter passed into the script from the form,
# create a variable by the same name for use later in the script.
foreach $param (@params) {           # For each element in the @params array 
  $theparam = $query->param($param); # Get the value that the parameter contains
  ${$param} = $theparam;             # Create a variable by the param name
}

&CheckDatabase; # Check for database, create if needed

# Check the action variable to determine what action we need to do
# Upload submit does not use a Content-Type of html/text
if ($action eq "uploadsubmit") { 
  $allowall = "no"; # Allow all file types?  yes/no (no capital letters)
  # Set File Size Limit. Note: 1024 = 1k
  $CGI::POST_MAX = 1024 * $filesize;
}
else { print $query->header; }

if (($action eq "") or ($action eq "home")) { ShowPage($HTMLmain); }
elsif ($action eq "add")                    { ShowPage($HTMLadd); }
elsif ($action eq "login")                  { ShowPage($HTMLlogin); }
elsif ($action eq "search")                 { ShowPage($HTMLsearch); }
elsif ($action eq "upload")                 { ShowPage($HTMLupload); }
elsif ($action eq "uploaddone")             { &ShowUploadDonePage; }
elsif ($action eq "uploadmsg")              { &ShowUploadMsgPage; }
elsif ($action eq "view")                   { &DoSearch; }
elsif ($action eq "searchsubmit")           { &DoSearch; }
elsif ($action eq "addsubmit")              { &AddUserSubmit; }
elsif ($action eq "editsubmit")             { &EditUserSubmit; }
elsif ($action eq "loginsubmit")            { &LoginSubmit; }
elsif ($action eq "sendloginsubmit")        { &SendUserInfo; }
elsif ($action eq "uploadsubmit")           { &UploadSubmit; }

exit; # End of main script logic

# Begin Subroutines

# ==============================================================================
# Show Upload Done Page
# ==============================================================================
sub ShowUploadDonePage {
  $pictureurl = $baseimages . "reader" . $key . ".jpg";
  ShowPage($HTMLuldone);
  exit;
}

# ==============================================================================
# Show Upload Message Page
# ==============================================================================
sub ShowUploadMsgPage {
  if ($message eq "badfile") {
    $messagetitle = "Bad Filename";
    $message = qq(The file name submitted for upload was not a valid filename.);
  }
  if ($message eq "baduser") {
    $messagetitle = "Bad Username";
    $message = qq(Bad username.);
  }
  $message .= qq(<br>Please go back and <a href="javascript:history.go(-1)">try the upload again</a>);
  ShowPage($HTMLulmsg);
  exit;
}

# ==============================================================================
# Upload submission
# ==============================================================================
sub UploadSubmit {

  # Check if the file name is empty
  if ($file1 ne "") {
    my $filename = $file1;
    $newmain = $filename;  
    $filegood = "no"; # Set default to bad file
    
    # Check to see if the file is has a good extension 
    $newmain = lc(substr($newmain,length($newmain) - 4,4)); 
    if ($newmain eq ".gif"){$filegood = "yes";}
    if ($newmain eq ".jpg"){$filegood = "yes";}
    if ($filegood eq "yes") {
      # Check the users info
      $count = GetUserRecordIntoVars($username);
      if ($count != 0) {
        # Build the file name - NOTE even though the user may upload either gifs
        # or JPGs, they both display properly in the browser if they have the
        # JPG file extension, so to make things easier, we name them this way 
        $filename = "reader" . $key . ".jpg";
      
        # Write the new file to the output folder
        open (OUTFILE, ">$imagesdir$filename"); 
          binmode OUTFILE; # Set Binary output mode on the output file
          while (my $bytesread = read($file1, my $buffer, 1024)){
            print OUTFILE $buffer; 
          } 
        close (OUTFILE);
        # Show Upload Successfull Message
        $donepage = "$thisscript?action=uploaddone\&key=$key";
      }
      else {
        # Bad user submission, they should never really get here.
        $message = "baduser";
        $donepage = "$thisscript?action=uploadmsg\&message=$message";
      }
    } 
    else {
      $message = "badfile";
      $donepage = "$thisscript?action=uploadmsg\&message=$message";
    }

  } # End if ($file ne "")
  else {
    $message = "badfile";
    $donepage = "$thisscript?action=uploadmsg\&message=$message";
  }
  #redirect to the message
  print qq(Location:  $donepage\n\n);
  exit;
}

# ==============================================================================
# Send Admin E-mail
# ==============================================================================
sub SendAdminEmail {
  $mode = shift;
  if ($mode eq "Added") {
    $msg = qq(User $realname, AKA "$username", Added themselves to the database.);
  }
  elsif ($mode eq "Changed") {
    $msg = qq(User $realname, AKA "$username", Changed their profile.);
  }
  elsif ($mode eq "Deleted") {
    $msg = qq(User $realname, AKA "$username", Deleted themselves from the database.);
  }
  # http://www.offroadsearch.com/cgi-bin/readers.cgi?action=view&type=standard&user=mike
  $url = qq($scripturl$thisscript?action=view&user=$username);
  
  # Check if the sendmail program can be found
  if (-e $sendmail) {
    # Send the username and password to the e-mail address submitted
    open (MAIL, "| $sendmail -t -oi");
    print MAIL <<__END__;
To: $adminemail
From: $adminemail  
Subject: $readersthingsname - $username $mode 

$msg
$url

Thanks,
The Webmaster
__END__
    close MAIL;   
  }  
}

# ==============================================================================
# Send User Information via e-mail
# ==============================================================================
sub SendUserInfo {
  if (&check_url != 1) { 
    print qq(Bad Referer!);
    exit; 
  }
  # Check e-mail validity
  if (MailValid($email) == 0) {
    $errormessage = qq(<b>Could Not Send E-mail!</b><br>The e-mail address entered 
                       does not appear to be a valid e-mail address format.);
    ShowPage($HTMLlogin);
    exit;
  }  
  # Check for the users e-mail address in the database
  my @results = DB_search_database($database, $email, "email", @fields);
  my $count = @results;  
  if ($count == 0) {
    $errormessage = qq(<b>Could Not Send E-mail!</b><br>The e-mail address entered 
                       does not appear to be in the database.);
    ShowPage($HTMLlogin);
    exit;
  }
  else {
    # Loop through all the results and build a list of the usernames and 
    # passwords for this e-mail address, since technically the person could
    # have multiple usernames and the same e-mail address in each of them.
    foreach $record (@results) {
      PopulateVarsFromPipedRecord($record);
      $info .= "User Name: $username\nPassword: $password\n";
    }
  }
  
  
  # Check if the sendmail program can be found
  if (-e $sendmail) {
    # Send the username and password to the e-mail address submitted
    open (MAIL, "| $sendmail -t -oi");
    print MAIL <<__END__;
To: $email
From: $adminemail  
Subject: Your Profile Login Info You Requested

$realname, ($email) Here is the login information that was requested from:
$scripturl$thisscript.

$info 
Thanks,
The Webmaster
__END__
    close MAIL;   
    $errormessage = qq(An e-mail with your username and password has been sent 
                       to the address you provided.);
  }
  else {
    $errormessage = qq(<b>Could Not Send E-mail!</b><br> The e-mail feature is 
                       either disabled or not properly configured.);
  }
  ShowPage($HTMLlogin);
}

# ==============================================================================
# Checks if the passed e-mail address is a valid e-mail address
# ==============================================================================
sub MailValid
{
  # Returns 0 if the e-mail format is invalid
  return 0 if $_[0] =~ /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
  return 0 if $_[0] !~ /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
  return 1;
}

# ==============================================================================
# Do Search - This is used for BOTH viewing and searching!
# ==============================================================================
sub DoSearch {

  # Determine search field
  if ($user ne "") { $search_field = "username"; }
  # Determine what to search for
  if ($user ne "") { $search_for = $user;} 

  my @results = DB_search_database($database, $search_for, $search_field, @fields);
  my $count = @results;  

  ShowPage($HTMLheader);
  my $searchhits = 0;
  if ($count == 0) {
    $messagetitle = "Search Results";
    $message = "No records were found for your search query.";
    ShowPage($HTMLmsg);
  }
  else {
    if ($type eq "") { $type = "standard"; } # Default display type
    foreach $record (@results) {
      PopulateVarsFromPipedRecord($record);
      $notes =~ s/\%nl\%/<br>/ig;
      # do special items
      if ($email =~ /\@/) { 
        $email = qq(<a href="mailto:$email">$email</a>); 
      } 
      else { 
        $email = "None"; 
      }
      if ($picture =~ /^(http|https):\/\//i) { 
        $photoyesno = "Yes";
        $picture = qq(<img src="$picture">); 
      } 
      else { 
        $photoyesno = "No";
        $picture = ""; 
      }
      if ($website =~ /^(http|https):\/\//i) { 
        $website = qq(<a href="$website" target="_blank">$website</a>); 
      } 
      else { 
        $website = "None"; 
      }

      if ($user ne "") {
        # If the user is specified, we need to check for an exact match
        # since the search function will return any partial matches as well
        if ($user eq $username) {
          ShowPage("$data$type.html");
          $searchhits++;
        }
      }
      else {
        # Check if a category match is required
        if ($searchcategory ne "") {
          if (lc($searchcategory) eq lc($category)) {
            ShowPage("$data$type.html");
            $searchhits++;
          } 
        }
        else { 
          ShowPage("$data$type.html");
          $searchhits++
        }
      }

      
    } # End foreach $record
    if ($searchhits == 0) {
      $messagetitle = "Search Results";
      $message      = "No records were found for your search query.";
      ShowPage($HTMLmsg);
    }
  }  
  ShowPage($HTMLfooter);  
  
}

# ==============================================================================
# Login Submit
# ==============================================================================
sub LoginSubmit {
  if (&check_url != 1) { 
    print qq(Bad Referer!);
    exit; 
  }
  #my @results = DB_search_database($database, $uname, "username", @fields);
  #my $count = @results;
  my $result = GetUserRecordIntoVars($uname);
  $notes =~ s/\%nl\%/\n/ig;
  # Check if the username was found
  if (($result == 0) or ($uname eq "")){
    $errormessage = qq(Username not found in database!);
    ShowPage($HTMLlogin);
  }
  else {
    # Username found, now check the password
    if ($passw eq $password) {
      # good password for the username
      ShowPage($HTMLedit);
    }  
    else {
      $errormessage = qq(Incorrect Password!);
      ShowPage($HTMLlogin);
      exit;
    }
  }
}

# ==============================================================================
# Get User Record into standard variables
# ==============================================================================
sub GetUserRecordIntoVars {
  my @results = DB_search_database($database, @_[0], "username", @fields);
  my $count = @results;
  if ($count > 0) { PopulateVarsFromPipedRecord(@results[0]); }
  return $count;
}

# ==============================================================================
# Populate Variables From Piped Record
# ==============================================================================
sub PopulateVarsFromPipedRecord {
  my @record = split(/\|/, @_[0]); 
  $key       = $record[$FLD_KEY];
  $username  = $record[$FLD_USERNAME];
  $password  = $record[$FLD_PASSWORD];
  $email     = $record[$FLD_EMAIL];
  $realname  = $record[$FLD_REALNAME];
  $website   = $record[$FLD_WEBSITE];
  $item      = $record[$FLD_ITEM];
  $picture   = $record[$FLD_PICTURE];
  $notes     = $record[$FLD_NOTES];
  $category  = $record[$FLD_CATEGORY];
}

# ==============================================================================
# Edit User Submit
# ==============================================================================
sub EditUserSubmit {
  if (&check_url != 1) { 
    print qq(Bad Referer!);
    exit; 
  }
 
 # Check if the user has checked the delete field on the form
 if ($deleteprofile =~ /checked/i) {
   # User wishes to be deleted
   # Check and see if an admin e-mail is needed
   # if ($adminemail eq "yes") {SendAdminEmail("deleted");}
   
   # Delete the user from the database
   my $NumDeleted = DB_delete_record($database, "username", $username, @fields);
   # Delete the users picture if it exists
   $picturefile = $imagesdir . "reader" . $key . ".jpg";
   if (-e $picturefile) {
     # Delete it if it exists
     unlink $picturefile;    
   }
   
   if ($adminemailondelete eq "yes") { SendAdminEmail("Deleted") };
 }
 else {
   &CleanUserInputs;
   DB_update_record($database, $key, $username, $password, $email, $realname, 
                    $website, $item, $picture, $notes, $category);
   if ($adminemailonedit eq "yes") { SendAdminEmail("Changed") };
 }

 # Take them to their displayed individual page.
 $search_for = $key;
 $search_field = "key";
 &DoSearch;

}

# ==============================================================================
# Clean User Inputs
# ==============================================================================
sub CleanUserInputs {
  $email        = cleaninput("$email");
  $real_name    = cleaninput("$realname");
  $website      = cleaninput("$website");
  $ride         = cleaninput("$item");
  $notes        = cleaninput("$notes");
  $picture      = cleaninput("$picture");
  $category     = cleaninput("$category");
  $spam		= cleaninput("$spam");
}

# ==============================================================================
# Clean Input - Strips any unwanted (bad) characters from input
# ==============================================================================
sub cleaninput {
 
 my $text = shift;
 $text =~ s/<!--(.|\n)*-->//g;     # remove Server side includes
                                   # which could be a security hole!!!!!!!!!!
 $text =~ s/<script//g;            # remove script tags
 $text =~ s/\&/\&amp;/g;           # remove ampersands
 $text =~ s/"/\&quot;/g;           # swap quotes with &quot;
 $text =~ s/  / \&nbsp;/g;         # swap 2 spaces with space and &nbsp;
 $text =~ s/</\&lt;/g;             # swap < with &lt;
 $text =~ s/>/\&gt;/g;             # swap > with &gt;
 $text =~ s/\|/\&#0124;/g;         # swap pipe with entity version
 $text =~ s/\t//g;                 # remove tabs
 $text =~ s/\r//g;                 # remove hard returns
 $text =~ s/  / /g;                # swap 2 spaces for 1 
# $text =~ s/\n\n/\<p\>/g;          # swap 2 new-lines for a paragraph tag
# $text =~ s/\n/\<br\>/g;           # swap 1 new-line for a break tags
 return $text;
}

# ==============================================================================
# Get Categories HTML
# ==============================================================================
sub GetCategoriesHTML {
  # Get the <option></option> categories for insertion into the html pages
  $categories = "";
  if (-e $categoryfile) {
    # Get all the lines from the category file
    open (CATEGORIES, "$categoryfile") or die "Error opening category data file.  $!\n";
     my @lines=<CATEGORIES>;
    close (CATEGORIES);    
    # Process each category name
    foreach $cat (@lines) {
      # chomp $cat;
      $cat =~ s/\n//g;
      $cat =~ s/\r//g;
      if ($cat eq $category) {
        $categories .= qq(<option selected value="$cat">$cat</option>);
      }
      else {
        $categories .= qq(<option value="$cat">$cat</option>);
      }
    }
  }
  else {
    # No category file found
    $categories = qq(<option selected value="General">General</option>);
  }
}

# ==============================================================================
# Get Navigation File Contents
# ==============================================================================
sub GetNavigationFileContents {
  # Get Navigation file contents
  my @navigation = GetFileContentsIntoArray($HTMLnav);
  @navigation = FilterItems(@navigation);
  $navigationfile = "";
  for (@navigation) { $navigationfile .= $_; }
}

# ==============================================================================
# Check for the database
# ==============================================================================
sub CheckDatabase {
  if (!-e "$database.txt") {
    # The database file does not exist, so create it with a default password
    # of "password"
    DB_create($database, "password");
  }
}

# ==============================================================================
# Add User
# ==============================================================================
sub AddUserSubmit {

  # Check for Bad referer
  if (&check_url != 1) { AddUserError("Bad Referer!"); }             # then exits

  # Check for missing form field values
  if (!$username) { AddUserError("Missing username"); }             # then exits
 
  # Check if the user name is already in the database
  my @results = DB_search_database($database, $username, "username", @fields);
  my $count = @results;
  if ($count > 0) {
    AddUserError("That username is already taken, please choose another.");
  }  
  
  # Check for bad form entries 
  if (!$password)  { AddUserError("Missing password"); }            # then exits
  if (!$email)     { AddUserError("Missing email address"); }       # then exits
  if (!$realname) { AddUserError("Missing real name"); }           # then exits

  # Check anti-bot answer
  if ($spam ne "cdsv357") { AddUserError("Invalid anti-spam answer"); } #then exits

  # Check for invalid characters in form fields,
  if ($username !~ /^[a-z0-9\\-\_]*$/i) { AddUserError("Invalid characters in username"); }
  if ($password =~ /\|/) { AddUserError("Invalid characters in password"); }
  if ($email !~ /\@/ || $in{'email'} =~ /\|/) { AddUserError("Invalid email address format"); }
  if ($realname =~ /\|/) { AddUserError("Invalid real name"); }
  if ($realname eq "") { AddUserError("Real name not specified"); }

  # If there were no errors, then we get here and call the add record routine
  $key = DB_add_record($database, $username, $password, $email, $realname, 
                       $website, $item, $picture, $notes, $category);

  # Now we take the user to the member page so they can enter their infomation
  ShowPage($HTMLedit);
	if ($adminemailonadd eq "yes") { SendAdminEmail("Added") };
}

# ==============================================================================
# Add User Error
# ==============================================================================
sub AddUserError {
  $errormessage = shift;
  ShowPage($HTMLadd);
  exit;
}

# ==============================================================================
# Show Page - Shows the passed page after FilterItems
# ==============================================================================
sub ShowPage {
  my $file = shift; # Get the filename passed to this procedure
  my @lines = GetFileContentsIntoArray($file);
  @lines = FilterItems(@lines);
  for (@lines) { print "$_"; }  # output each line in @lines to Browser
  print "\n\n";
}

# ==============================================================================
# Get File Contents Into Array (return lines in an array)
# ==============================================================================
sub GetFileContentsIntoArray {
  my $filename = shift; # Get filename passed to the routine
  # Get Contents of file into lines array
  open (FILE, $filename) || die "Error opening $filename.  $!\n";
    my @filelines=<FILE>; 
  close (FILE);
  return @filelines;
}

# ==============================================================================
# Get File Contents Into String (return lines in an array)
# ==============================================================================
sub GetFileContentsIntoString {
  my $filename = shift; # Get filename passed to the routine
  # Get Contents of file into lines array
  open (FILE, $filename) || die "Error opening $filename.  $!\n";
    my @filelines=<FILE>; 
  close (FILE);
  my $contents = "";
  for (@filelines) { $contents .= $_; }
  return $contents;
}

# ==============================================================================
# Filter Items
# ==============================================================================
sub FilterItems {
  my $output = 1;
  &GetCategoriesHTML;   
  # Loop through element in the array passed to this routine
  foreach $line (@_) {
    if ($output == 1) {
      if ($line =~ /CGII_OUTPUT_OFF/){ 
        $output = 0;
        
        # $` returns everything before the matched string.
        # remove everything after and including the CGII_OUTPUT_OFF from the line
        if ($line =~ /\<!-- CGII_OUTPUT_OFF --\>/) { 
          $line =~ s/\<!-- CGII_OUTPUT_OFF --\>//;
          $line = $`; 
        };
        if ($line =~ /CGII_OUTPUT_OFF/) { 
          $line =~ s/CGII_OUTPUT_OFF//;
          $line = $`; 
        };
      }
      else {

        # Check for CGI Includes
        while ($line =~ /CGII_REPLACE/) {
          # Line contains a CGII directive
         
          # replace the <!-- CGII_REPLACE_whatever --> with xxfooxx
          $line =~ s/\<!-- CGII_REPLACE_+[a-zA-Z0-9]+ --\>/xxfooxx/; # [a-zA-Z0-9]
          my $var = $&;
          $var =~ s/\<!-- CGII_REPLACE_//; # remove <!-- CGII_REPLACE_
          $var =~ s/ --\>//; # remove -->
          $line =~ s/xxfooxx/${$var}/;
          
          # replace the CGII_REPLACE_whatever with xxfooxx
          $line =~ s/CGII_REPLACE_+[a-zA-Z0-9]+/xxfooxx/; # [a-zA-Z0-9]
          my $var = $&;
          $var =~ s/CGII_REPLACE\_//; # remove CGII_REPLACE_
          $line =~ s/xxfooxx/${$var}/;
          
        }

        # any image reference that isn't preceeded by http:, add the base images
        # folder url to it.
        $line =~ s/img src\=\"(?!http\:)/img src\=\"$baseimages/ig;

        # For each element in the @items array
        foreach $param (@params) {
          # replace %$param% with the value in the variable by the same name
          $line =~ s/\%$param\%/${$param}/ig;
        }
      } # end else for if ($line =~ /CGII_OUTPUT_OFF/)
      
    } # end if ($output == 1)
    else { 
      # if output is off, check to see if we need to turn it back on
      if ($line =~ /CGII_OUTPUT_ON/){ 
        $output = 1;
        # $' returns everything after the matched string.
        # remove everything before and including the CGII_OUTPUT_OFF from the line
        if ($line =~ /\<!-- CGII_OUTPUT_ON --\>/) { 
          $line =~ s/\<!-- CGII_OUTPUT_ON --\>//;        
          $line = $'; 
        };
        if ($line =~ /CGII_OUTPUT_ON/) { 
          $line =~ s/CGII_OUTPUT_ON//;
          $line = $'; 
        };         
      }
      $line = "";  # Erase the current line
    } 
  } # end foreach $line (@_)
  return @_;
}

# ==============================================================================
# Check Url - Checks to see if the form is being submitted from one of the sites
#             that are specified in $referers
# ==============================================================================
sub check_url {
  # Get the referer from the environment
  $referer = $ENV{'HTTP_REFERER'}; 

  # If there is no referer, then consider it a bad referer
  if ($referer eq ""){ return 0; }

  # Remove the http:// and ftp:// from the referer
  $referer =~ s/(http\:\/\/|https\:\/\/|ftp\:\/\/)//gi;
  
  # Split the url into the temp array
  @temp = split(/\//, $referer);
  
  # Get the domain name from the first array element 
  $refer_domain = $temp[0];
  
  # Default match value is 0, which means no match (bad referer)
  $okay = 0; 
  
  $referers =~ s/ //g; # remove spaces
  (@referers) = split(/\,/, $referers);
  
  # Loop through each domain listed in the @referers array
  foreach $domain (@referers) {
    # Check the referer $domain against the domains in our list
	  # If it matches, then return 1, which means it's OK (good referer)
	  if ($refer_domain =~ /$domain/i) { return 1; }
  }
  # The domain was not found in out referer list, return bad referer
  return 0;  
}
