#!/usr/bin/perl
#
# ------------------------
# UtahCountyHomes Database
# ------------------------
# Database Administrator
#
# File: uch.cgi
# Description: This is the main program file and contains all the functionality
# of the database manager.
# Author: Sven Kelling
# Email: sven@powervision.net
# Web: http://www.powervision.net
# Version: 3.0
#
# COPYRIGHT NOTICE:
#
# Copyright 1997 - 2002 PowerVision. All Rights Reserved.
#
# Selling the code for this program without prior written consent is
# expressly forbidden. Obtain permission before redistributing this
# program over the Internet or in any other medium. In all cases
# copyright and header must remain intact.
#
# Please check the README file for full details on registration.
# =====================================================================
# This script will only run from the URL's listed below
#&check_url;
@referers = ('www.powervision.net','powervision.net','www.thefoodguys.com','thefoodguys.com','www.utahcountycars.com','utahcountycars.com','www.utahcarsearch.com','www.utbay.com','utbay.com','www.utahcountyautoauction.com','utahcountyautoauction.com','utahcountyhomes.com','www.utahcountyhomes.com','209.15.22.58');
# If you run into problems, set $db_script_path to the full path
# to your directory.
$db_script_path = ".";
use CGI;
$query = new CGI;
# Actual path to directory holding temporary csv files
# NOTE: add trailing "/"
#(Make sure that this directory is chmod 755 on Unix servers)
$db_csv_path = "/home/utahcou/public_html/database/csv/";
# Actual url to directory holding temporary csv files
# NOTE: no trailing "/"
$db_csv_url = "http://www.utahcountyhomes.com/database/csv";
# Load the form information and set the config file and userid.
local(%in) = &parse_form;
$in{'db'} ? ($db_setup = $in{'db'}) : ($db_setup = 'userdata');
$in{'uid'} ? ($db_uid = $in{'uid'}): ($db_uid = '');
# Required Librariers
# --------------------------------------------------------
# Make sure we are using perl 5.003, load the config file, and load the auth file.
eval {
unshift (@INC, $db_script_path);
require 5.003; # We need at least Perl 5.003
unless ($db_setup =~ /^[A-Za-z0-9]+$/) { die "Invalid config file name: $db_setup"; }
require "$db_setup.cnfg"; # Database Definition File
require "auth.pl"; # Authorization Routines
};
if ($@) { &cgierr ("Error loading required libraries.\nCheck that they exist, permissions are set correctly and that they compile.\nReason: $@"); }
# If we are using benchmarking, then we start a timer and stop it around &main. Then we print the difference.
if ($db_benchmark) { $t0 = new Benchmark; }
eval { &main; }; # Trap any fatal errors so the program hopefully
if ($@) { &cgierr("fatal error: $@"); } # never produces that nasty 500 server error page.
# Stop the timer and print.
if ($db_benchmark) { $t1 = new Benchmark; print "
"; }
# Display debugging information if requested.
&cgierr("Debug Information") if ($db_debug);
exit; # There are only two exit calls in the script, here and in in &cgierr.
sub main {
# --------------------------------------------------------
# Puts up a maintenance screen if checked in .cnfg files while database is maintained
if ($db_maintenance) {
&html_maintenance;
exit;
}
my ($status, $uid);
local($per_add, $per_view, $per_mod, $per_del, $per_deal, $per_admin);
$|++; # Flush Output Right Away
&auth_cleanup unless ($auth_no_authentication); # Remove old session files.
($status, $uid, $per_view, $per_add, $per_del, $per_mod, $per_deal, $per_admin)
= &auth_check_password; # Authenticate User, get permissions and userid.
if ($status eq "ok") {
# Set the script link URL with db and user info for links. Use $db_script_url for forms.
$db_script_link_url = "$db_script_url?db=$db_setup&uid=$db_uid";
if ($uid eq "default") { $db_userid = $uid; }
else { ($db_userid) = $db_uid =~ /([A-Za-z0-9]+)\.\d+/; }
# Main Menu. Check to see what the user requested, then, if he has permission for that
# request, do it. Otherwise send the user off to an unauthorized request page.
if ($in{'add_form'}) { if ($per_add) { &html_add_form; } else { &html_unauth; } }
elsif ($in{'add_record'}) { if ($per_add) { &add_record; } else { &html_unauth; } }
elsif ($in{'add_form_owner'}) { if ($per_add) { &html_add_form_owner; } else { &html_unauth; } }
elsif ($in{'add_record_owner'}) { if ($per_add) { &add_record_owner; } else { &html_unauth; } }
elsif ($in{'topten'}) { if ($per_view) { &html_topten; }
else { &html_unauth; } }
elsif ($in{'view_search'}) { if ($per_view) { &html_view_search; } else { &html_unauth; } }
elsif ($in{'view_search_dealer'}) { if ($per_view) { &html_view_search_dealer; } else { &html_unauth; } }
elsif ($in{'view_records'}) { if ($per_view) { &view_records; } else { &html_unauth; } }
elsif ($in{'view_records2'}) { if ($per_view) { &view_records2; } else { &html_unauth; } }
elsif ($in{'view_records_noadds'}) { if ($per_view) { &view_records_noadds; } else { &html_unauth; } }
elsif ($in{'view_records_featured'}){ if ($per_view) { &view_records_featured; } else { &html_unauth; } }
elsif ($in{'viewrecordsdeal'}) { if ($per_mod) { &viewrecordsdeal; } else { &html_unauth; } }
elsif ($in{'viewrecpubdeal'}) { if ($per_view) { &viewrecpubdeal; } else { &html_unauth; } }
elsif ($in{'export_records'}) { if ($per_view) { &export_records; } else { &html_unauth; } }
elsif ($in{'delete_search'}) { if ($per_del) { &html_delete_search; } else { &html_unauth; } }
elsif ($in{'preview_record'}) { if ($per_add) { &preview_record; }
else { &html_unauth; } }
elsif ($in{'preview_record_owner'}) { if ($per_add) { &preview_record_owner; }
else { &html_unauth; } }
elsif ($in{'auto_delete'}) { if ($per_admin) { &auto_delete; }
else { &html_unauth; } }
elsif ($in{'auto_notify'}) { if ($per_admin) { &auto_notify; }
else { &html_unauth; } }
elsif ($in{'domain_error'}) { if ($per_view) { &html_domain_error; }
else { &html_unauth; } }
elsif ($in{'domain_error'}) { if ($per_view) { &html_domain_error; }
else { &html_unauth; } }
elsif ($in{'alert'}) { &alert; }
elsif ($in{'send_alert'}) { &send_alert; }
elsif ($in{'send_email_form'}) { &html_send_email_form; }
elsif ($in{'send_email'}) { &send_email; }
elsif ($in{'send_email_form2'}) { &html_send_email_form2; }
elsif ($in{'send_email2'}) { &send_email2; }
elsif ($in{'forward_email_form'}) { &html_forward_email_form; }
elsif ($in{'forward_email'}) { &forward_email; }
elsif ($in{'mass_mail_form'}) { if ($per_admin) { &html_mass_mail_form; }
else { &html_unauth; } }
elsif ($in{'mass_mail'}) { if ($per_admin) { &mass_mail; }
else { &html_unauth; } }
elsif ($in{'delete_form'}) { if ($per_del) { &html_delete_form; } else { &html_unauth; } }
elsif ($in{'delete_records'}) { if ($per_del) { &delete_records; } else { &html_unauth; } }
elsif ($in{'modify_search'}) { if ($per_mod) { &html_modify_search; } else { &html_unauth; } }
elsif ($in{'modify_form'}) { if ($per_mod) { &html_modify_form; } else { &html_unauth; } }
elsif ($in{'renew_search'}) { if ($per_mod) { &html_renew_search; } else { &html_unauth; } }
elsif ($in{'renew_form'}) { if ($per_del) { &html_renew_form; } else { &html_unauth; } }
elsif ($in{'renew'}) { if ($per_mod) { &renew; }
else { &html_unauth; } }
elsif ($in{'modify_form_record'}) { if ($per_mod) { &html_modify_form_record; }
else { &html_unauth; } }
elsif ($in{'modify_record'}) { if ($per_mod) { &modify_record; } else { &html_unauth; } }
elsif ($in{'admin_display'}) { if ($per_admin) { &admin_display; } else { &html_unauth; } }
elsif ($in{'logoff'}) { &auth_logging('logged off') if ($auth_logging);unlink ("$auth_dir/$uid");
#old logoff without back browser logout
#elsif ($in{'logoff'}) { &auth_logging('logged off') if #($auth_logging);
#
$auth_logoff ? (print "Location: $auth_logoff\n\n") : (print "Location: $db_script_url\n\n"); }
elsif ((keys(%in) <= 2) ||
($in{'login'})) { &html_home; }
elsif ((keys(%in) <= 2) ||
($in{'loginowner'})) { &html_home_owner; }
else { &html_unkown_action; }
}
# If we allow users to signup, and they want to, go to the signup form.
elsif ($auth_signup and $in{'signup_form'}) {
&html_signup_form;
}
elsif ($auth_signup and $in{'signup'}) {
&signup;
}
# If we allow owners to signup, and they want to, go to the signup form.
elsif ($auth_signup and $in{'signup_form_owner'}) {
&html_signup_form_owner;
}
elsif ($auth_signup and $in{'signupowner'}) {
&signupowner;
}
# Auth Check Password has determined that the user has not logged in, so let's send
# him to the login screen.
elsif ($status eq "no login") {
&html_login_form;
}
# Auth Check Password had an error trying to authenticate the user. Probably there was
# an invalid user/password or the user file has expired. Let's go to an error page and
# ask the user to re log on.
else {
&html_login_failure($status);
}
}
sub add_record {
# --------------------------------------------------------
# Adds a record to the database. First, validate_record is called
# to make sure the record is ok to add. If it is, then the record is
# encoded and added to the database and the user is sent to
# html_add_success, otherwise the user is sent to html_add_failure with
# an error message explaining why. The counter file is also updated to the
# next number.
&check_url;
my ($output, $status, $counter);
# Set the userid to the logged in user.
($auth_user_field >= 0) and ($in{$db_cols[$auth_user_field]} = $db_userid);
# First we validate the record to make sure the addition is ok.
if ($in{'file-to-upload-1'}) { $in{'Graphic'} = 'Yes'; }
else { $in{'Graphic'} = ''; }
$in{'Asking_Price'} =~ s/,//g; ### remove comma from entry
$in{'Asking_Price'} =~ s/\$//g; ### remove dollar sign from entry
#$in{'Milage'} =~ s/,//g; ### remove comma from entry
#$in{'DealerPrice'} =~ s/,//g; ### remove comma from entry
#$in{'DealerPrice'} =~ s/\$//g; ### remove dollar sign from entry
$status = &validate_record;
# We keep checking for the next available key, or until we've tried 50 times
# after which we give up.
while ($status eq "duplicate key error" and $db_key_track) {
return "duplicate key error" if ($counter++ > 50);
$in{$db_key}++;
$status = &validate_record;
}
if (($status eq "ok") && ($in{'file-to-upload-1'})) { $status = &validate_upload; } #Validate Pictures
if ($status eq "ok") {
open (DB, ">>$db_file_name") or &cgierr("error in add_record. unable to open database: $db_file_name.\nReason: $!");
if ($db_use_flock) {
flock(DB, 2) or &cgierr("unable to get exclusive lock on $db_file_name.\nReason: $!");
}
print DB &join_encode(%in);
close DB; # automatically removes file lock
if ($db_key_track) {
open (ID, ">$db_id_file_name") or &cgierr("error in get_defaults. unable to open id file: $db_id_file_name.\nReason: $!");
if ($db_use_flock) {
flock(ID, 2) or &cgierr("unable to get exclusive lock on $db_id_file_name.\nReason: $!");
}
print ID $in{$db_key}; # update counter.
close ID; # automatically removes file lock
}
&auth_logging("added record: $in{$db_key}") if ($auth_logging);
&html_add_success;
}
else {
&html_add_failure($status);
}
}
sub add_record_owner {
# --------------------------------------------------------
# Adds a record to the database. First, validate_record is called
# to make sure the record is ok to add. If it is, then the record is
# encoded and added to the database and the user is sent to
# html_add_success, otherwise the user is sent to html_add_failure with
# an error message explaining why. The counter file is also updated to the
# next number.
&check_url;
my ($output, $status, $counter);
# Set the userid to the logged in user.
($auth_user_field >= 0) and ($in{$db_cols[$auth_user_field]} = $db_userid);
# First we validate the record to make sure the addition is ok.
if ($in{'file-to-upload-1'}) { $in{'Graphic'} = 'Yes'; }
else { $in{'Graphic'} = ''; }
$in{'Asking_Price'} =~ s/,//g; ### remove comma from entry
$in{'Asking_Price'} =~ s/\$//g; ### remove dollar sign from entry
#$in{'Milage'} =~ s/,//g; ### remove comma from entry
#$in{'DealerPrice'} =~ s/,//g; ### remove comma from entry
#$in{'DealerPrice'} =~ s/\$//g; ### remove dollar sign from entry
$status = &validate_record;
# We keep checking for the next available key, or until we've tried 50 times
# after which we give up.
while ($status eq "duplicate key error" and $db_key_track) {
return "duplicate key error" if ($counter++ > 50);
$in{$db_key}++;
$status = &validate_record;
}
if (($status eq "ok") && ($in{'file-to-upload-1'})) { $status = &validate_upload; } #Validate Pictures
if ($status eq "ok") {
open (DB, ">>$db_file_name") or &cgierr("error in add_record. unable to open database: $db_file_name.\nReason: $!");
if ($db_use_flock) {
flock(DB, 2) or &cgierr("unable to get exclusive lock on $db_file_name.\nReason: $!");
}
print DB &join_encode(%in);
close DB; # automatically removes file lock
if ($db_key_track) {
open (ID, ">$db_id_file_name") or &cgierr("error in get_defaults. unable to open id file: $db_id_file_name.\nReason: $!");
if ($db_use_flock) {
flock(ID, 2) or &cgierr("unable to get exclusive lock on $db_id_file_name.\nReason: $!");
}
print ID $in{$db_key}; # update counter.
close ID; # automatically removes file lock
}
&auth_logging("added record: $in{$db_key}") if ($auth_logging);
&html_add_success_owner;
}
else {
&html_add_failure_owner($status);
}
}
sub preview_record {
# --------------------------------------------------------
my ($status, $counter);
# Set the userid to the logged in user.
($auth_user_field >= 0) and ($in{$db_cols[$auth_user_field]} = $db_userid);
# First we validate the record to make sure the addition is ok.
$status = &validate_record;
if ($in{'file-to-upload-1'}) { $in{'Graphic'} = 'Yes'; }
else { $in{'Graphic'} = ''; }
# We keep checking for the next available key, or until we've tried 50 times
# after which we give up.
while ($status eq "duplicate key error" and $db_key_track) {
return "duplicate key error" if ($counter++ > 50);
$in{$db_key}++;
$status = &validate_record;
}
if (($status eq "ok") && ($in{'file-to-upload-1'})) { $status = &validate_upload; } #Validate Pictures
if ($status eq "ok") {
&html_preview;
}
else {
&html_add_failure($status);
}
}
sub preview_record_owner {
# --------------------------------------------------------
my ($status, $counter);
# Set the userid to the logged in user.
($auth_user_field >= 0) and ($in{$db_cols[$auth_user_field]} = $db_userid);
# First we validate the record to make sure the addition is ok.
$status = &validate_record;
if ($in{'file-to-upload-1'}) { $in{'Graphic'} = 'Yes'; }
else { $in{'Graphic'} = ''; }
# We keep checking for the next available key, or until we've tried 50 times
# after which we give up.
while ($status eq "duplicate key error" and $db_key_track) {
return "duplicate key error" if ($counter++ > 50);
$in{$db_key}++;
$status = &validate_record;
}
if (($status eq "ok") && ($in{'file-to-upload-1'})) { $status = &validate_upload; } #Validate Pictures
if ($status eq "ok") {
&html_preview_owner;
}
else {
&html_add_failure_owner($status);
}
}
sub delete_records {
# --------------------------------------------------------
# Deletes a single or multiple records. First the routine goes thrrough
# the form input and makes sure there are some records to delete. It then goes
# through the database deleting each entry and marking it deleted. If there
# are any keys not deleted, an error message will be returned saying which keys
# were not found and not deleted, otherwise the user will go to the success page.
&check_url;
my ($key, %delete_list, $rec_to_delete, @lines, $line, @data, $errstr, $succstr, $output, $restricted);
$rec_to_delete = 0;
foreach $key (keys %in) { # Build a hash of keys to delete.
if ($in{$key} eq "delete") {
$delete_list{$key} = 1;
$rec_to_delete = 1;
}
}
if (!$rec_to_delete) {
&html_delete_failure("no records specified.");
return;
}
open (DB, "<$db_file_name") or &cgierr("error in delete_records. unable to open db file: $db_file_name.\nReason: $!");
if ($db_use_flock) { flock(DB, 1); }
@lines = ;
close DB;
($restricted = 1) if ($auth_modify_own and !$per_admin);
LINE: foreach $line (@lines) {
if ($line =~ /^$/) { next LINE; }
if ($line =~ /^#/) { $output .= $line; next LINE; }
chomp ($line);
@data = &split_decode($line);
($output .= "$line\n" and next LINE) if ($restricted and ($db_userid ne $data[$auth_user_field]));
if ($delete_list{$data[$db_key_pos]}) { # if this id is one we want to delete
$delete_list{$data[$db_key_pos]} = 0; # mark it deleted and don't print to the new database.
unlink "$counter_dir/$data[$db_key_pos]";
$succstr .= "$data[4] $data[8] $data[9] $data[3] \$$data[7],";
if ($db_upload) {
if (-e "$SAVE_DIRECTORY/$data[$db_key_pos]") {
opendir (GRAPHIC, "$SAVE_DIRECTORY/$data[$db_key_pos]") or &cgierr("unable to open directory in delete records: $SAVE_DIRECTORY/$data[$db_key_pos]. Reason: $!");
@files = readdir(GRAPHIC);
closedir (GRAPHIC);
foreach $file (@files) {
unlink ("$SAVE_DIRECTORY/$data[$db_key_pos]/$file");
}
rmdir ("$SAVE_DIRECTORY/$data[$db_key_pos]");
}
}
}
else { $output .= $line . "\n"; }
}
foreach $key (keys %delete_list) {
if ($delete_list{$key}) {
$errstr .= "$key,"; }}
#foreach $key (keys %delete_list) {
# $delete_list{$key} ? # Check to see if any items weren't deleted
# ($errstr .= "$key,") : # that should have been.
# ($succstr .= "$key $data[5] $data[6] $data[7],"); # For logging, we'll remember the one's we deleted.
#}
chop($succstr); # Remove trailing delimeter
chop($errstr); # Remove trailing delimeter
open (DB, ">$db_file_name") or &cgierr("error in delete_records. unable to open db file: $db_file_name.\nReason: $!");
if ($db_use_flock) {
flock(DB, 2) or &cgierr("unable to get exclusive lock on $db_file_name.\nReason: $!");
}
print DB $output;
close DB; # automatically removes file lock
&auth_logging("deleted records: $succstr") if ($auth_logging);
$errstr ? # Do we have an error?
&html_delete_failure($errstr) : # If so, then let's report go to the failure page,
&html_delete_success($succstr); # else, everything went fine.
}
sub renew {
# --------------------------------------------------------
# Renews a single or multiple records. First the routine goes thrrough
# the form input and makes sure there are some records to renew. It then goes
# through the database renewing each entry and marking it renewed. If there
# are any keys not renewed, an error message will be returned saying which keys
# were not found and not renewed, otherwise the user will go to the success page.
&check_url;
my ($key, %mod_list, $rec_to_mod, @lines, $line, @data, $errstr, $succstr, $output, $restricted, %mod_tmp);
$rec_to_mod = 0;
foreach $key (keys %in) { # Build a hash of keys to mod.
if ($in{$key} eq "modify") {
$mod_list{$key} = 1;
$rec_to_mod = 1;
}
}
if (!$rec_to_mod) {
&html_renew_failure("no records specified.");
return;
}
open (DB, "<$db_file_name") or &cgierr("error in renew. unable to open db file: $db_file_name.\nReason: $!");
if ($db_use_flock) { flock(DB, 1); }
@lines = ;
close DB;
($restricted = 1) if ($auth_modify_own and !$per_admin);
LINE: foreach $line (@lines) {
if ($line =~ /^$/) { next LINE; }
if ($line =~ /^#/) { $output .= $line; next LINE; }
chomp ($line);
@data = &split_decode($line);
($output .= "$line\n" and next LINE) if ($restricted and ($db_userid ne $data[$auth_user_field]));
if ($mod_list{$data[$db_key_pos]}) {
$mod_list{$data[$db_key_pos]} = 0;
%mod_tmp = &array_to_hash(0,@data);
$mod_tmp{'Entry_Date'} = &get_date;
$output .= &join_encode(%mod_tmp);
$succstr .= "$data[8] $data[9] $data[4],";
}
else {
$output .= $line . "\n";
}
}
foreach $key (keys %mod_list) {
if ($mod_list{$key}) {
$errstr .= "$key,";
}
}
# foreach $key (keys %mod_list) {
# $mod_list{$key} ? # Check to see if any items weren't modified
# ($errstr .= "$key,") ; # that should have been.
# For logging, we'll remember the one's we modified.
# }
chop($succstr); # Remove trailing delimeter
chop($errstr); # Remove trailing delimeter
open (DB, ">$db_file_name") or &cgierr("error in renew. unable to open db file: $db_file_name.\nReason: $!");
if ($db_use_flock) {
flock(DB, 2) or &cgierr("unable to get exclusive lock on $db_file_name.\nReason: $!");
}
print DB $output;
close DB; # automatically removes file lock
&auth_logging("modified records: $succstr") if ($auth_logging);
$errstr ? # Do we have an error?
&html_renew_failure($errstr) : # If so, then report & go to the failure page
&html_renew_success($succstr); # else, everything went fine.
}
sub modify_record {
# --------------------------------------------------------
# This routine does the actual modification of a record. It expects
# to find in %in a record that is already in the database, and will
# rewrite the database with the new entry. First it checks to make
# sure that the modified record is ok with validate record.
# It then goes through the database looking for the right record to
# modify, if found, it prints out the modified record, and returns
# the user to a success page. Otherwise the user is returned to an error
# page with a reason why.
&check_url;
my ($status, $line, @lines, @data, $output, $found, %rec, $key, $num_files, @files, $file);
if ($auth_modify_own and !$per_admin) {
%rec = &get_record($in{$db_key});
unless ($rec{$db_cols[$auth_user_field]} eq $db_userid) {
&html_modify_failure("You are not authorized to modify this record");
return;
}
}
foreach $key (keys %in) {
if ($in{$key} eq 'delete') {
unlink "$SAVE_DIRECTORY/$in{$db_key}/$key";
}
}
$num_files=0;
if (-e "$SAVE_DIRECTORY/$in{$db_key}") {
opendir (GRAPHIC, "$SAVE_DIRECTORY/$in{$db_key}") or &cgierr("unable to open directory: $SAVE_DIRECTORY/$rec{$db_key}. Reason: $!");
@files = readdir(GRAPHIC);
closedir (GRAPHIC);
foreach $file (@files) {
next if ($file =~ /^\./); # Skip "." and ".." entries..
next if ($file =~ /^index/); # Skip index.htm type files..
++$num_files;
}
}
if ($num_files or $in{'file-to-upload-1'}) { $in{'Graphic'} = 'Yes'; }
else { $in{'Graphic'} = ''; }
$in{'Entry_Date'} = &get_date;
$status = &validate_record; # Check to make sure the modifications are ok!
if (($status eq "ok") && ($in{'file-to-upload-1'})) { $status = &validate_upload; } #Validate Pictures
if ($status eq "ok") {
open (DB, "<$db_file_name") or &cgierr("error in modify_records. unable to open db file: $db_file_name.\nReason: $!");
if ($db_use_flock) { flock(DB, 1); }
@lines = ; # Slurp the database into @lines..
close DB;
$found = 0; # Make sure the record is in here!
LINE: foreach $line (@lines) {
if ($line =~ /^$/) { next LINE; } # Skip and Remove blank lines
if ($line =~ /^#/) { $output .= $line; next LINE; } # Comment Line
chomp ($line);
@data = &split_decode($line);
if ($data[$db_key_pos] eq $in{$db_key}) {
# If we have userid's and this is not an admin, then we force the record to keep it's own
# userid.
if ($auth_user_field >= 0 and (!$per_admin or !$in{$db_cols[$auth_user_field]})) {
$in{$db_cols[$auth_user_field]} = $data[$auth_user_field];
}
$output .= &join_encode(%in);
$found = 1;
}
else {
$output .= $line . "\n"; # else print regular line.
}
}
if ($found) {
open (DB, ">$db_file_name") or &cgierr("error in modify_records. unable to open db file: $db_file_name.\nReason: $!");
if ($db_use_flock) {
flock(DB, 2) or &cgierr("unable to get exclusive lock on $db_file_name.\nReason: $!");
}
print DB $output;
close DB; # automatically removes file lock
&auth_logging("modified record: $in{$db_key}") if ($auth_logging);
&html_modify_success;
}
else {
&html_modify_failure("$in{$db_key} (can't find requested record)");
}
}
else {
&html_modify_failure($status); # Validation Error
}
}
sub view_records {
# --------------------------------------------------------
# This is called when a user is searching the database for
# viewing. All the work is done in query() and the routines just
# checks to see if the search was successful or not and returns
# the user to the appropriate page.
&check_url;
&log_search;
my ($status, @hits) = &query("view");
if ($status eq "ok") {
&html_view_success(@hits);
}
else {
&html_view_failure($status);
}
}
sub view_records2 {
# --------------------------------------------------------
# This is called when a user is searching the database for
# viewing. All the work is done in query() and the routines just
# checks to see if the search was successful or not and returns
# the user to the appropriate page.
&check_url;
&log_search;
my ($status, @hits) = &query("view");
if ($status eq "ok") {
&html_view_success(@hits);
}
else {
&html_view_failure($status);
}
}
sub view_records_noadds {
# --------------------------------------------------------
# This is called when a user is searching the database for
# viewing. All the work is done in query() and the routines just
# checks to see if the search was successful or not and returns
# the user to the appropriate page.
&check_url;
&log_search;
my ($status, @hits) = &query("view");
if ($status eq "ok") {
&html_view_success_noadds(@hits);
}
else {
&html_view_failure_noadds($status);
}
}
sub view_records_featured {
# --------------------------------------------------------
# This is called when a user is searching the database for
# viewing. All the work is done in query() and the routines just
# checks to see if the search was successful or not and returns
# the user to the appropriate page.
&check_url;
&log_search;
my ($status, @hits) = &query("view");
if ($status eq "ok") {
&html_view_success_featured(@hits);
}
else {
&html_view_failure($status);
}
}
sub viewrecordsdeal {
# --------------------------------------------------------
# This is called when a Dealer is searching the database for
# viewing wholesale. All the work is done in query() and the routines just
# checks to see if the search was successful or not and returns
# the user to the appropriate page.
&check_url;
my ($status, @hits) = &query("view");
if ($status eq "ok") {
&html_view_success(@hits);
}
else {
&html_view_failure($status);
}
}
sub viewrecpubdeal {
# --------------------------------------------------------
# This is called when the public is searching the database for a
# Dealer. All the work is done in query() and the routines just
# checks to see if the search was successful or not and returns
# the user to the appropriate page.
&check_url;
my ($status, @hits) = &query("view");
if ($status eq "ok") {
&html_view_success_pub_deal(@hits);
}
else {
&html_view_failure($status);
}
}
sub query {
# --------------------------------------------------------
# First let's get a list of database fields we want to search on and
# store it in @search_fields
&check_url;
my ($i, $column, @search_fields, @search_gt_fields, @search_lt_fields, $maxhits, $numhits, $nh,
$field, @regexp, $line, @values, $key_match, @hits, @sortedhits, $next_url, $next_hit, $prev_hit,
$first, $last, $upper, $lower, $left, $right, $restricted);
# local (%sortby);
local (%sortby1);
local (%sortby2);
local (%sortby3);
if ($in{'Year_Built-gt'}) { $in{'Year_Built-gt'} = $in{'Year_Built-gt'} - .01; }if ($in{'Year_Built-lt'}) {$in{'Year_Built-lt'} = $in{'Year_Built-lt'} + .01; }
# First thing we do is find out what we are searching for. We build a list of fields
# we want to search on in @search_fields.
if ($in{'keyword'}) { # If this is a keyword search, we are searching the same
$i = 0; # thing in all fields. Make sure "match any" option is
$in{'ma'} = "on"; # on, otherwise this will almost always fail.
foreach $column (@db_cols) {
if (($db_sort{$column} eq 'date') or &date_to_unix($in{'keyword'})) { $i++; next; }
if ($i == $auth_user_field) { $i++; next; }
push (@search_fields, $i); # Search every column
$in{$column} = $in{'keyword'}; # Fill %in with keyword we are looking for.
$i++;
}
}
else { # Otherwise this is a regular search, and we only want records
$i = 0; # that match everything the user specified for.
foreach $column (@db_cols) {
if ($in{$column} =~ /^\>(.+)$/) { ($db_sort{$column} eq 'date') and (&date_to_unix($1) or return "Invalid date format: '$1'");
push (@search_gt_fields, $i); $in{"$column-gt"} = $1; $i++; next; }
if ($in{$column} =~ /^\<(.+)$/) { ($db_sort{$column} eq 'date') and (&date_to_unix($1) or return "Invalid date format: '$1'");
push (@search_lt_fields, $i); $in{"$column-lt"} = $1; $i++; next; }
if ($in{$column} !~ /^\s*$/) { ($db_sort{$column} eq 'date') and (&date_to_unix($in{$column}) or return "Invalid date format: '$in{$column}'");
push(@search_fields, $i); $i++; next; }
if ($in{"$column-gt"} !~ /^\s*$/) { ($db_sort{$column} eq 'date') and (&date_to_unix($in{"$column-gt"}) or return "Invalid date format: '$in{$column}'");
push(@search_gt_fields, $i); }
if ($in{"$column-lt"} !~ /^\s*$/) { ($db_sort{$column} eq 'date') and (&date_to_unix($in{"$column-lt"}) or return "Invalid date format: '$in{$column}'");
push(@search_lt_fields, $i); }
$i++;
}
}
# If we don't have anything to search on, let's complain.
if (!@search_fields and !@search_gt_fields and !@search_lt_fields) {
return "no search terms specified";
}
# Define the maximum number of hits we will allow, and the next hit counter.
$in{'mh'} ? ($maxhits = $in{'mh'}) : ($maxhits = $db_max_hits);
$in{'nh'} ? ($nh = $in{'nh'}) : ($nh = 1);
$numhits = 0;
# Let's set restricted to 1 if the user can only view/mod their own and
# this isn't an admin.
($restricted = 1) if ($_[0] eq "view" and $auth_view_own and !$per_admin);
($restricted = 1) if ($_[0] eq "mod" and $auth_modify_own and !$per_admin);
# Now let's build up all the regexpressions we will use. This saves the program
# from having to recompile the same regular expression every time.
foreach $field (@search_fields) {
my $tmpreg = "$in{$db_cols[$field]}";
(!$in{'re'}) and ($tmpreg = "\Q$tmpreg\E");
($in{'ww'}) and ($tmpreg = "\\b$tmpreg\\b");
(!$in{'cs'}) and ($tmpreg = "(?i)$tmpreg");
($in{$db_cols[$field]} eq "*") and ($tmpreg = ".*"); # A "*" matches anything.
$regexp_func[$field] = eval 'sub { m/$tmpreg/o; }';
$regexp_bold[$field] = $tmpreg;
}
# Now we go through the database and do the actual searching.
# First figure out which records we want:
$first = ($maxhits * ($nh - 1));
$last = $first + $maxhits - 1;
open (DB, "<$db_file_name") or &cgierr("error in search. unable to open database: $db_file_name.\nReason: $!");
if ($db_use_flock) { flock(DB, 1); }
LINE: while () {
(/^#/) and next LINE; # Skip comment Lines.
(/^\s*$/) and next LINE; # Skip blank lines.
$line = $_; chomp ($line); # Remove trailing new line.
@values = &split_decode($line);
# If we are only allowed to view/mod our own record, then let's check here.
next LINE if ($restricted and ($db_userid ne $values[$auth_user_field]));
# Normal searches.
$key_match = 0;
foreach $field (@search_fields) {
$_ = $values[$field]; # Reg function works on $_.
$in{'ma'} ?
($key_match = ($key_match or &{$regexp_func[$field]})) :
(&{$regexp_func[$field]} or next LINE);
}
# Greater then searches.
foreach $field (@search_gt_fields) {
$term = $in{"$db_cols[$field]-gt"};
if ($db_sort{$db_cols[$field]} eq "date") {
$in{'ma'} ?
($key_match = ($key_match or (&date_to_unix($values[$field])) > &date_to_unix($term))) :
(&date_to_unix($values[$field]) > (&date_to_unix($term)) or next LINE);
}
elsif ($db_sort{$db_cols[$field]} eq 'alpha') {
$in{'ma'} ?
($key_match = ($key_match or ($values[$field] > $term))) :
((lc($values[$field]) gt lc($term)) or next LINE);
}
else {;
$in{'ma'} ?
($key_match = ($key_match or ($values[$field] > $term))) :
(($values[$field] > $term) or next LINE);
}
}
# Less then searches.
foreach $field (@search_lt_fields) {
$term = $in{"$db_cols[$field]-lt"};
if ($db_sort{$db_cols[$field]} eq "date") {
$in{'ma'} ?
($key_match = ($key_match or (&date_to_unix($values[$field]) < &date_to_unix($term)))) :
(&date_to_unix($values[$field]) < (&date_to_unix($term)) or next LINE);
}
elsif ($db_sort{$db_cols[$field]} eq 'alpha') {
$in{'ma'} ?
($key_match = ($key_match or ($values[$field] < $term))) :
((lc($values[$field]) lt lc($term)) or next LINE);
}
else {
$in{'ma'} ?
($key_match = ($key_match or ($values[$field] < $term))) :
(($values[$field] < $term) or next LINE);
}
}
if ($key_match || (!($in{'keyword'}) && !($in{'ma'}))) {
if (exists $in{'sb1'} && exists $in{'sb2'} && exists $in{'sb3'}) {
$sortby1{(($#hits+1) / ($#db_cols+1))} = $values[$in{'sb1'}];
$sortby2{(($#hits+1) / ($#db_cols+1))} = $values[$in{'sb2'}];
$sortby3{(($#hits+1) / ($#db_cols+1))} = $values[$in{'sb3'}];
push (@hits, @values);
}
elsif (exists $in{'sb1'} && exists $in{'sb2'}) {
$sortby1{(($#hits+1) / ($#db_cols+1))} = $values[$in{'sb1'}];
$sortby2{(($#hits+1) / ($#db_cols+1))} = $values[$in{'sb2'}];
push (@hits, @values);
}
elsif (exists $in{'sb1'}) {
$sortby1{(($#hits+1) / ($#db_cols+1))} = $values[$in{'sb1'}];
push (@hits, @values);
}
else {
(($numhits >= $first) and ($numhits <= $last)) and push (@hits, @values);
}
$numhits++; # But we always count it!
}
}
close DB;
# Now we've stored all our hits in @hits, and we've got a sorting values stored in %sortby indexed by their position in @hits.
$numhits ? ($db_total_hits = $numhits) : ($db_total_hits = 0);
($db_total_hits == 0) and return ("no matching records.");
# Sort the array @hits in order if we are meant to sort.
if (exists $in{'sb1'}) { # Sort hits on first field.
my ($sort_func, $tmp_func);
$sort_func = "";
$sort_pos = 1;
$sb_num = "sb" . "$sort_pos";
while (exists ($in{$sb_num})) {
$tmp_func = $sort_func eq "" ? "" : "$sort_func" . " || ";
$sort_func = $tmp_func . &build_sort_func;
$sort_pos += 1;
$sb_num = "sb" . "$sort_pos";
}
$sort_func =~ tr/!/$/; # Replace temporary characters with $
foreach $hit (sort { eval($sort_func); } (keys %sortby1)) {
$first = ($hit * $#db_cols) + $hit; $last = ($hit * $#db_cols) + $#db_cols + $hit;
push (@sortedhits, @hits[$first .. $last]);
}
@hits = @sortedhits;
}
# If we have to many hits, let's build the next toolbar, and return only the hits we want.
if ($numhits > $maxhits) {
# Remove the nh= from the query string.
$next_url = $ENV{'QUERY_STRING'};
$next_url =~ s/\&nh=\d+//;
$next_hit = $nh + 1; $prev_hit = $nh - 1;
# Build the next hits toolbar. It seems really complicated as we have to do
# some number crunching to keep track of where we are on the toolbar, and so
# that the toolbar stays centered.
# First, set how many pages we have on the left and the right.
$left = $nh; $right = int($numhits/$maxhits) - $nh;
# Then work out what page number we can go above and below.
($left > 7) ? ($lower = $left - 7) : ($lower = 1);
($right > 7) ? ($upper = $nh + 7) : ($upper = int($numhits/$maxhits) + 1);
# Finally, adjust those page numbers if we are near an endpoint.
(7 - $nh >= 0) and ($upper = $upper + (8 - $nh));
($nh > ($numhits/$maxhits - 7)) and ($lower = $lower - ($nh - int($numhits/$maxhits - 7) - 1));
$db_next_hits = "";
# Then let's go through the pages and build the HTML.
($nh > 1) and ($db_next_hits .= qq~[<<] ~);
for ($i = 1; $i <= int($numhits/$maxhits) + 1; $i++) {
if ($i < $lower) { $db_next_hits .= " ... "; $i = ($lower-1); next; }
if ($i > $upper) { $db_next_hits .= " ... "; last; }
($i == $nh) ?
($db_next_hits .= qq~$i ~) :
($db_next_hits .= qq~$i ~);
if (($i * $maxhits) >= $numhits) { last; } # Special case if we hit exact.
}
$db_next_hits .= qq~[>>] ~ unless ($nh == $i);
# Slice the @hits to only return the ones we want, only have to do this if the results are sorted.
if (exists $in{'sb1'}) {
$first = ($maxhits * ($nh - 1)) * ($#db_cols+1);
$last = $first + (($#db_cols+1) * $maxhits) - 1;
$last = $#hits if ($last > $#hits);
@hits = @hits[$first .. $last];
}
}
# Bold the results
if ($db_bold and $in{'view_records'}) {
for $i (0 .. (($#hits+1) / ($#db_cols+1)) - 1) {
$offset = $i * ($#db_cols+1);
foreach $field (@search_fields) {
$hits[$field + $offset] =~ s,(<[^>]+>)|($regexp_bold[$field]),defined($1) ? $1 : "$2",ge;
}
}
}
return ("ok", @hits);
}
sub log_search {
# --------------------------------------------------------
#
my $curr_time = time;
my $term = lc($in{'query'});
if ((-e "$kword_file") && ($term)) {
if ((-s "$kword_file") > 1000000) {
open (DAT, ">$kword_file") ||
&cgierr ("Error 01 [search.cgi]: Cannot open search log file. Reason: $!");
flock (DAT, 2) ||
&cgierr ("Error 02 [search.cgi]: Cannot flock search log file. Reason: $!");
print DAT "$term|1|$curr_time\n";
close (DAT);
}
else {
open (DAT, "<$kword_file") ||
&cgierr ("Error 03 [search.cgi]: Cannot open search log file. Reason: $!");
@kwords = ;
close (DAT);
chomp @kwords;
undef $newfile;
undef $found;
foreach (@kwords) {
($word, $count, $oldtime) = split (/\|/,$_);
if ($term eq lc($word)) {
$count++;
$found++;
$newfile .= "$word|$count|$curr_time\n";
}
else { $newfile .= "$_\n"; }
}
if (! $found) { $newfile .= "$term|1|$curr_time\n"; }
open (DAT, ">$kword_file") ||
&cgierr ("Error 04 [search.cgi]: Cannot open search log file. Reason: $!");
flock (DAT, 2) ||
&cgierr ("Error 05 [search.cgi]: Cannot flock search log file. Reason: $!");
print DAT $newfile;
close (DAT);
}
}
elsif ((! -e "$kword_file") && ($term)) {
open (DAT, ">$kword_file") ||
&cgierr ("Error 06 [search.cgi]: Cannot create search log file. Reason: $!");
flock (DAT, 2) ||
&cgierr ("Error 07 [search.cgi]: Cannot flock search log file. Reason: $!");
print DAT "$term|1|$curr_time\n";
close (DAT);
chmod (0666, "$kword_file") ||
&cgierr ("Error 08 [search.cgi]: Cannot chmod search log file. Reason: $!");
}
}
sub admin_display {
# --------------------------------------------------------
# Let's an admin add/update/remove users from the authorization file.
#
my ($message, @lines, $line);
# Do we have anything to do?
CASE: {
# If we've been passed in new_username, then we are adding a new user. Do
# some basic error checking and then add him into the password file.
$in{'new_username'} and do {
unless ((length($in{'new_username'}) >= 3) and (length($in{'new_username'}) <= 12) and ($in{'new_username'} =~ /^[a-zA-Z0-9]+$/)) {
$message = "Invalid username: $in{'new_username'}. Must only contain letters and numbers and be less then 12 and greater then 3 characters.";
last CASE;
}
unless ((length($in{'password'}) >= 3) and (length($in{'password'}) <= 12)) {
$message = "Invalid password: '$in{'password'}'. Must be less then 12 and greater then 3 characters.";
last CASE;
}
open (PASS, ">>$auth_pw_file") or &cgierr ("unable to open: $auth_pw_file.\nReason: $!");
if ($db_use_flock) {
flock(PASS, 2) or &cgierr("unable to get exclusive lock on $auth_pw_file.\nReason: $!");
}
my @salt_chars = ('A' .. 'Z', 0 .. 9, 'a' .. 'z', '.', '/');
my $salt = join '', @salt_chars[rand 64, rand 64];
my $encrypted = crypt($in{'password'}, $salt);
print PASS "$in{'new_username'}:$encrypted:$in{'per_view'}:$in{'per_add'}:$in{'per_del'}:$in{'per_mod'}:$in{'per_deal'}:$in{'per_admin'}\n";
close PASS;
$message = "User: $in{'new_username'} created.";
last CASE;
};
# If we've been passed in delete, then we are removing a user. Check
# to make sure a user was selected then try and remove him.
$in{'delete'} and do {
unless ($in{'username'}) {
$message = "No username selected to delete.";
last CASE;
}
open (PASS, "<$auth_pw_file") or &cgierr ("unable to open: $auth_pw_file.\nReason: $!");
if ($db_use_flock) { flock(PASS, 1) }
@lines = ;
close PASS;
open (PASS, ">$auth_pw_file") or &cgierr ("unable to open: $auth_pw_file.\nReason: $!");
if ($db_use_flock) {
flock(PASS, 2) or &cgierr("unable to get exclusive lock on $auth_pw_file.\nReason: $!");
}
my $found = 0;
foreach $line (@lines) {
($line =~ /^$in{'username'}:/) ?
($found = 1) :
print PASS $line;
}
close PASS;
$found ?
($message = "User: $in{'username'} deleted.") :
($message = "Unable to find userid: $in{'username'} in password file.");
last CASE;
};
# If we have a username, and the admin didn't press inquire, then
# we are updating a user.
($in{'username'} && !$in{'inquire'}) and do {
open (PASS, "<$auth_pw_file") or &cgierr ("unable to open: $auth_pw_file.\nReason: $!");
if ($db_use_flock) { flock(PASS, 1); }
@lines = ;
close PASS;
open (PASS, ">$auth_pw_file") or &cgierr ("unable to open: $auth_pw_file.\nReason: $!");
if ($db_use_flock) {
flock(PASS, 2) or &cgierr("unable to get exclusive lock on $auth_pw_file.\nReason: $!");
}
my $found = 0;
foreach $line (@lines) {
if ($line =~ /^$in{'username'}:/) {
my $password = (split (/:/, $line))[1];
unless ($password eq $in{'password'}) {
my @salt_chars = ('A' .. 'Z', 0 .. 9, 'a' .. 'z', '.', '/');
my $salt = join '', @salt_chars[rand 64, rand 64];
$password = crypt($in{'password'}, $salt);
}
print PASS "$in{'username'}:$password:$in{'per_view'}:$in{'per_add'}:$in{'per_del'}:$in{'per_mod'}:$in{'per_deal'}:$in{'per_admin'}\n";
$found = 1;
}
else {
print PASS $line;
}
}
$in{'inquire'} = $in{'username'};
$found ?
($message = "User: $in{'username'} updated.") :
($message = "Unable to find user: '$in{'username'}' in the password file.");
last CASE;
};
};
# Now let's load the list of users.
open (PASS, "<$auth_pw_file") or &cgierr ("unable to open: $auth_pw_file.\nReason: $!");
if ($db_use_flock) { flock(PASS, 1); }
@lines = ;
close PASS;
# If we are inquiring, let's look for the specified user.
my (@data, $user_list, $perm, $password);
$user_list = qq~";
# Build the permissions list if we haven't inquired in someone.
if (!$perm) {
$perm = qq|
View
Add
Delete
Modify
Dealer
Admin |;
}
&html_admin_display ($message, $user_list, $password, $perm);
}
sub signup {
# --------------------------------------------------------
# Allows a user to sign up without admin approval. Must have $auth_signup = 1
# set. The user gets @default_permissions.
#
my $message;
# Check to make sure userid is ok, pw ok, and userid is unique.
unless ((length($in{'userid'}) >= 3) and (length($in{'userid'}) <= 12) and ($in{'userid'} =~ /^[a-zA-Z0-9]+$/)) {
$message = "Invalid userid: $in{'userid'}. Must only contain only letters and be less then 12 and greater then 3 characters.";
}
unless ((length($in{'pw'}) >= 3) and (length($in{'pw'}) <= 12)) {
$message = "Invalid pw: '$in{'pw'}'. Must be less then 12 and greater then 3 characters.";
}
unless ($in{'pw'} eq $in{'pw2'}) {
$message = "You must enter the same password twice";
}
open (PASS, "<$auth_pw_file") or &cgierr ("unable to open: $auth_pw_file.\nReason: $!");
if ($db_use_flock) { flock(PASS, 1); }
while () {
/^\Q$in{'userid'}\E:/ and ($message = "userid already exists. Please try another.");
}
close PASS;
if ($message) {
&html_signup_form ($message);
return;
}
# Add the userid into the file with default permissions.
open (PASS, ">>$auth_pw_file") or &cgierr ("unable to open: $auth_pw_file.\nReason: $!");
if ($db_use_flock) {
flock(PASS, 2) or &cgierr("unable to get exclusive lock on $auth_pw_file.\nReason: $!");
}
srand( time() ^ ($$ + ($$ << 15)) ); # Seed Random Number
my @salt_chars = ('A' .. 'Z', 0 .. 9, 'a' .. 'z', '.', '/');
my $salt = join '', @salt_chars[rand 64, rand 64];
my $encrypted = crypt($in{'pw'}, $salt);
my $permissions = join (":", @auth_signup_permissions);
print PASS "$in{'userid'}:$encrypted:$permissions\n";
close PASS;
&html_signup_success;
}
sub signupowner {
# --------------------------------------------------------
# Allows a user to sign up without admin approval. Must have $auth_signup = 1
# set. The user gets @default_permissions.
#
my $message;
# Check to make sure userid is ok, pw ok, and userid is unique.
unless ((length($in{'userid'}) >= 3) and (length($in{'userid'}) <= 12) and ($in{'userid'} =~ /^[a-zA-Z0-9]+$/)) {
$message = "Invalid userid: $in{'userid'}. Must only contain only letters and be less then 12 and greater then 3 characters.";
}
unless ((length($in{'pw'}) >= 3) and (length($in{'pw'}) <= 12)) {
$message = "Invalid pw: '$in{'pw'}'. Must be less then 12 and greater then 3 characters.";
}
unless ($in{'pw'} eq $in{'pw2'}) {
$message = "You must enter the same password twice";
}
open (PASS, "<$auth_pw_file") or &cgierr ("unable to open: $auth_pw_file.\nReason: $!");
if ($db_use_flock) { flock(PASS, 1); }
while () {
/^\Q$in{'userid'}\E:/ and ($message = "userid already exists. Please try another.");
}
close PASS;
if ($message) {
&html_signup_form_owner ($message);
return;
}
# Add the userid into the file with default permissions.
open (PASS, ">>$auth_pw_file") or &cgierr ("unable to open: $auth_pw_file.\nReason: $!");
if ($db_use_flock) {
flock(PASS, 2) or &cgierr("unable to get exclusive lock on $auth_pw_file.\nReason: $!");
}
srand( time() ^ ($$ + ($$ << 15)) ); # Seed Random Number
my @salt_chars = ('A' .. 'Z', 0 .. 9, 'a' .. 'z', '.', '/');
my $salt = join '', @salt_chars[rand 64, rand 64];
my $encrypted = crypt($in{'pw'}, $salt);
my $permissions = join (":", @auth_signup_permissions);
print PASS "$in{'userid'}:$encrypted:$permissions\n";
close PASS;
&html_signup_success_owner;
}
sub get_record {
# --------------------------------------------------------
# Given an ID as input, get_record returns a hash of the
# requested record or undefined if not found.
my ($key, $found, $line, @data, $field, $restricted);
$key = $_[0];
$found = 0;
# ($restricted = 1) if ($auth_modify_own and !$per_admin);
open (DB, "<$db_file_name") or &cgierr("error in get_records. unable to open db file: $db_file_name.\nReason: $!");
if ($db_use_flock) { flock(DB, 1); }
LINE: while () {
(/^#/) and next LINE;
(/^\s*$/) and next LINE;
$line = $_; chomp ($line);
@data = &split_decode($line);
next LINE if ($restricted and ($db_userid ne $data[$auth_user_field]));
if ($data[$db_key_pos] eq $key) {
$found = 1;
for ($i = 0; $i <= $#db_cols; $i++) { # Map the array columns to a hash.
$rec{$db_cols[$i]} = $data[$i];
}
last LINE;
}
}
close DB;
$found ?
(return %rec) :
(return undef);
}
sub get_defaults {
# --------------------------------------------------------
# Returns a hash of the defaults used for a new record.
my (%default);
foreach $field (keys %db_defaults) {
$default{$field} = $db_defaults{$field};
## Below this adds userid in add form ##
($auth_user_field >=0) and ($db_defaults{$db_cols[$auth_user_field]} = $db_userid);
}
if ($db_key_track) {
open (ID, "<$db_id_file_name") or &cgierr("error in get_defaults. unable to open id file: $db_id_file_name.\nReason: $!");
if ($db_use_flock) { flock(ID, 1); }
$default{$db_key} = + 1; # Get next ID number
close ID;
}
return %default;
}
sub validate_record {
# --------------------------------------------------------
# Verifies that the information passed through the form and stored
# in %in matches a valid record. It checks first to see that if
# we are adding, that a duplicate ID key does not exist. It then
# checks to see that fields specified as not null are indeed not null,
# finally it checks against the reg expression given in the database
# definition.
my ($col, @input_err, $errstr, $err, $line, @lines, @data);
if ($in{'add_record'}) { # don't need to worry about duplicate key if modifying
open (DB, "<$db_file_name") or &cgierr("error in validate_records. unable to open db file: $db_file_name.\nReason: $!");
if ($db_use_flock) { flock(DB, 1); }
LINE: while () {
(/^#/) and next LINE;
(/^\s*$/) and next LINE;
$line = $_; chomp ($line);
@data = &split_decode($line);
if ($data[$db_key_pos] eq $in{$db_key}) {
return "duplicate key error";
}
}
close DB;
}
foreach $col (@db_cols) {
if ($in{$col} =~ /^\s*$/) { # entry is null or only whitespace
($db_not_null{$col}) and # entry is not allowed to be null.
push(@input_err, "$col (Can not be left blank)"); # so let's add it as an error
}
else { # else entry is not null.
($db_valid_types{$col} && !($in{$col} =~ /$db_valid_types{$col}/)) and
push(@input_err, "$col (Invalid format)"); # but has failed validation.
}
(length($in{$col}) > $db_lengths{$col}) and
push (@input_err, "$col (Too long. Max length: $db_lengths{$col})");
if ($db_sort{$col} eq "date") {
push (@input_err, "$col (Invalid date format)") unless &date_to_unix($in{$col});
}
}
if ($#input_err+1 > 0) { # since there are errors, let's build
foreach $err (@input_err) { # a string listing the errors
$errstr .= "
$err"; # and return it.
}
return "
$errstr
";
}
else {
return "ok"; # no errors, return ok.
}
}
sub join_encode {
# --------------------------------------------------------
# Takes a hash (ususally from the form input) and builds one
# line to output into the database. It changes all occurrences
# of the database delimeter to '~~' and all newline chars to '``'.
my (%hash) = @_;
my ($tmp, $col, $output);
foreach $col (@db_cols) {
$tmp = $hash{$col};
$tmp =~ s/^\s+//g; # Trim leading blanks...
$tmp =~ s/\s+$//g; # Trim trailing blanks...
$tmp =~ s/\Q$db_delim\E/~~/og; # Change delimeter to ~~ symbol.
$tmp =~ s/\n/``/g; # Change newline to `` symbol.
$tmp =~ s/\r//g; # Remove Windows linefeed character.
$output .= $tmp . $db_delim; # Build Output.
}
chop $output; # remove extra delimeter.
$output .= "\n"; # add linefeed char.
return $output;
}
sub split_decode {
# --------------------------------------------------------
# Takes one line of the database as input and returns an
# array of all the values. It replaces special mark up that
# join_encode makes such as replacing the '``' symbol with a
# newline and the '~~' symbol with a database delimeter.
my ($input) = shift;
$input =~ s/\Q$db_delim\E$/$db_delim /o; # Add a space if we have delimiter new line.
my (@array) = split (/\Q$db_delim\E/o, $input);
for ($i = 0; $i <= $#array; $i++) {
$array[$i] =~ s/~~/$db_delim/og; # Retrieve Delimiter..
$array[$i] =~ s/``/\n/g; # Change '' back to newlines..
}
return @array;
}
sub build_select_field {
# --------------------------------------------------------
# Builds a SELECT field based on information found
# in the database definition. Parameters are the column to build
# and a default value (optional).
my ($column, $value) = @_;
my (@fields, $ouptut);
@fields = split (/\,/, $db_select_fields{$column});
if ($#fields == -1) {
$output = "error building select field: no select fields specified in config for field '$column'!";
}
else {
$output = qq|";
}
return $output;
}
sub build_select_field_from_db {
# --------------------------------------------------------
# Builds a SELECT field from the database.
my ($column, $value, $name) = @_;
my (@fields, $field, @selectfields, @lines, $line, $ouptut);
my ($fieldnum, $found, $i) = 0;
$name || ($name = $column);
for ($i = 0; $i <= $#db_cols; $i++) {
if ($column eq $db_cols[$i]) {
$fieldnum = $i; $found = 1;
last;
}
}
if (!$found) {
return "error building select field: no fields specified!";
}
open (DB, "<$db_file_name") or &cgierr("unable to open $db_file_name. Reason: $!");
if ($db_use_flock) { flock(DB, 1); }
LINE: while () {
next if /^#/;
next if /^\s*$/;
$line = $_;
chomp ($line);
@fields = &split_decode ($line);
if (!(grep $_ eq $fields[$fieldnum], @selectfields)) {
push (@selectfields, $fields[$fieldnum]);
}
}
close DB;
$output = qq|";
return $output;
}
sub build_checkbox_field {
# --------------------------------------------------------
# Builds a CHECKBOX field based on information found
# in the database definition. Parameters are the column to build
# whether it should be checked or not and a default value (optional).
my ($column, $values) = @_;
if (!$db_checkbox_fields{$column}) {
return "error building checkboxes: no checkboxes specified in config for field '$column'";
}
my @names = split (/,/, $db_checkbox_fields{$column});
my @values = split (/\Q$db_delim\E/, $values);
my ($name, $output);
foreach $name (@names) {
(grep $_ eq $name, @values) ?
($output .= qq! $name\n!) :
($output .= qq! $name\n!);
}
return $output;
}
sub build_radio_field {
# --------------------------------------------------------
# Builds a RADIO Button field based on information found
# in the database definition. Parameters are the column to build
# and a default value (optional).
my ($column, $value) = @_;
my (@buttons, $button, $output);
@buttons = split (/,/, $db_radio_fields{$column});
if ($#buttons == -1) {
$output = "error building radio buttons: no radio fields specified in config for field '$column'!";
}
else {
foreach $button (@buttons) {
$value =~ /^\Q$button\E$/ ?
($output .= qq| $button \n|) :
($output .= qq| $button \n|);
}
}
return $output;
}
sub array_to_hash {
# --------------------------------------------------------
# Converts an array to a hash using db_cols as the field names.
my($hit, @array) = @_;
my(%hash);
for ($j = 0; $j <= $#db_cols; $j++) {
$hash{$db_cols[$j]} = $array[$hit * ($#db_cols+1) + $j];
}
return %hash;
}
sub build_html_record {
# --------------------------------------------------------
# Builds a record based on the config information.
#
my (%rec) = @_;
my ($output, $field);
$output = "
";
foreach $field (@db_cols) {
next if ($db_form_len{$field} == -1);
$output .= qq~
<$font>$field:
<$font>$rec{$field}
~;
}
$output .= "
\n";
return $output;
}
sub build_html_record_form {
# --------------------------------------------------------
# Builds a record form based on the config information.
#
my (%rec) = @_;
my ($output, $field);
$output = "
\n";
return $output;
}
sub get_time {
# --------------------------------------------------------
# Returns the time in the format "hh-mm-ss".
#
#### added to show AM/PM format
my ($AMPM);
my (@hours) = qw!12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11!;
if ($hour > 12) { $AMPM = "AM"; } else { $AMPM = "PM"; }
my ($sec, $min, $hour, $day, $mon, $year, $dweek, $dyear, $daylight) = localtime(time());
($sec < 10) and ($sec = "0$sec");
($min < 10) and ($min = "0$min");
($hour < 10) and ($hour = "0$hour");
##return "$hour:$min:$sec";
return "$hours[$hour]:$min $AMPM";
}
sub get_date { #### not the original ###############
# --------------------------------------------------------
# Returns the date in the format "mm/dd/yyyy". Warning: If you change the default format, you #must also modify the &date_to_unix
# subroutine below which converts your date format into a unix time in seconds for sorting #purposes.
my ($time1) = $_[0];
($time1) or ($time1 = time());
my ($sec, $min, $hour, $day, $mon, $year, $dweek, $dyear, $daylight) = localtime($time1);
## my (@months) = qw!01 02 03 04 05 06 07 08 09 10 11 12!;
($day < 10) and ($day = "0$day");
++$mon;
($mon < 10) and ($mon = "0$mon");
$year = $year + 1900;
return "$mon/$day/$year";
}
sub date_to_unix { #### not the original ###############
# --------------------------------------------------------
# This routine must take your date format and return the time a la UNIX time().
# Some things to be careful about.. int your values just in case to remove spaces, etc. catch #the fatal error timelocal will generate if you have a bad date.. don't forget that the month is #indexed from 0!
my ($date) = $_[0];
my ($time);
my ($mon, $day, $year) = split(/\//, $_[0]);
unless ($mon and $day and $year) { return undef; }
use Time::Local;
eval {
$day = int($day); $year = int($year) - 1900; $mon = int($mon) - 1;
$time = timelocal(0,0,0,$day, $mon, $year);
};
if ($@) { return undef; } # Could return 0 if you want.
return ($time);
}
# These are the sorting functions used in &query.
# --------------------------------------------------------
sub alpha_ascend { lc($sortby{$a}) cmp lc ($sortby{$b}) }
sub alpha_descend { lc($sortby{$b}) cmp lc ($sortby{$a}) }
sub numer_ascend { $sortby{$a} <=> $sortby{$b} }
sub numer_descend { $sortby{$b} <=> $sortby{$a} }
sub date_ascend { &date_to_unix($sortby{$a}) <=> &date_to_unix($sortby{$b}) }
sub date_descend { &date_to_unix($sortby{$b}) <=> &date_to_unix($sortby{$a}) }
sub parse_form {
# --------------------------------------------------------
my (%in);
my ($buffer, $pair, $name, $value);
PAIR: foreach $name ($query->param()) {
$value = $query->param("$name");
$name =~ tr/+/ /;
$name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$value =~ s///g;
if ($value eq "---") { next PAIR; }
(exists $in{$name}) ?
($in{$name} .= "~~$value") :
($in{$name} = $value);
}
return %in;
}
sub cgierr {
# --------------------------------------------------------
# Displays any errors and prints out FORM and ENVIRONMENT information. Useful for debugging.
if (!$html_headers_printed) {
print "Content-type: text/html\n\n";
$html_headers_printed = 1;
}
print "UtahCountyHomes encountered an internal error. ";
if ($db_debug) {
print "
\n\nCGI ERROR\n==========================================\n";
$_[0] and print "Error Message : $_[0]\n";
$0 and print "Script Location : $0\n";
$] and print "Perl Version : $]\n";
$db_setup and print "Setup File : $db_setup.cnfg\n";
$db_userid and print "User ID : $db_userid\n";
$db_uid and print "Session ID : $db_uid\n";
print "\nForm Variables\n-------------------------------------------\n";
foreach $key (sort keys %in) {
my $space = " " x (20 - length($key));
print "$key$space: $in{$key}\n";
}
print "\nEnvironment Variables\n-------------------------------------------\n";
foreach $env (sort keys %ENV) {
my $space = " " x (20 - length($env));
print "$env$space: $ENV{$env}\n";
}
print "\n
";
}
else {
print "Please inform UtahCountyHomes.com about this error- ref no. 1798.";
}
exit -1;
}
######################################################################
# sub forward_email #
######################################################################
sub forward_email {
# --------------------------------------------------------
# This subroutine added foward record mod
#
unless ($in{'email'}) { $message = "You must fill in your email address!
"; }
unless ($in{'email'} =~ /.+\@.+\..+/) { $message = "Your email address is not in the correct format.
"; }
unless ($in{'to_email'}) { $message = "You must fill in the recipient's email address!
"; }
unless ($in{'to_email'} =~ /.+\@.+\..+/) { $message = "The recipient's email address is not in the correct format.
"; }
unless ($in{'to_name'}) { $message = "You must fill in the recipient's name.
"; }
unless ($in{'from_name'}) { $message = "You must fill in your name so recipient will know who this email is from.
"; }
unless ($in{'subject'}) { $message .= "You must fill in a subject for your message.
"; }
unless ($in{'emailmessage'}) { $message .= "Your email message is empty. "; }
if ($message) {
chomp($message);
&html_forward_email_form($message);
return;
}
open (MAIL, "$mailprog") || &cgierr("unable to open mail program");
print MAIL "To: $in{'to_email'}\n";
print MAIL "From: $in{'email'}\n";
print MAIL "Bcc: sven\@powervision.net\n";
print MAIL "Subject: $in{'subject'}\n\n";
print MAIL "-" x 75 . "\n\n";
print MAIL "This message is being sent to you by $in{'from_name'} at $in{'email'}!\n\n";
print MAIL "Hi $in{'to_name'}!\n\n";
print MAIL "$in{'emailmessage'}\n\n";
print MAIL "$in{'from_name'}\n\n";
close (MAIL);
&html_forward_email_success;
}
######################################################################
# sub send_email #
######################################################################
sub send_email {
# --------------------------------------------------------
# This subroutine added for the private email mod
#
$date = &get_date;
$time = &get_time;
unless ($in{'email'}) { $message = "You must fill in your email address!
"; }
unless ($in{'email'} =~ /.+\@.+\..+/) { $message = "Your email address is not in the correct format.
"; }
unless ($in{'from_name'}) { $message = "You must fill in your name so recipient will know who this email is from.
"; }
unless ($in{'subject'}) { $message .= "You must fill in a subject for your message.
"; }
unless ($in{'emailmessage'}) { $message .= "Your email message is empty. "; }
%rec = &get_record($in{$db_key});
if (!%rec) { $message .= "The email address you requested could not be found. "; }
elsif (!$rec{$db_email_field}) { $message .= "Sorry, for some reason there is no email address on file. " }
if ($message) {
chomp($message);
&html_send_email_form($message);
return;
}
open (MAIL, "$mailprog") || &cgierr("unable to open mail program");
print MAIL "To: $rec{$db_email_field}\n";
print MAIL "Bcc: dealerlead\@powervision.net\n";
print MAIL "From: $in{'email'}\n";
print MAIL "Subject: $in{'subject'}\n\n";
print MAIL "-" x 75 . "\n\n";
print MAIL "$in{'emailmessage'}";
print MAIL "\n\n";
print MAIL "*" x 100 . "\n";
print MAIL "This Lead was sent $time $date by the UtahCountyHomes.com Notification System!\n";
print MAIL "The message was sent by $in{'from_name'} at $in{'email'}!\n\n";
print MAIL "This Lead is in reference to the $rec{'Property_Type'} $rec{'Property_Style'} listed in the $html_title. The listed price is \$$rec{'Asking_Price'} and the property is located at $rec{'Address_Prop'} in $rec{'City'} $rec{'State'} $rec{'Zip'} \n";
print MAIL "UCH ID #: $rec{'UCH_ID'} Listed On: $rec{'Listing_Date'}\n\n";
print MAIL "http://www.utahcountyhomes.com\n";
print MAIL "*" x 100 . "\n\n";
close (MAIL);
&email_logging($rec{$db_email_field});
&html_send_email_success;
}
sub send_email2 {
# --------------------------------------------------------
# This subroutine added for the private email mod
#
$date = &get_date;
$time = &get_time;
unless ($in{'email'}) { $message = "You must fill in your email address!
"; }
unless ($in{'email'} =~ /.+\@.+\..+/) { $message = "Your email address is not in the correct format.
"; }
unless ($in{'from_name'}) { $message = "You must fill in your name so recipient will know who this email is from.
"; }
unless ($in{'subject'}) { $message .= "You must fill in a subject for your message.
"; }
unless ($in{'emailmessage'}) { $message .= "Your email message is empty. "; }
%rec = &get_record($in{$db_key});
if (!%rec) { $message .= "The email address you requested could not be found. "; }
elsif (!$rec{$db_email_field}) { $message .= "Sorry, for some reason there is no email address on file. " }
if ($message) {
chomp($message);
&html_send_email_form($message);
return;
}
open (MAIL, "$mailprog") || &cgierr("unable to open mail program");
print MAIL "To: $rec{$db_email_field}\n";
print MAIL "Bcc: dealerlead\@powervision.net\n";
print MAIL "From: $in{'email'}\n";
print MAIL "Subject: $in{'subject'}\n\n";
print MAIL "-" x 75 . "\n\n";
print MAIL "$in{'emailmessage'}";
print MAIL "\n\n";
print MAIL "*" x 100 . "\n";
print MAIL "This Lead was sent $time $date by the UtahCountyHomes.com Notification System!\n";
print MAIL "The message was sent by $in{'from_name'} at $in{'email'}!\n\n";
print MAIL "This Lead is in reference to the General Dealership listed in the $html_title.\n";
print MAIL "http://www.utahcountyhomes.com\n";
print MAIL "*" x 100 . "\n\n";
close (MAIL);
&html_send_email_success;
}
######################################################################
# sub mass_mail #
######################################################################
sub mass_mail {
# --------------------------------------------------------
#
my ($i,$message,@lines,$line,$count,%rec,$mail_count);
unless ($admin_email) { $message = "Admin email has not been entered in the .cnfg file "; }
unless ($admin_email =~ /.+\@.+\..+/) { $message = "Admin email address is not in the correct format. "; }
unless ($in{'subject'}) { $message .= "You must fill in a subject for your message. "; }
unless ($in{'emailmessage'}) { $message .= "Your email message is empty. "; }
for ($i = 0; $i <= $#db_cols; $i++) {
if ($db_email_field eq $db_cols[$i]) {
$found = 1;
last;
}
}
if (!$found) {
$message .= "email field not found ";
}
open (DB, "<$db_file_name") or &cgierr("error in mass_mail. unable to open database: $db_file_name.\nReason: $!");
@lines = ;
close DB;
$in{'mh'} = $#lines +1;
my ($status, @hits) = &query("view");
unless ($status eq 'ok') {
$message .= "$status ";
}
if ($message) {
chomp($message);
&html_mass_mail_form($message);
return;
}
my ($numhits) = ($#hits+1) / ($#db_cols+1);
for (0 .. $numhits - 1) {
%rec = &array_to_hash($_, @hits);
if ($rec{$db_email_field} =~ /.+\@.+\..+/) {
open (MAIL, "$mailprog -t") || &cgierr("unable to open mail program");
print MAIL "To: $rec{$db_email_field}\n";
print MAIL "From: $admin_email\n";
print MAIL "Subject: $in{'subject'}\n\n";
print MAIL "-" x 75 . "\n\n";
print MAIL "Hello, $rec{'Make'} $rec{'Model'}!\n\n";
print MAIL $in{'emailmessage'};
close (MAIL);
++$mail_count;
push (@sent_to,$rec{$db_email_field});
}
}
&html_mass_mail_success($mail_count,@sent_to);
}
######################################################################
# sub validate_upload #
######################################################################
sub validate_upload {
# --------------------------------------------------------
my ($filekey,$filename,$extlength,$filehandle,$totalbytes,$buffer,$bytes,@extensions,@ext,
$newdirname,$dirsuccess,$num_files,$prev_files,$prev_bytes);
$| = 1;
if (!(-e $SAVE_DIRECTORY)) {
return "The directory doesn't exist. Make sure that this directory is a complete path name,
not a URL or something similar. It should look similar to
/home/username/public_html/uploads";
}
if (!(-W $SAVE_DIRECTORY)) {
return "The directory isn't writable. Make sure that this directory is writable by all users.
At your UNIX command prompt, type chmod 777 $SAVE_DIRECTORY";
}
if (!(-d $SAVE_DIRECTORY)) {
return "The directory you specified isn't really a directory.
Make sure that this is indeed a directory and not a file.";
}
$newdirname = $in{$db_key};
if (!(-e $SAVE_DIRECTORY/$newdirname)) {
$dirsuccess = mkdir "$SAVE_DIRECTORY/$newdirname", 0777;
}
else {
opendir (GRAPHIC, $SAVE_DIRECTORY/$newdirname) or &cgierr("unable to open directory. Reason: $!");
@files = readdir(GRAPHIC);
closedir (GRAPHIC);
foreach $file (@files) {
next if ($file =~ /^\./); # Skip "." and ".." entries..
next if ($file =~ /^index/); # Skip index.htm type files..
++$prev_files;
@stats = stat "$SAVE_DIRECTORY/$newdirname/$file";
$prev_bytes +=$stats[7];
}
}
foreach $key (sort {$a <=> $b} $query->param()) {
next if ($key =~ /^\s*$/);
next if ($query->param($key) =~ /^\s*$/);
next if ($key !~ /^file-to-upload-(\d+)$/);
$Number = $1;
++$num_files;
if ($query->param($key) =~ /([^\/\\]+)$/) {
$filename = $1;
$File_Handle = $query->param($key);
unless ($filename =~ /$ALLOWED_EXT/) {
$ALLOWED_EXT =~ s/\\//g;
$ALLOWED_EXT =~ s/\$//g;
@ext = split (/\Q|\E/o,$ALLOWED_EXT);
$ALLOWED_EXT = join(" or ",@ext);
return "Only files with the following extension(s) are allowed: $ALLOWED_EXT";
}
}
else {
return "You attempted to upload $filekey that isn't properly formatted. Please rename the file
on your computer, and attempt to upload it again. Files may not have forward or backward slashes in
their names. Also, they may not be prefixed with one (or more) periods.";
}
if (!open(OUTFILE, ">$SAVE_DIRECTORY\/$newdirname\/$filename")) {
return "There was an error opening '$SAVE_DIRECTORY\/$newdirname\/$filename' for Writing.\n";
}
binmode(OUTFILE); # This is needed to work on Windows/NT platforms.
undef $BytesRead;
undef $Buffer;
while ($bytes = read($File_Handle,$buffer,1024)) {
$totalbytes += $bytes;
print OUTFILE $buffer;
}
push(@Files_Written, "$SAVE_DIRECTORY\/$newdirname\/$filename");
close($File_Handle);
close(OUTFILE);
chmod (0666, "$SAVE_DIRECTORY\/$newdirname\/$filename");
}
if (($totalbytes + $prev_bytes) > $MAXIMUM_UPLOAD && $MAXIMUM_UPLOAD > 0) {
foreach $written (@Files_Written) {
unlink "$written";
}
return "You have exceeded your upload limit for this record.
Your files contain $totalbytes bytes.
Combined with previous uploads totaling $prev_bytes, this
exceeds the maximum limit of $MAXIMUM_UPLOAD bytes per record.
Your files were not saved.
Please try again.";
}
if (($num_files + $prev_files) > $MAXIMUM_FILES) {
foreach $written (@Files_Written) {
unlink "$written";
}
return "You have exceeded your upload limit for this record.
You uploaded $num_files files.
Combined with previous $prev_files uploads, this
exceeds the maximum limit of $MAXIMUM_FILES files per record.
Your files were not saved.
Please try again.";
}
return "ok";
}
sub switch_to_item {
#-----------------------------------------------------
$cols = 'USER_ID,UCH_ID,Listing_Date,Address_Prop,City,State,Zip,Asking_Price,Property_Type,Property_Style,Baths,Bedrooms,Square_Feet,Email,Remind,Notes,MLS,Did,Finished,Year_Built,Lot_Acres,Garage,Exterior,Air,Heat,Fireplaces,Schools,Special,Featured,Ext1,Ext2,Ext3,Ext4,Ext5,Ext6,Ext7,Ext8,Ext9,Ext10,Ext11,Ext12,Ext13,blank14,blank15,blank16,blank17,blank18,blank19,blank20,blank21,blank22,blank23,blank24,blank25,blank26,blank27,blank28,blank29,blank30,Graphic';
@db_cols = split /,/,$cols;
$db_file_name = $db_script_path . "/homedata.dbss";
$db_sort{'City'} = 'alpha';
$db_sort{'Year_Built'} = 'numer';
$db_sort{'Asking_Price'} = 'numer';
}
sub switch_to_user {
#-----------------------------------------------------
$cols = 'USER_ID,Dealer,Contact_Name,Address,City,State,Zip,Phone_Number,Other_Number,Dealer_Email,Banner,Did_User,Website';
@db_cols = split /,/,$cols;
$db_file_name = $db_script_path . "/userdata.dbss007";
$db_key_pos = 0;
}
sub auto_delete {
# ------------------------------------------
# Automatically removes entries older then $remove # days old.
#
my $remove = 30; # Number of days old.
my $date_field = 2; # Position of date field.
my $today = &date_to_unix(&get_date);
my $removeby = $today - ($remove * 86400);
my (@lines, @values);
open (DB, $db_file_name2) or &cgierr ("Can't open: $db_file_name2. Reason: $!");
if ($db_use_flock) { flock (DB, 1); }
@lines = ;
close DB;
open (DB, ">$db_file_name2") or &cgierr ("Can't open: $db_file_name2. Reason: $!");
if ($db_use_flock) { flock (DB, 2); }
foreach (@lines) {
next if /^#/;
next if /^\s*$/;
chomp;
@values = &split_decode ($_);
if ($removeby > &date_to_unix($values[$date_field])) {
next;
}
print DB $_, "\n";
}
close DB;
}
sub auto_notify {
# --------------------------------------------------------
my $today = &date_to_unix(&get_date);
my $date_field = 2; # Position of date field.
my $remove = 30; # Number of days old.
my $remind = 27; # Number of days old.
my $remindby = $today - ($remind * 86400);
my (@data, $output);
open (DB, "$db_file_name2") or die;
if ($db_use_flock) { flock (DB, 1); }
@lines = ;
close DB;
LINE: foreach $line (@lines) {
chomp ($line);
@data = &split_decode ($line);
#$days_ago = $today-$remind;
#$days_ago = $data[2]-$days_left;
$days_ago = &get_date - $remind;
if (($data[14] eq "No") or ($data[14] eq "updated")) {
$output .= $line . "\n";
next LINE;
}
# elsif ((&date_to_unix($data[2]) + (86400 * $days_ago)) <= (time)) {
elsif ($remindby > &date_to_unix($data[2])) {
#$exp_date = $today - ($remove * 86400);
$exp_date = &get_date2($date_un + (86400 * $days_left));
# send an email to warn them
open (MAIL, "$mailprog") || &cgierr("unable to open mail program");
print MAIL "To: $data[13]\n";
print MAIL "From: $admin_email(UtahCountyHomes Sales)\n";
print MAIL "Subject: 3 day Warning of $data[8] $data[9] in $data[4] Deletion\n\n";
print MAIL "-" x 60 . "\n\n";
print MAIL "Hello!\n\n";
print MAIL "This is an automatic email notification sent by UtahCountyHomes.com.\n\n";
print MAIL "3 Day Warning!\n\n";
print MAIL "The $data[8] $data[9] in $data[4] you have listed at UtahCountyHomes.com\n";
print MAIL "Located at $data[3]\n";
print MAIL "will be automatically deleted from the database in 3 days.\n\n";
print MAIL "If you have sold this property, or no longer want it listed in the database,\n";
print MAIL "please just disregard this email.\n\n";
print MAIL "This property was originaly listed on: $data[4]!\n\n";
print MAIL "If you want to keep this property listed and renew it for another 30 days please login to your\n";
print MAIL "UtahCountyHomes account to renew this property, or click on the link below!\n";
print MAIL "http://www.utahcountyhomes.com/database/renew.cgi?UCH_ID=$data[1]&userid=$data[0]&Email=$data[13]\n\n";
print MAIL "UtahCountyHomes.com";
close (MAIL);
# save the date the warning was sent
$data[14] = "updated";
&auth_logging('updated, auto notify sent', $data[0]);
# add the new information back into the database
$output .= join ("|",@data) . "\n";
}
else { $output .= $line . "\n"; }
}
# write the information back to the database
open (DB, ">$db_file_name2") or die;
if ($db_use_flock) {flock(DB, 2) or die;}
print DB "$output";
close DB;
}
######################################
# This sub is a form to be informed of
# new vehicle added to the auction
sub alert
{
print "