#!/usr/bin/perl -Tw

use CGI qw/:standard/;
use Digest::MD5 qw(md5_hex);
use LWP::UserAgent;
#use Tie::File;
use Time::localtime;


require "/home/ericll75/www/common/dbcommon.sub";
require "/home/ericll75/www/common/eltaint.sub";

BEGIN {
  use CGI::Carp qw(carpout);
  open(LOG, ">>/home/ericll75/www/steepturns.com/badcams/members/index.log") or
       die("Unable to open index.log: $!\n");
  carpout(LOG);
}
use CGI::Carp qw(fatalsToBrowser);
$CGI::DISABLE_UPLOADS = 1;                    # Disable uploads
$CGI::POST_MAX        = 1024;           # limit posts to 1K max


my $UserName = $ENV{'REMOTE_USER'};
local $LastAction;

my $WhatChange = param('change');
   if ($WhatChange =~ /^(sitename|sitedesc|siteurl|camurl|siterating|username|realname|useremail|userbday|sexorient|location|userpw|activestatus)$/) {
      &ChangePrompt;
   }
   elsif ($WhatChange =~ /^(postsitename|postsitedesc|postsiteurl|postcamurl|postsiterating|postusername|postrealname|postuseremail|postuserbday|postsexorient|postlocation|postuserpw|postactivestatus)$/) {
      &ChangePost;
   }
   else {
      $WhatChange = '';
   }



&DispUserInfo;

sub DispUserInfo {
   my @CurrUserInfo;
   @CurrUserInfo = &GetAllUserInfo;

   my $FileErr = substr(param('FileErr'),0,80);
      if ($FileErr) {
         if ($FileErr =~ /[^A-Za-z0-9\s\-\'\;\:\!\.\ \(\)]/) { $FileErr = ''; }
      }
      else { $FileErr = &escapify($FileErr); }

   my $BdayMonth = int(substr($CurrUserInfo[18],0,2));
   my $BdayDate  = int(substr($CurrUserInfo[18],2,2));
   my $BdayYear  = substr($CurrUserInfo[18],4,4);
   my $LastCamTime;
   my $LastLogin;
   my $LastUpdated;
   my $SignDate;
   if ($CurrUserInfo[11] > $CurrUserInfo[10]) {   #They are not online now.
      $LastCamTime  = sprintf("%02d",localtime($CurrUserInfo[10])->mon()+1) . "-" . sprintf("%02d",localtime($CurrUserInfo[10])->mday()) . "-" . sprintf("%04d",localtime($CurrUserInfo[10])->year()+1900) . " at ";
      $LastCamTime .= sprintf("%02d",localtime($CurrUserInfo[10])->hour()) . ":" . sprintf("%02d",localtime($CurrUserInfo[10])->min());
   }
   else { $LastCamTime = "Currently online"; }
   if ($CurrUserInfo[21]) { $LastLogin = int(substr($CurrUserInfo[21],4,2))."-".int(substr($CurrUserInfo[21],6,2))."-".substr($CurrUserInfo[21],0,4); }
   if ($CurrUserInfo[22]) { $LastUpdated = int(substr($CurrUserInfo[22],4,2))."-".int(substr($CurrUserInfo[22],6,2))."-".substr($CurrUserInfo[22],0,4); }
   if ($CurrUserInfo[23]) { $SignDate = int(substr($CurrUserInfo[23],4,2))."-".int(substr($CurrUserInfo[23],6,2))."-".substr($CurrUserInfo[23],0,4); }

   if ($CurrUserInfo[1] eq 'IN') { $ActiveStatus = "Active"; }
   elsif ($CurrUserInfo[1] eq 'nu') { $ActiveStatus = "New User, awaiting review"; }
   elsif ($CurrUserInfo[1] eq 'ci') { $ActiveStatus = "Cam Info changed, awaiting review"; }
   elsif ($CurrUserInfo[1] eq 'py') { $ActiveStatus = "Rejected - your cam MUST be free of charge to be on this portal."; }
   elsif ($CurrUserInfo[1] eq 'wp') { $ActiveStatus = "Rejected - your cam url MUST be the actual cam .gif or .jpg!.  This is the SAME image that your site automatically refreshes when you are online."; }
   elsif ($CurrUserInfo[1] eq 'rj') { $ActiveStatus = "Rejected - please make sure all your info is correct and legitimate."; }

   &DispHeader;
   print qq`
   <font face="Arial, Helvetica, sans-serif" color=yellow size=4><i>$FileErr</i></font><br>
   <table border="0" width="90%" bgColor="#666666" align="center">
     <tr>
     <td align="center" valign="top" width="50%"> 
       <p><font face="Arial, Helvetica, sans-serif"><b><font color="#FFFFFF">Current 
        Cam Image:</font></b><font color="#FFFFFF"><br>
        <img src="$CurrUserInfo[5]" align="center" border="2"> 
        <br>
        Last time on cam: $LastCamTime<br><br>
        Last login to BadCams: $LastLogin<br>
        Last update to profile: $LastUpdated<br>
        Cam Profile Created: $SignDate
        </font></font></p>
     </td>
     <td valign=top>
       <table border="1" bgColor="#FFFFFF" align="right" cellpadding="10" cellspacing="0" width="340">
         <tr><td class=eatab1 width="150"><a class=eatab1 href="?change=username">UserName:</a></td><td class=eatab2 width="150">$UserName ($CurrUserInfo[16])</td></tr>
         <tr>
           <td class=eatab1><a class=eatab1 href="?change=realname">Real Name:</a></td>
           <td class=eatab2>$CurrUserInfo[14] $CurrUserInfo[15]</td></tr>
         <tr>
           <td class=eatab1><a class=eatab1 href="?change=useremail">Email Address:</a></td>
           <td class=eatab2>$CurrUserInfo[13]</td></tr>
         <tr>
           <td class=eatab1><a class=eatab1 href="?change=userbday">Birth Date:</a></td>
           <td class=eatab2>$BdayMonth-$BdayDate-$BdayYear</td></tr>
         <tr>
           <td class=eatab1><a class=eatab1 href="?change=sexorient">Sexual Orientation:</a></td>
           <td class=eatab2>$CurrUserInfo[17]</td></tr>
         <tr>
           <td class=eatab1><a class=eatab1 href="?change=location">Location:</a></td>
           <td class=eatab2>$CurrUserInfo[19]</td></tr>
         <tr>
           <td class=eatab1><a class=eatab1 href="?change=userpw">Password:</a></td>
           <td class=eatab2><i>(not shown)</i></td>
         </tr>
         <tr>
           <td class=eatab1><a class=eatab1 href="?change=activestatus">Status:</a></td>
           <td class=eatab2><b>$ActiveStatus</b></td>
         </tr>
       </table>
     </td></tr>
     <tr><td colspan=2>
       <table border="1" bgcolor="#FFFFFF" align="center" cellpadding="5" cellspacing="0" width="80%">
         <tr> 
           <td class=eatab1 width="130"><font color=blue>Site ID:</font></td>
           <td class=eatab2 width="200">$CurrUserInfo[0]</td>
         </tr>
         <tr> 
           <td class=eatab1><a class=eatab1 href="?change=sitename">Site/Webcam Name:</a></td>
           <td class=eatab2>$CurrUserInfo[2]</td>
         </tr>
         <tr> 
           <td class=eatab1><a class=eatab1 href="?change=sitedesc">Site/Webcam Description:</a></td>
           <td class=eatab2>$CurrUserInfo[3]</td>
         </tr>
         <tr> 
           <td class=eatab1><a class=eatab1 href="?change=siteurl">Site URL<br> (main page):</a></td>
           <td class=eatab2>$CurrUserInfo[4]</td>
         </tr>
         <tr> 
           <td class=eatab1><a class=eatab1 href="?change=camurl">Cam URL:</a></td>
           <td class=eatab2>$CurrUserInfo[5]</td>
         </tr>
         <tr> 
           <td class=eatab1><a class=eatab1 href="?change=siterating">Site 
             Rating:</a></td>
           <td class=eatab2>$CurrUserInfo[6]</td>
         </tr>
       </table>
     </td></tr>
   </table>`;
   &DispFooter;
}

#-------------------------------- Displays header up to the table.
sub DispHeader {
   print "Content-type: text/html\n\n";
   print qq`
   <html>
   <head>
   <title>BadCams User Data</title>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   <style type="text/css">
   <!--
     .eatab1 {  font-family: Arial, Helvetica, sans-serif; font-weight: bold; background-position: right; color: #000000}
     A.eatab1:link    { color: #0000FF }    /* unvisited links */
     A.eatab1:visited { color: #0000FF }    /* visited links   */
     A.eatab1:hover   { color: #FF0000  }    /* user hovers     */
     A.eatab1:active  { color: #0000FF }    /* active links    */
     .eatab2 {  font-family: Arial, Helvetica, sans-serif; color: #000000}
   -->
   </style>
   </head>
   <body bgcolor="#666666" text="#999999" link="#FFFFFF" vlink="#FFFFFF" alink="#999999">
   <div align="center">
   <p><img src="http://www.steepturns.com/badcams/gfx/badtitle1.gif" width=500 height=44></p>
   <p><font color="#FFFFFF" face="Arial, Helvetica, sans-serif" size="5"><b><font size="6">Edit 
     your account</font></b></font></p>
   <p><font color="#FFFFFF" face="Arial, Helvetica, sans-serif" size="5"><b><a href="http://www.badcams.com"><font size="2">[ 
     Return to Portal ]</font></a><br>
     </b></font><br></p>\n`;
}

#-------------------------- Displays footer after the table.
sub DispFooter {
   print qq`<br><br><br><br>
   <font size=2>[ <a href="mailto:badcams\@steepturns.com?subject=Questions/Comments">Questions/Comments</a> ]</FONT>
   <P><font color=#0000ff size=1><A href="http://www.steepturns.com/">©2001 Steep 
   Turns(SM) Web Design</a> </font></p><a href="http://www.steepturns.com/"><img 
   alt="Steep Turns(SM) Web Design" border=0 height=45 src="http://www.steepturns.com/SALMiniTrans.gif" width=50></a></div>
   </body>
   </html>`;
   exit;
}

sub GetAllUserInfo {
   my @CurrUserInfo;
   $SQL = qq`SELECT SiteID,ActiveStatus,SiteName,SiteDesc,SiteURL,CamURL,SiteRating,VisitorsIn,VisitorsOut,LastCamMD5,LastCamTime,LastOffTime,
             UserName,UserEmail,FirstName,LastName,UserGender,SexOrient,UserBday,UserLocation,LastAction,LastLogin,LastUpdated,SignDate FROM CamUsers1 WHERE UserName='$UserName'`;
   &CreateDBConnection;
      &DoSQL;
      @CurrUserInfo = $sth->fetchrow_array;
   $dbh->disconnect;
   return @CurrUserInfo;
}

#-----------------------
sub ChangePrompt {
   my @CurrUserInfo;
   @CurrUserInfo = &GetAllUserInfo;
   &DispHeader;
   print qq`     <table width="80%" border=1 bgColor=white cellpadding=20><tr><td class=eatab2>
       <form name=chprompt method=post action="http://www.steepturns.com/badcams/members/index.cgi">
       <input type=hidden name=change value="post$WhatChange">`;
   if ($WhatChange eq 'sitename') {
      print qq`
       <b>Enter your new site/webcam name:</b><br><br>
       <input type="text" name="SiteName" value="`.&htmlify($CurrUserInfo[2]).qq`" maxlength="80" size="60">`;
   }
   elsif ($WhatChange eq 'sitedesc') {
      print qq`
       <b>Enter your new site/webcam description:</b><br><br>
       <input type="text" name="SiteDesc" value="`.&htmlify($CurrUserInfo[3]).qq`" size="60" maxlength="200"><br>
       <font size=2>(This field is optional and may be left blank)</font>`;
   }
   elsif ($WhatChange eq 'siteurl') {
      print qq`
       <b>Enter your new website URL:</b><br><br>
       <input type="text" name="SiteURL" value="`.&htmlify($CurrUserInfo[4]).qq`" size="60" maxlength="200">`;
   }
   elsif ($WhatChange eq 'camurl') {
      print qq`
       <b>Enter your new webcam URL (this must be the direct .jpg URL):</b><br><br>
       <input type="text" name="CamURL" value="`.&htmlify($CurrUserInfo[5]).qq`" size="60" maxlength="200">`;
   }
   elsif ($WhatChange eq 'siterating') {
      print qq`
       <b>Enter your new site rating:</b><br><br>
       <select name="SiteRating">
         <option value="$CurrUserInfo[6]" selected>$CurrUserInfo[6]</option>
         <option value="">--</option>
         <option value="PG">PG</option>
         <option value="R">R</option>
         <option value="X">X</option>
       </select>`;
   }
   elsif ($WhatChange eq 'username') {
      print qq`
       <b>Enter your new username:</b><br><br>
       <input type="text" name="UserName" value="`.&htmlify($CurrUserInfo[12]).qq`" size="20" maxlength="20"><br><br><br>
       <b>You must also enter your password:</b><br>
       <input type="password" name="UserPW" value="" size="20" maxlength="20">`;
   }
   elsif ($WhatChange eq 'realname') {
      print qq`
       <b>Enter your real name:</b><br><br>
       <table border=0><tr>
         <td class=eatab2 align="right">First Name</td><td><input type="text" name="FirstName" value="$CurrUserInfo[14]" width=30 maxlength=20></td>
       </tr><tr> 
         <td class=eatab2 align="right">Last Name</td><td><input type="text" name="LastName" value="$CurrUserInfo[15]" width=30 maxlength=30></td>
       </tr></table>`;
   }
   elsif ($WhatChange eq 'useremail') {
      print qq`
       <b>Enter your new email address:</b><br><br>
       <input type="text" name="UserEmail" value="`.&htmlify($CurrUserInfo[13]).qq`" maxlength="60" size="40">`;
   }
   elsif ($WhatChange eq 'userbday') {
      $BdayMonth = substr($CurrUserInfo[18],0,2);
      $BdayDate  = substr($CurrUserInfo[18],2,2);
      $BdayYear  = substr($CurrUserInfo[18],4,4);
      print qq`
       <b>Enter your birthdate:</b><br><br>
      <select name="BdayMonth">
        <option value="$BdayMonth" selected>$BdayMonth</option>
        <option value="">--</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option>
      </select>
      / 
      <select name="BdayDate">
        <option value="$BdayDate" selected>$BdayDate</option>
        <option value="">--</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option>
        <option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option>
        <option value="21">21</option><option value="22">22</option><option value="23">23</option><option value="24">24</option><option value="25">25</option><option value="26">26</option><option value="27">27</option><option value="28">28</option><option value="29">29</option><option value="30">30</option><option value="31">31</option>
      </select>
      / 
      <input type="text" name="BdayYear" value="$BdayYear" width=6 maxlength=4>`;
   }
   elsif ($WhatChange eq 'sexorient') {
      print qq`
       <b>Enter your sexual orientation:</b><br><br>
       <select name="SexOrient" size="1" value="">
         <option value="$CurrUserInfo[17]" selected>$CurrUserInfo[17]
         <option value="">----------------
         <option value="Not Specified">Not Specified 
         <option value="Straight">Straight 
         <option value="Straight but Curious">Straight but Curious 
         <option value="Gay/Lesbian">Gay/Lesbian
         <option value="Bisexual">Bisexual 
         <option value="Undecided">Undecided 
         <option value="Just Plain Horny">Just Plain Horny 
       </select>`;
   }
   elsif ($WhatChange eq 'location') {
      print qq`
       <b>Enter your new state/province (if living the the U.S. or Canada), otherwise enter your country:</b><br><br>
       <table border=0><tr><td align=right class=eatab2>State/Province:</td>
       <td>
         <select name="UserState" size="5" value="">
           <option value="$CurrUserInfo[19]" selected>$CurrUserInfo[19]<option value="">---------------
           <option value="OU">Outside US & Canada
           <option value="Alabama">Alabama<option value="Alaska">Alaska<option value="Arizona">Arizona<option value="Arkansas">Arkansas<option value="California">California<option value="Colorado">Colorado<option value="Connecticut">Connecticut<option value="Deleware">Delaware<option value="Dist. of Columbia">Dist. of Columbia<option value="Florida">Florida<option value="Georgia">Georgia<option value="Hawaii">Hawaii<option value="Idaho">Idaho<option value="Illinois">Illinois<option value="Indiana">Indiana<option value="Iowa">Iowa<option value="Kansas">Kansas
           <option value="Kentucky">Kentucky<option value="Louisiana">Louisiana<option value="Maine">Maine<option value="Maryland">Maryland<option value="Massachusetts">Massachusetts<option value="Michigan">Michigan<option value="Minnesota">Minnesota<option value="Mississippi">Mississippi<option value="Missouri">Missouri<option value="Montana">Montana<option value="Nebraska">Nebraska<option value="Nevada">Nevada<option value="New Hampshire">New Hampshire<option value="New Jersey">New Jersey<option value="New Mexico">New Mexico<option value="New York">New York
           <option value="North Carolina">North Carolina<option value="North Dakota">North Dakota<option value="Ohio">Ohio<option value="Oklahoma">Oklahoma<option value="Oregon">Oregon<option value="Pennsylvania">Pennsylvania<option value="Puerto Rico">Puerto Rico<option value="Rhode Island">Rhode Island<option value="South Carolina">South Carolina<option value="South Dakota">South Dakota<option value="Tennessee">Tennessee<option value="Texas">Texas<option value="Utah">Utah<option value="Vermont">Vermont<option value="Virginia">Virginia<option value="Washington">Washington
           <option value="West Virginia">West Virginia<option value="Wisconsin">Wisconsin<option value="Wyoming">Wyoming<option value="Virgin Islands">Virgin Islands<option value="British Columbia">British Columbia<option value="Alberta">Alberta<option value="Ontario">Ontario<option value="Quebec">Quebec<option value="New Brunswick">New Brunswick<option value="Nova Scotia">Nova Scotia<option value="Prince Edward Island">Prince Edward Island<option value="Newfoundland">Newfoundland<option value="Yukon Territory">Yukon Territory<option value="Northwest Territories">Northwest Territories<option value="Other">Other
         </select>
       </td></tr><tr><td align=right class=eatab2>Country:<br>(if outside U.S. or Canada)</td>
       <td><input type="text" name="UserCountry" value="" maxlength="22" size="30">
       </td></tr></table>`;
   }
   elsif ($WhatChange eq 'userpw') {
      print qq`
       <b>Enter your new password:</b><br><br>
       <table border=0><tr>
         <td class=eatab2 align="right" valign=top>Verify OLD Password</td>
         <td valign=top><input type="password" name="UserPOld" value="" size="20" maxlength="20"><br><br></td>
       </tr><tr>
         <td class=eatab2 align="right">NEW Password</td>
         <td><input type="password" name="UserP1" value="" size="20" maxlength="20"></td>
       </tr><tr>
         <td class=eatab2 align="right">Verify new Password</td>
         <td><input type="password" name="UserP2" value="" size="20" maxlength="20"></td>
       </tr></table>`;
   }
   print qq`<br><br><br>
       <table border=0><tr><td><input type=submit value="Make Change"></td>
         <td width=50> </td>
         <td><input type=button value="Do Nothing" onClick="javascript:document.href='http://www.steepturns.com/badcams/members/index.cgi'"></td>
       </tr></table>
     </td></tr></table>`;
   &DispFooter;
}

#----------------------------------
sub ChangePost {
   if ($WhatChange eq 'postsitename') {
      my $SiteName = substr(param('SiteName'),0,80);
         $SiteName = &elokphrase($SiteName);
      if (length($SiteName) < 4 || length($SiteName) > 80) {
         &NewErr('You did not enter your site/webcam name!  Nothing Done!'); }
      elsif (&NeedsReview) {
         &WriteUpdate('SiteName',$SiteName,'string');
         &NewErr('Your site/webcam name has been successfully changed.'); }
   }
   elsif ($WhatChange eq 'postsitedesc') {
      my $SiteDesc    = substr(param('SiteDesc'),0,200);
         $SiteDesc    = &elokphrase($SiteDesc);
      if (length($SiteDesc) > 200) {
         &NewErr('Illegal site/webcam description!  Nothing Done!'); }
      elsif (&NeedsReview) {
         &WriteUpdate('SiteDesc',$SiteDesc,'string');
         &NewErr('Your site description has been successfully changed.'); }
   }
   elsif ($WhatChange eq 'postsiteurl') {
      my $SiteURL = &escapify(param('SiteURL'));
      if (!&ValidURL($SiteURL) || length($SiteURL) < 7 || length($SiteURL) > 200) {
         &NewErr('Invalid Website URL!  Nothing done.'); }
      elsif (!&CheckURLExists($SiteURL)) {
         &NewErr('That website URL does not exist!  Nothing done.'); }
      elsif (&NeedsReview) {
         &WriteUpdate('SiteURL',$SiteURL,'string');
         &NewErr('Your site URL has been successfully changed.'); }
   }
   elsif ($WhatChange eq 'postcamurl') {
      my $CamURL = &escapify(param('CamURL'));
      if (!&ValidURL($CamURL) || length($CamURL) < 7 || length($CamURL) > 200) {
         &NewErr('Invalid webcam URL!  Nothing done.'); }
      elsif (&NeedsReview) {
         &WriteUpdate('CamURL',$CamURL,'string');
         &NewErr('Your webcam URL has been successfully changed.'); }
   }
   elsif ($WhatChange eq 'postsiterating') {
      my $SiteRating  = &escapify(param('SiteRating'));
      if ($SiteRating !~ /^PG|R|X$/) {
         &NewErr('You must select your site\'s rating!  Nothing done.'); }
      elsif (&NeedsReview) {
         &WriteUpdate('SiteRating',$SiteRating,'string');
         &NewErr('Your site\'s rating has been successfully changed.'); }
   }
   elsif ($WhatChange eq 'postusername') {
      my $NewUserName = param('UserName');
      my $UserPW      = param('UserPW');
      if (length($NewUserName) < 4 || length($NewUserName) > 20) {
         &NewErr('Your username must be 4-20 characters long!  Nothing done.'); }
      elsif ($NewUserName =~ /[^A-Za-z0-9]/) {
         &NewErr('That username contains invalid characters!  Nothing done.'); }
      elsif ($UserPW =~ /[^A-Za-z0-9]/ || length($UserPW) < 6 || length($UserPW) > 20) {
         &NewErr('Incorrect password!  Your username has NOT been changed.'); }
      else {
         my $OldHashedPW = crypt($UserPW,$UserName);
         my $NewHashedPW = crypt($UserPW,$NewUserName);
         my $UserChangedFlag = 0;
         my @AllUsers;
         open (PWDAT, "/home/ericll75/www/steepturns.com/badcams/Data/.htpasswd") or croak("Unable to open user data file! $!\n");
         flock(PWDAT,1) || croak("Unable to flock user data file!");
            @AllUsers = <PWDAT>;
         close (PWDAT);
         foreach (@AllUsers) {
            if ($_ =~ /^$NewUserName:/) {
               &NewErr('That username is already being used; please choose another name and try again.');
            }
         }
         foreach (@AllUsers) {
            if ($_ =~ s/^$UserName:$OldHashedPW/$NewUserName:$NewHashedPW/) {
               $UserChangedFlag = 1;
               last;
            }
         }
         if ($UserChangedFlag == 0) {
            &NewErr('Incorrect password!  Your username has NOT been changed.'); }
         else {
            &WriteUpdate('UserName',$NewUserName,'newuser');
            open (PWDAT, ">/home/ericll75/www/steepturns.com/badcams/Data/.htpasswd") or croak("Unable to open user data file! $!\n");
            flock(PWDAT,1) || croak("Unable to flock user data file!");
               print PWDAT @AllUsers;
            close (PWDAT);
            &NewErr('Your username has been successfully changed.',$NewUserName,$UserPW);
         }
      }
   }
   elsif ($WhatChange eq 'postrealname') {
      my $FirstName   = &escapify(param('FirstName'));
      my $LastName    = &escapify(param('LastName'));
      if (length($FirstName) < 1 || length($LastName) < 1) {
         &NewErr('You must enter both your first and last name!  Nothing done.'); }
      elsif (length($FirstName) > 20 || $FirstName =~ /[^A-Za-z\s]/) {
         &NewErr('Illegal characters in your first name!  Nothing done.'); }
      elsif (length($LastName) > 30 || $LastName =~ /[^A-Za-z\s]/) {
         &NewErr('Illegal characters in your last name!  nothing done.'); }
      else {
         &WriteUpdate('FirstName',$FirstName,'string');
         &WriteUpdate('LastName',$LastName,'string');
         &NewErr('Your name has been successfully changed.');
      }
   }
   elsif ($WhatChange eq 'postuseremail') {
      my $UserEmail   = substr(param('UserEmail'),0,60);
      if (length($UserEmail) < 6) {
         &NewErr('You must enter your email address!  Nothing done.'); }
      elsif (!&CheckEmail($UserEmail)) {
         &NewErr('Invalid email address!  Nothing done.'); }
      else {
         &WriteUpdate('UserEmail',&escapify($UserEmail),'string');
         &NewErr('Your email address has been successfully changed.');
      }
   }
   elsif ($WhatChange eq 'postuserbday') {
      my $BdayMonth   = param('BdayMonth');
      my $BdayDate    = param('BdayDate');
      my $BdayYear    = param('BdayYear');
      if ($BdayMonth !~ /^\d\d?$/ || $BdayMonth < 1 || $BdayMonth > 12) {
         &NewErr('You must select your birth month!  Nothing done.'); }
      elsif ($BdayDate !~ /^\d\d?$/ || $BdayDate < 1 || $BdayDate > 31 ||
             ($BdayMonth == 2 && $BdayDate > 29) ||
             ($BdayMonth =~ /^4|6|9|11$/ && $BdayDate > 30)) {
         &NewErr('You must select your birth date!  Nothing done.'); }
      elsif ($BdayYear !~ /^\d\d\d\d$/ || $BdayYear < 1900) {
         &NewErr('Invalid birth year!  Nothing done.'); }
      elsif ($BdayYear > 1986) {
         &NewErr('Sorry, that age is too young!  Nothing done.'); }
      else {
         my $Bday = sprintf("%02d", $BdayMonth) . sprintf("%02d", $BdayDate) . $BdayYear;
         &WriteUpdate('UserBday',$Bday,'string');
         &NewErr('Your birthdate has been successfully changed.');
      }
   }
   elsif ($WhatChange eq 'postsexorient') {
      my $SexOrient   = &escapify(param('SexOrient'));
      if (length($SexOrient) < 1 || length($SexOrient) > 21 || $SexOrient =~ /[^A-Za-z\s\/]/) {
         &NewErr('You did not enter your sexual orientation!  Nothing Done.'); }
      else {
         @CurrUserInfo = &GetAllUserInfo;
         if ($SexOrient eq "Gay/Lesbian" && $CurrUserInfo[16] eq 'F') {
            $SexOrient = "Lesbian"; }
         elsif ($SexOrient eq "Gay/Lesbian") {
            $SexOrient = "Gay"; }
         &WriteUpdate('SexOrient',$SexOrient,'string');
         &NewErr('Your sexual orientation has been successfully changed.');
      }
   }
   elsif ($WhatChange eq 'postlocation') {
      my $UserState   = &escapify(param('UserState'));
      my $UserCountry = &escapify(param('UserCountry'));
      if ((length($UserState) < 3 && length($UserCountry) < 2) ||
          length($UserState) > 20 || $UserState =~ /[^A-Za-z\.\s]/ ||
          $UserCountry =~ /[^A-Za-z\.\s]/) {
         &NewErr('You must enter your state, or if not living in the U.S.<br>or Canada, you must enter your country.  Nothing done.'); }
      elsif (length($UserState) < 3 &&
             ($UserCountry =~ /united states/i || $UserCountry =~ /u\.s\./i ||
              $UserCountry =~ /canada/i)) {
         &NewErr('If you live in the U.S. or Canada, you must enter your state.  Nothing done.'); }
      else {
         my $UserLocation;
         if (length($UserState) > 2) { $UserLocation = $UserState; }
         else { $UserLocation = $UserCountry; }
         &WriteUpdate('UserLocation',$UserLocation,'string');
         &NewErr('Your location has been successfully changed.');
      }
   }
   elsif ($WhatChange eq 'postuserpw') {
      my $OldUserPW = param('UserPOld');
      my $UserP1    = param('UserP1');
      my $UserP2    = param('UserP2');
      if (length($UserP1) < 6 || length($UserP2) < 6 ||
          length($UserP1) > 20 || length($UserP2) > 20) {
         &NewErr('Your new password must be 6-20 characters long!  Nothing done.'); }
      elsif ($UserP1 =~ /[^A-Za-z0-9]/) {
         &NewErr('Your new password contains invalid characters!  Nothing done.'); }
      elsif ($UserP1 ne $UserP2) {
         &NewErr('Those passwords do not match!  Nothing done.'); }
      elsif ($OldUserPW =~ /[^A-Za-z0-9]/ || length($OldUserPW) < 6 || length($OldUserPW) > 20) {
         &NewErr("The original password is incorrect!  Your password has NOT been changed."); }
      else {
         my $OldHashedPW = crypt($OldUserPW,$UserName);
         my $NewHashedPW = crypt($UserP1,$UserName);
         my $UserChangedFlag = 0;
         my @AllUsers;
         open (PWDAT, "/home/ericll75/www/steepturns.com/badcams/Data/.htpasswd") or croak("Unable to open user data file! $!\n");
         flock(PWDAT,1) || croak("Unable to flock user data file!");
            @AllUsers = <PWDAT>;
         close (PWDAT);
         foreach (@AllUsers) {
            if ($_ =~ s/^$UserName:$OldHashedPW$/$UserName:$NewHashedPW/) {
               $UserChangedFlag = 1;
               last;
            }
         }
         if ($UserChangedFlag == 0) {
            &NewErr('The original password is incorrect!  Your password has NOT been changed.'); }
         else {
            open (PWDAT, ">/home/ericll75/www/steepturns.com/badcams/Data/.htpasswd") or croak("Unable to open user data file! $!\n");
            flock(PWDAT,1) || croak("Unable to flock user data file!");
               print PWDAT @AllUsers;
            close (PWDAT);
            my $PostDate .= sprintf("%04d",localtime->year()+1900) . sprintf("%02d",localtime->mon()+1) . sprintf("%02d",localtime->mday());
               $PostDate .= sprintf("%02d",localtime->hour()) . sprintf("%02d",localtime->min()) . sprintf("%02d",localtime->sec());
            $SQL = qq`SELECT LastAction FROM CamUsers1 WHERE UserName='$UserName'`;
            &CreateDBConnection;
               &DoSQL;
               my ($LastAction) = $sth->fetchrow_array;
               $SQL = qq`UPDATE CamUsers1 SET LastAction='$LastAction\/\/UserPW^$PostDate' WHERE UserName='$UserName'`;
               &DoSQL;
            $dbh->disconnect;
            &NewErr('Your password has been successfully changed.',$UserName,$UserP1);
         }
      }
   }
}

#------------------------- Write update to CamUsers1 table.
sub WriteUpdate {
   my $PostDate .= sprintf("%04d",localtime->year()+1900) . sprintf("%02d",localtime->mon()+1) . sprintf("%02d",localtime->mday());
      $PostDate .= sprintf("%02d",localtime->hour()) . sprintf("%02d",localtime->min()) . sprintf("%02d",localtime->sec());
   my $FieldCheck;
   my $WhatField    = shift;
   my $WhatValue    = shift;
   my $StringOrInt  = shift;
   if ($StringOrInt eq 'string') {
      $SQL1 = qq`UPDATE CamUsers1 SET $WhatField='`.&escapify($WhatValue).qq`' WHERE UserName='$UserName'`;
      $SQL2 = qq`SELECT $WhatField FROM CamUsers1 WHERE UserName='$UserName'`;
   }
   elsif ($StringOrInt eq 'newuser') {
                  #This is only used if we are changing the username.
      $SQL1 = qq`UPDATE CamUsers1 SET $WhatField='$WhatValue' WHERE UserName='$UserName'`;
      $SQL2 = qq`SELECT $WhatField FROM CamUsers1 WHERE UserName='$WhatValue'`;
   }
   else {
      $SQL1 = qq`UPDATE CamUsers1 SET $WhatField=$WhatValue WHERE UserName='$UserName'`;
      $SQL2 = qq`SELECT $WhatField FROM CamUsers1 WHERE UserName='$UserName'`;
   }
   $SQL = qq`SELECT LastAction FROM CamUsers1 WHERE UserName='$UserName'`;
   &CreateDBConnection;
      &DoSQL;
      my ($LastAction) = $sth->fetchrow_array;
      $SQL = qq`UPDATE CamUsers1 SET LastAction='$LastAction\/\/$WhatField^$PostDate' WHERE UserName='$UserName'`;
      &DoSQL;
      $SQL = $SQL1;
      &DoSQL;
      $SQL = $SQL2;               #This was assigned up above.
      &DoSQL;
      ($FieldCheck) = $sth->fetchrow_array;
   $dbh->disconnect;
   if ($FieldCheck eq $WhatValue) { return 1; }
   else { &NewErr("Error saving changes, nothing done."); }
}

#------------------------- Sets ActiveStatus to let moderator review.
sub NeedsReview {
   &CreateDBConnection;
      $SQL = qq`UPDATE CamUsers1 SET ActiveStatus='ci' WHERE UserName='$UserName'`;
      &DoSQL;
      $SQL = qq`SELECT ActiveStatus FROM CamUsers1 WHERE UserName='$UserName'`;
      &DoSQL;
      ($FieldCheck) = $sth->fetchrow_array;
   $dbh->disconnect;
   if ($FieldCheck eq 'ci') { return 1; }
   else { &NewErr("Error saving changes, nothing done."); }
}

sub escapify {
   $_[0] =~ s/([^\/]?)\'/$1\\\'/g;
   $_[0] =~ s/([^\/]?)\"/$1\\\"/g;
   return $_[0];
}
sub sql2html {
   $_[0] =~ s/\\\'/\&\#39;/g;
   $_[0] =~ s/\\\"/\&\#34;/g;
   return $_[0];
}
sub htmlify {
   $_[0] =~ s/\'/\&\#39;/g;
   $_[0] =~ s/\"/\&\#34;/g;
   return $_[0];
}





#---------------------------- End of most error/taint checks.


my $SiteID;
my $IDList;
my $CurrCamMD5;
my @PrevUserList;
my $UserLocation;
my $CurrTimeStamp = time;

#--------------------- Get cam checksum.
my $ua = LWP::UserAgent->new;                # Create a user agent object
   $ua->agent("Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)");
my $req = HTTP::Request->new(GET => "$CamURL");
   $req->content('match=www&errors=0');
my $res = $ua->request($req);                                #Pass request to user agent, get response.



unless ($res->is_success) {                    #If cam image doesn't exist, return w/error.
   &NewErr('NoCSU');
}
else {
   $CurrCamMD5 = md5_hex($res->content);
}


#--------------------- Check/write to password file.

$UserName = &escapify($UserName);                   #Since we did not encrypt UserName up above.



if (length($UserState) > 2) { $UserLocation = $UserState; }
else { $UserLocation = $UserCountry; }

my $Bday = sprintf("%02d", $BdayMonth) . sprintf("%02d", $BdayDate) . $BdayYear;
my $PostDate .= sprintf("%04d",localtime->year()+1900) . sprintf("%02d",localtime->mon()+1) . sprintf("%02d",localtime->mday());
   $PostDate .= sprintf("%02d",localtime->hour()) . sprintf("%02d",localtime->min()) . sprintf("%02d",localtime->sec());





sub NewErr {
   my $LoginCred = '';
   if ($_[1] && $_[2]) { $LoginCred = $_[1].":".$_[2]."\@"; }
                      #This will log them in with the new username/password.
   print "Content-type: text/html\n\n";
   print qq`
      <html>
      <body onLoad="javascript:SubmitNow()">
         <form name="ErrFormNew" method="post" action="http://`.$LoginCred.qq`www.steepturns.com/badcams/members/index.cgi">
            <input type=hidden name=FileErr value="$_[0]">
         </form>
         <SCRIPT language=JavaScript><!--
            function SubmitNow() {
               document.ErrFormNew.submit()
            }
         //-->
         </SCRIPT>

      </body>
      </html>`;
   exit;
}
sub escapify {
   $_[0] =~ s/([^\/]?)\'/$1\\\'/g;
   $_[0] =~ s/([^\/]?)\"/$1\\\"/g;
   return $_[0];
}

sub sql2html {
   $_[0] =~ s/\\\'/\&\#39;/g;
   $_[0] =~ s/\\\"/\&\#34;/g;
   return $_[0];
}

#---------------------------  See if the URL exists.
sub CheckURLExists {
   use LWP::Simple ();                  #Don't import anything...
   *LWPhead = \&LWP::Simple::head;      #...then import head as LWPhead()
   if (!LWPhead($_[0])) {    #Checks if URL actually exists.
      return 0;
   }
   else {
     return 1;
   }
}
