###############################################################################
# BizDesign ImageFolio Lite Edition 4.2 (Four-dot-Two)
###############################################################################
#
#          ##          ###        VERSION       :  4.2
#        ####        ##   ##      RELEASED ON   :  02/15/2007
#      ##  ##              ##     LAST MODIFIED :  02/15/2007
#    ##########          ##       
#          ##   ###    ##         
#          ##   ###  ########     
#
###############################################################################
# Released by BizDesign, Inc.
# written by Dirk Koppers and Greg Raaum of BizDesign
#
# Purchasing :  http://imagefolio.com/purchase/
# Support    :  http://imagefolio.com/support/
# Phone      :  (214) 642-9787
# Email      :  sales@bizdesign.com
###############################################################################
# COPYRIGHT AND LICENSE INFORMATION :
#
# Copyright (c) 1999-2007 BizDesign, Inc. All rights reserved.
#
# Selling or distributing the code for this program without prior written
# consent is expressly forbidden.
#
# One licensed copy of the program may reside on a single server, in use by a
# single domain.  For each installed instance of the program, a separate
# license is required.
#
# Licensed users may alter or modify this software, at their own risk, of
# course.  They may also hire others to modify their own copy of the code, as
# long as the code is not transferred to or retained by the individual who is
# hired (unless he/she is also a license holder). Although license-holders
# may modify the code for their use, modified code may NOT be resold or
# distributed.
#
# THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BIZDESIGN,
# INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# BizDesign, Inc. is not liable for any conduct associated with image gallery
# activity, nor for any binary media posted using this program, including but
# not imited to images, photographs, movies, and clipart.
#
# The user must assume the entire risk of using the program.  Although this
# program has been thoroughly tested on BizDesign's servers, BizDesign does not
# warrant that it works on all servers and will not be held liable for anything,
# including but not limited to, misusage, error, or loss of data.  ANY
# LIABILITY OF THE SELLER WILL BE LIMITED EXCLUSIVELY TO PRODUCT REPLACEMENT
# OR REFUND OF PURCHASE PRICE.  Use at your own risk!
###############################################################################
# Do not modify below this line unless you know what you are doing.
###############################################################################
   require "$currdir/admin/init.pl";
   use CGI qw(:standard);
   $CGITempFile::TMPDIRECTORY = $tempuploaddir;
   require "$libpath/crypt.pl";
   if ($use_im && !$iBULC_thumbnailing) {
      require "$libpath/imagemagick.pl";
   }
   elsif (!$iBULC_thumbnailing) {
      require "$libpath/imageconvert.pl"; &load_ic;
   }
   if ($using_multiuser_mod) {
      $FORM{'admin'} = 1;
      require "$config_directory/users_config.pl";
      require "$libpath/users_access.pl";
      if (!$is_admin) {&start_multiuser_mod;}
   }
   &config_more;
   require "$libpath/iptc.pl";
   my ($encryption_key,$uploaddir,$file1,$file2,$file3,$field,$fraudkey,$comparekey);
   &start;


   sub setup_all {
      $encryption_key = $secret_key;
   }

   sub setup_client {
      # This is the main configuration part. The information here will be used for the setup of the iBULC client as
      # outlined here: http://www.ibulc.com/developers/client_setup.shtml
      my ($iB_version,$iB_random,$iB_upload,$iB_return,$iB_types,$iB_max,$iB_original,$iB_medium,$iB_small,$iB_field_value,$iB_field_name,$iB_cookie,$iB_encryption,$iB_packets,$iB_bgcolor,$iB_stylesheet,$iB_display,$iB_custom_result,$iB_affiliate,$iB_language);
      $iB_version         = "1.3";
      $iB_random          = time;
      $iB_upload          = $iBULC_uploaddurl;
      $iB_return          = "$imagefolio_url?direct=$category";
      if ($use_fullsize && (lc($myextension_fullsize) ne 'zip')) {
         $iB_types           = $myextension_fullsize;
      }
      else {
         @allow_extensions = sort { 
                if(lc($a) eq 'jpg') { return -1; }
                elsif(lc($b) eq 'jpg') { return 1; }
                else { return lc($a) cmp lc($b); }
               } @allow_extensions;
         foreach (@allow_extensions) {
            next if !exists($extensions{lc($_)});
            $iB_types       .= "$_,";
         }
         $iB_types           =~ s/\,$//g;
      }
      $iB_max             = $max_size;
      if ($iBULC_thumbnailing) {
         $iB_original        = $use_fullsize;
         $iB_medium          = "medium_|$ImageDimensions|$ImageDimensions|0|$ImageQuality|$ImageSharpness|1";
         $iB_small           = "small_|$ThumbDimensions|$ThumbDimensions|0|$ThumbQuality|$ThumbSharpness|0";
      }
      else {
         $iB_original        = "1";
         $iB_medium          = ();
         $iB_small           = ();
      }
      $iB_field_value     = $category;
      $iB_field_name      = "Category";
#      $iB_watermark       = "$base_if_url/$overlay_image";
      $iB_cookie          = qq|[IFPro_user_session->$COOKIE{'IFPro_user_session'}][IFPro_mem->$COOKIE{'IFPro_mem'}][IF_UID->$COOKIE{'IF_UID'}][UPLOAD_DATE->$set_upload_date]|;
      $iB_encryption      = &admin_encrypt("$iB_types~$iB_max~$iB_original~$iB_medium~$iB_small~$iB_field_value~$iB_cookie~$iB_watermark", $encryption_key) if $encryption_key;
      $iB_encryption =~ s/[^a-z]//g;
      $iB_packets  = "1";
      $iB_bgcolor          = $iBULC_bgcolor;
      $iB_bgcolor            =~ s/^\#//g;
      $iB_stylesheet         = $iBULC_stylesheet_url;
      if ($FORM{'fe_admin'}) {
         $iB_display         = "popup";
      }
      else {
         $iB_display         = "iframe";
      }
      $iB_custom_result   = "1";
#      $iB_aid             = "IF";
      $iB_language        = "English";
      $iB_clock           = "$iBULC_clock"; # Set this to "White" if you are using a dark background color in your stylesheet.
      $iB_watermark_gravity = "Center";
      $iB_check_types      = "0";
      $iB_wxh_info = "1";
#      $iB_cleanup_files = "skip";
      # Now we put all this stuff together to get the iBULC setup query.
      my $iB_query = "iB_version=$iB_version;iB_random=$iB_random;iB_upload=$iB_upload;iB_return=$iB_return;iB_types=$iB_types;iB_max=$iB_max;iB_field_value=$iB_field_value;iB_field_name=$iB_field_name;iB_cookie=$iB_cookie;iB_small=$iB_small;iB_medium=$iB_medium;iB_original=$iB_original;iB_encryption=$iB_encryption;iB_packets=$iB_packets;iB_bgcolor=$iB_bgcolor;iB_stylesheet=$iB_stylesheet;iB_display=$iB_display;iB_custom_result=$iB_custom_result;iB_aid=$iB_aid;iB_language=$iB_language;iB_clock=$iB_clock;iB_watermark=$iB_watermark;iB_watermark_gravity=$iB_watermark_gravity;iB_check_types=$iB_check_types;iB_wxh_info=$iB_wxh_info;iB_cleanup_files=$iB_cleanup_files";
      return $iB_query;
   }

   sub setup_upload {
      # Set the directory that the files should be uploaded to. Make sure it is writable (CHMODD 777).
#      $uploaddir = $tempdir;
      $uploaddir = $image_directory;
   }


###############################################################################
# START
###############################################################################
   sub start {
      $query = new CGI;
      $file1 = $query->param("FILE1");
      $file2 = $query->param("FILE2");
      $file3 = $query->param("FILE3");
      $field = $query->param("FIELD");
      $fraudkey = $query->param("FRAUD_KEY");
      $comparekey = $query->param("COMPARE_KEY");
      $set_upload_date = $query->param("set_upload_date");

      if ($file1 or $file2 or $file3) {
         print "Content-type: text/html\n\n";
         if ($COOKIE{'UPLOAD_DATE'}) {
            $current_time -= $COOKIE{'UPLOAD_DATE'}*60*60*24;
         }
          if ($is_user && !$group_media_fs_per) {
            $use_fullsize = 0;
         }
         if ($admin_demo_mode) {
            $file1 = (); # Needed for win32 to remove the tempfile
            $file2 = (); # Needed for win32 to remove the tempfile
            $file3 = (); # Needed for win32 to remove the tempfile
            print "File not saved";
            exit;
         }
         &upload;
         $file1 = (); # Needed for win32 to remove the tempfile
         $file2 = (); # Needed for win32 to remove the tempfile
         $file3 = (); # Needed for win32 to remove the tempfile
      }
      elsif ($fraudkey && $comparekey) {
         print "Content-type: text/html\n\n";
         &fraud_check;
      }
      else {
         $FORM{'fe_admin'} = $query->param("fe_admin");
         if ($FORM{'fe_admin'}) {
            $category = $query->param("admin_directory");
         }
         else {
            $category = $query->param("category");
            $iBULC_bgcolor = "eeeeee";
            $iBULC_stylesheet_url = "";
         }
         print "Content-type: text/html\n\n";
         if (!$category) { &Errorme('You must select a Category.'); }
#         elsif (!(-e $tempdir))            { &Error('Your temp directory does not exist.'); }
#         elsif (!(-W $tempdir))            { &Error('Your temp directory is not writable.'); }
#         elsif (!(-d $tempdir))            { &Error('Your temp directory is not a valid directory.'); }

         if (!$is_admin && !$is_user) {
            &Errorme("You do not have permission to upload files to this site.");
         }
         elsif ($is_user) {
            if (!$group_media_upload_per) {
               &Errorme("Sorry $ifusername, you do not have permission to upload files to this site.");
            }
            &compare_cat($category);
            if (!$group_media_fs_per) {
               $use_fullsize = 0;
            }
         }
         elsif ($is_admin) {
            @allow_extensions = ();
            foreach $key (keys %extensions) {
               push(@allow_extensions, $key);
            }
         }
         &setup_ibulc;
      }
   }

###############################################################################
# SETUP iBULC
###############################################################################
   sub setup_ibulc {

      &setup_all;
      my $iB_query = &setup_client;
      $iB_query =~ s/([^a-zA-Z0-9])/"%" . sprintf("%2x", ord($1))/ge;

      print qq|<html>
      <head>
      <title>iBULC setup</title>
      <script language="JavaScript">
      setup = 0;
      function check_status(){
         now = new Date();
         iBULC=new Image();
         iBULC.onload=online;
         iBULC.src='http://127.0.0.1:1125/images/dot.gif?'+now.getTime();
         if (!setup) {
            window.setTimeout("check_status()", 1000);
         }
      }
      function online() {
         document.cookie = "cachereload=2\|1; path=/";
         setup = 1;
         window.focus();
         location.href = 'http://127.0.0.1:1125/setup/?$iB_query';
      }
      </script>
      </head>
      <body bgcolor="#FFFFFF" text="#000000" onLoad="check_status()">
      Currently you do not have the <a href="http://www.ibulc.com" target="_blank">internet Batch Up-Load Component</a> running.
      If you have downloaded it before then please run it now or download it here.<br><br>
      <center>
      <a href="http://download.ibulc.com/iBULCsetup-win.exe">Windows 98/ME/NT/2000/XP</a> or 
      <a href="http://download.ibulc.com/iBULCsetup-mac.dmg.gz">Mac OS-X</a>
      </center>
      </body>
      </html>|;
   }

###############################################################################
# FRAUD CHECK
###############################################################################
   sub fraud_check {
      &setup_all;
      $comparekey = &admin_encrypt($comparekey, $encryption_key);
      $comparekey =~ s/[^a-z]//g;
#      print "$comparekey<br>$fraudkey"; exit;
      if ($comparekey eq $fraudkey) {
         print "TRUE";
      }
      else {
         print "FALSE";
      }
   }

###############################################################################
# UPLOAD
###############################################################################
   sub upload {

      &setup_all;
      &setup_upload;

      my ($start_types,$start_max,$totalbytes,$bytesread,$buffer);


      if ($encryption_key) {
         ($start_types, $start_max) = split(/\~/, $comparekey);
         $comparekey = &admin_encrypt($comparekey, $encryption_key);
         $comparekey =~ s/[^a-z]//g;
#         $comparekey = $comparekey . "~$encryption_key";
#         $comparekey = md5_hex("$comparekey");
         if ($comparekey ne $fraudkey) {
            print "FRAUD_KEY and COMPARE_KEY do not match";
            $file1 = (); # Needed for win32 to remove the tempfile
            $file2 = (); # Needed for win32 to remove the tempfile
            $file3 = (); # Needed for win32 to remove the tempfile
            exit;
         }
         if ($file1) {
            my $found_type = ();
            my @start_types = split(/\,/, $start_types);
            my $all_types = shift(@start_types) if (lc($start_types[0]) eq 'all');
            foreach my $type (@start_types) {
               if ($file1 =~ /\.$type$/i) {
                  $found_type = 1;
               }
            }
            if ($all_types) {
               if ($found_type) {
                  print "Uploaded file type is not valid";
                  $file1 = (); # Needed for win32 to remove the tempfile
                  $file2 = (); # Needed for win32 to remove the tempfile
                  $file3 = (); # Needed for win32 to remove the tempfile
                  exit;
               }
            }
            elsif (!$found_type) {
               print "Uploaded file type is not valid";
               $file1 = (); # Needed for win32 to remove the tempfile
               $file2 = (); # Needed for win32 to remove the tempfile
               $file3 = (); # Needed for win32 to remove the tempfile
               exit;
            }
         }
      }

      if ($field) {
         $uploaddir .= "/$field";
         if (!-d $uploaddir) {
            print "Category \"$field\" does not exist.";
            exit;
         }
         elsif (!-w $uploaddir) {
            chmod (0777, $uploaddir);
            if (!-w $uploaddir) {
               print "Category \"$field\" is not writable.";
               exit;
            }
         }
#         my @categories = split(/\//, $field);
#         foreach (@categories) {
#            $uploaddir .= "/$_";
#            if (!-d $uploaddir) {
#               mkdir ("$uploaddir", "0777");
#               chmod(0777,"$uploaddir");
#            }
#         }
      }
      else {
         print "No upload category specified.";
         exit;
      }




      my $filedate = time;

      if ($file1) {
         my $totalbytes = ();
         my $outfile = ();
         ($shortname, $extension) = clean_file($file1);
         if ($use_fullsize && (lc($myextension_fullsize) eq 'zip')) {
            $outfile = "${mypattern_fullsize}${shortname}.$extension";
         }
         elsif ($use_fullsize && ($extension eq lc($myextension_fullsize))) {
            $outfile = "${mypattern_fullsize}${shortname}.$myextension_fullsize";
         }
         else {
            $extension = lc($extension);
            $outfile = "$shortname.$extension";
            $email_image_name = "$shortname.$extension";
            $if_tagfile = $extensions{$extension}[2];
         }
         $totalbytes = &save_file($file1, $outfile);
         if ($encryption_key) {
            if ($totalbytes > $start_max) {
               print "File to large";
               unlink "$uploaddir/$file1";
               $file1 = (); # Needed for win32 to remove the tempfile
               $file2 = (); # Needed for win32 to remove the tempfile
               $file3 = (); # Needed for win32 to remove the tempfile
               exit;
            }
         }
         if ($extension =~ /(jpg|tif)/i) {
            &add_user_info("$uploaddir/$outfile"); #gives error with jpg files that contain paths.
         }
         if (!$file2 && !$file3) {
            if (($extension =~ /(jpg|tif|png|psd|pcd|bmp|gif)/i) && !$iBULC_thumbnailing) {
               $imageconvert_log = ();
               &resize_image("$uploaddir/$outfile", "$uploaddir/$shortname.jpg");
               &add_user_info("$uploaddir/$shortname.jpg");
               &resize_thumbnail("$uploaddir/$shortname.jpg", "$uploaddir/$mypattern$shortname.jpg");
               &add_user_info("$uploaddir/$mypattern$shortname.jpg");
               if ($outfile ne "$shortname.jpg" && $email_image_name) {
                  unlink("$uploaddir/$outfile");
                  $email_image_name = ();
                  $if_tagfile = ();
               }
            }
            else {
               $used_icon = $extensions{$extension}[4];
               require File::Copy;
               &File::Copy::copy ("$icons_path/$used_icon", "$uploaddir/$mypattern$shortname.jpg");
               &add_user_info("$uploaddir/$mypattern$shortname.jpg");
               if (!$email_image_name) {
                  &File::Copy::copy ("$uploaddir/$mypattern$shortname.jpg", "$uploaddir/$shortname.jpg");
               }
            }
         }
         elsif ($outfile ne "$shortname.jpg" && $email_image_name) {
            unlink("$uploaddir/$outfile");
            $email_image_name = ();
            $if_tagfile = ();
         }
         if ($use_fullsize && (lc($myextension_fullsize) eq 'zip')) {
            require Archive::Zip;
            my $zip = Archive::Zip->new();
            if (lc($extension) eq "zip") {
               rename ("$uploaddir/$outfile","$uploaddir/${mypattern_fullsize}${shortname}.$myextension_fullsize");
#               rename ("$uploaddir/$outfile","$uploaddir/$outfile.temp.$myextension_fullsize");
#               $zip->addFile("$uploaddir/$outfile.temp.$myextension_fullsize","$shortname.$extension");
#               my $member = $zip->memberNamed("$shortname.$extension");
#               $member->desiredCompressionMethod( 0 );
#               $zip->writeToFileNamed("$uploaddir/${mypattern_fullsize}${shortname}.$myextension_fullsize");
#               unlink("$uploaddir/$outfile.temp.$myextension_fullsize");
            }
            else {
               $zip->addFile("$uploaddir/$outfile","$shortname.$extension");
               my $member = $zip->memberNamed("$shortname.$extension");
               $member->desiredCompressionMethod( 0 );
               $zip->writeToFileNamed("$uploaddir/${mypattern_fullsize}${shortname}.$myextension_fullsize");
               unlink("$uploaddir/$outfile");
            }
            chmod(0777,"$uploaddir/${mypattern_fullsize}${shortname}.$myextension_fullsize");
         }
      }
      if ($file2) {
         ($shortname, $extension) = clean_file($file2) if !$shortname;
         my $outfile = "$shortname.jpg";
         &save_file($file2, $outfile);
         &add_user_info("$uploaddir/$outfile");
      }
      if ($file3) {
         ($shortname, $extension) = clean_file($file3) if !$shortname;
         my $outfile = "$mypattern$shortname.jpg";
         &save_file($file3, $outfile);
         &add_user_info("$uploaddir/$outfile");
      }

      $newthumb = "$mypattern$shortname.$extension";

      &update_index_files;
      if ($is_user) {&create_email;&create_imagethumb_cache;}


      if ($index_requests_notification) {
         &rebuild_index_request_log;
      }

      # If you have set "$iB_custom_result=0" in the setup then make sure you print here "Done". Anything
      # else will show up as "Failed" in the iBULC client.
      print "Done";
   }

sub rebuild_index_request_log {
   open (FILE,">>$data_directory/index_request.tmp");
   print FILE "1\n";
   close(FILE);
   chmod(0777,"$data_directory/index_request.tmp");

   open (FILE,"$data_directory/index_request.tmp");
   (@index_request)=<FILE>;
   close(FILE);
   $index_requests=@index_request;

   if ($index_requests >= $index_requests_notification) {
      $request_email = ($index_requests / $index_requests_notification);
      ($request_email, $deci) = split(/\./,$request_email);
      if (!$deci) {
         &send_index_request_email;
      }
   }
}

sub send_index_request_email {
   $my_current_time = &admin_encrypt($current_time, $secret_key);
   my $from_out = $admin_email;
   my $to_out = $admin_email;
   my $cc_out = ();
   if (@picpost_moderators) {
      foreach $picpost_moderator (@picpost_moderators) {
         $my_picpost_moderator .= "$picpost_moderator,";
      }
      $my_picpost_moderator =~ s/,$//g;
      $bcc_out = $my_picpost_moderator;
   }
   my $subject_out = "Rebuild Index Request";
   my $type_out_0 = 'text/plain';  # 'text/plain' or 'text/html' or 'multipart/mixed' or 'multipart/related'
   my $data_out_0 = qq|Site: $imagefolio_url\n\Files have been added/moved/deleted $index_requests times without the index being rebuild. It is suggest that you rebuild the index now by clicking here:\n$buildurl&mct=$my_current_time\n\nNote: this direct link will expire in 24 hours.\n|;
   my $priority = 1;
   &send_mime_email($from_out, $to_out, $cc_out, $bcc_out, $subject_out, $type_out_0, $data_out_0, $type_out_1, $data_out_1, $type_out_2, $id_out, $path_out, $priority);
}

sub create_email {
   if (!$email_image_name) {
      $email_image_name = "$shortname.jpg";
   }
   if ($if_tagfile) {
      $if_tagfile = $extensions{"jpg"}[2];
   }
   $encrypt_link = &admin_encrypt("$imagefolio_url?action=view&link=$field&image=$email_image_name&tt=$if_tagfile&ota=1", $secret_key);
   $one_time_access = &admin_encrypt("$field/$email_image_name", $secret_key);
   if ($ifemail) {
      $from_email = $ifemail;
   }
   else {
      $from_email = $admin_email;
   }
   my $from_out = "$from_email";
   my $to_out = "$admin_email";
   my $cc_out = ();
   if (@picpost_moderators) {
      foreach $picpost_moderator (@picpost_moderators) {
         $my_picpost_moderator .= "$picpost_moderator,";
      }
      $my_picpost_moderator =~ s/,$//g;
      $bcc_out = $my_picpost_moderator;
   }
   $subject_out = "New Upload ($email_image_name)";
   if ($group_media_upload_approval) {
      $subject_out .= " ***Approval Required***";
      $message_out = qq|<b><$font><font color="#FF0000">TAKE ACTION!</font> This file needs approval before it is visible.</font></b><br><br>|;
      $approve_text = "approve/";
      $priority = 1;
   }
   else {
      $priority = 0;
   }
   my $type_out_0 = 'multipart/related';  # 'text/plain' or 'text/html' or 'multipart/mixed' or 'multipart/related'
   my $data_out_0 = '';
   my $type_out_1 = 'text/html'; # blank 'text/plain' or 'text/html'
   my $data_out_1 = qq|<body><center>$message_out<table border="1" cellspacing="1" cellpadding="5">
                         <tr>
                           <td align="center" width="50%" valign="top" nowrap><$font><a href="$adminurl&start=$encrypt_link"><b>Admin view</b><br><br><img src="cid:$email_image_name" border=0></a><br><br>After login you have administrator rights. You can<br>${approve_text}rename/caption/delete/move the file.</font></td>
                           <td align="center" width="50%" valign="top" nowrap><$font><a href="$imagefolio_url?action=view&link=$field&image=$email_image_name&tt=$if_tagfile&ota=$one_time_access"><b>One time quick access</b><br><br><img src="cid:$email_image_name" border=0></a><br><br>You have one time, quick access to this file only.<br>You can ${approve_text}delete the file.</font></td>
                         </tr>
                       </table></center></body>|;
   my $type_out_2 = 'image/jpeg'; # the type of attachment
   my $id_out = $email_image_name;
   my $path_out = "$uploaddir/$mypattern$shortname.jpg";
   &send_mime_email($from_out, $to_out, $cc_out, $bcc_out, $subject_out, $type_out_0, $data_out_0, $type_out_1, $data_out_1, $type_out_2, $id_out, $path_out, $priority);
}

sub create_imagethumb_cache {
   if (!$group_media_upload_approval) {
      $cachefilename = "thumb~USER~$ifusername~sort1~show_tn1";
      $cachefilename =~ s/[^0-9a-zA-Z\_]/~/g;
      $cacheloc = "$cache_directory/searches/$cachefilename";
      open (TCACHE,">>$cacheloc");
      print TCACHE "blah|$newthumb|$field|$filedate|0|0|\n";
      close(TCACHE);
      chmod(0777,"$cacheloc");

      $cachefilename = "direct~$field";
      $cachefilename =~ s/[^0-9a-zA-Z\_]/~/g;
      $cacheloc = "$cache_directory/searches/$cachefilename";
      open (TCACHE,">>$cacheloc");
      print TCACHE "blah|$newthumb|$field|$filedate|0|0|\n";
      close(TCACHE);
      chmod(0777,"$cacheloc");
   }
}

sub update_index_files {
   my $catlist = ();

   open (CATFILE, "$catfile");
   my(@catfiledata)=<CATFILE>;
   close(CATFILE);

   foreach $catfiledata (@catfiledata) {
      my ($catpath, $catcount, $catage) = split(/\t/, $catfiledata);
      if ($catpath eq $field){
         $catcount++;
         $catlist .= $catpath . "\t" . $catcount . "\t" . $filedate . "\t\n";
      }
      else {
         $catlist .= $catfiledata;
      }
   }

   open(CATFILE, ">$catfile");
   if ($useflock) { flock(CATFILE, 2); }
   print CATFILE $catlist;
   if ($useflock) { flock(CATFILE, 8); }
   close(CATFILE);

}

sub resize_image {
   my ($infile, $outfile) = @_;
   if (!$use_im) {
      &do_ic("\"$infile\"", "\"$outfile\"", $ImageDimensions, $ImageQuality, $ImageSharpness, $ImageContrast, $ImageCustom);
   }
   else {
      &do_im($infile, $outfile, $ImageDimensions, $ImageQuality, $ImageSharpness, $ImageContrast);
   }
   chmod (0666, $outfile);
}

sub resize_thumbnail {
   my ($infile, $outfile) = @_;
   if (!$use_im) {
      $ThumbCustom .= " -rmeta";
      &do_ic("\"$infile\"", "\"$outfile\"", $ThumbDimensions, $ThumbQuality, $ThumbSharpness, $ThumbContrast, $ThumbCustom, $ThumbCrop_ic);
   }
   else {
      &do_im($infile, $outfile, $ThumbDimensions, $ThumbQuality, $ThumbSharpness, $ThumbContrast, $ThumbCrop_im);
   }
   chmod (0666, $outfile);
}

sub add_user_info {
   my $input = shift;
#   return if $input =~ /\.tif$/i;
   @IPTC_attributes = ('caption/abstract','writer/editor','headline','special instructions','copyright notice','credit','source','object name','date created','by-line','by-line title','city','province/state','country/primary location name','original transmission reference','contact','content location code','content location name','country/primary location code','digital creation date','digital creation time','edit status','editorial update','expiration date','expiration time','fixture identifier','image orientation','image type','language identifier','object cycle','originating program','program version','reference date','reference number','reference service','release date','release time','sub-location','subject reference','time created','urgency','custom1','custom2','custom3','custom4','custom5','custom6','custom7','custom8','custom9','custom10','custom11','custom12','custom13','custom14','custom15','custom16','custom17','custom18','custom19','custom20');
   if (defined($source_iptc_info)) {
      $createinfo = create Image::IPTCInfo("$input");
      $createinfo->ClearKeywords();
      $createinfo->ClearSupplementalCategories();
      my $keywordsRef = $source_iptc_info->Keywords();
      if ($keywordsRef) {
         foreach $keyword (@$keywordsRef) {
            $createinfo->AddKeyword("$keyword");
         }
      }
      foreach $IPTC_attribute (@IPTC_attributes) {
         $iptcvalue = $source_iptc_info->Attribute("$IPTC_attribute");
         $createinfo->SetAttribute("$IPTC_attribute","$iptcvalue");
       }
      $createinfo->Save();
   }
   else {
      if (!$group_media_desc_per && !$is_admin) {
         my $iptc_info = new Image::IPTCInfo("$input");
         if (defined($iptc_info)){
            $createinfo = create Image::IPTCInfo("$input");
            $createinfo->ClearKeywords();
            $createinfo->ClearSupplementalCategories();
            foreach $IPTC_attribute (@IPTC_attributes) {
               $createinfo->SetAttribute("$IPTC_attribute","");
            }
         }
         else {
            $createinfo = create Image::IPTCInfo("$input");
         }
      }
      else {
         $createinfo = create Image::IPTCInfo("$input");
      }
      if ($ifemail && $ifusername) {
         $encrypt_email = &admin_encrypt($ifemail, $ifusername);
      }
      else {
         $encrypt_email = ();
      }
      $createinfo->SetAttribute('originating program','www.imagefolio.com');
      $createinfo->SetAttribute('program version','4.x');
      $createinfo->SetAttribute('custom18',"[$current_time][$ifusername][$encrypt_email][$group_media_upload_approval][$extension]") if $is_user;
      $createinfo->SetAttribute('custom18',"[$current_time][][][][$extension]") if $is_admin;
      $createinfo->Save();
   }

   if (!$source_iptc_info) {
      $source_iptc_info = new Image::IPTCInfo("$input");
   }
}

   sub clean_file {
      my $file = shift;
      $file =~ s!^.*(\\|\/)!!;
      my ($extension) = ($file =~ /\.([^.]+)$/);
      $extension = lc($extension);
      my ($base) = $file =~ m,^(.*)\.\w+$,;
#      $base =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
      $base =~ s/ /_/g;
      $base =~ s/\.//g;
      $base =~ s/[$deny_chars]//g;
      $base =~ s/$mypattern//g;
      $base =~ s/$mypattern_fullsize//g;
      $base =~ s/medium_//g;
      $base =~ s/small_//g;
      if (!$base) {
         $base = "novalidname";
      }
      $testfile1 = qq|$uploaddir/$base.jpg|;
      $testfile2 = qq|$uploaddir/$base.$extension|;
#      $testfile3 = qq|$uploaddir/$base.$myextension_fullsize| if lc($myextension_fullsize) eq 'zip');
      if ($overwrite_if_exist) {
         if (-e $testfile2 && ($extension eq 'jpg')) {
            $source_iptc_info = new Image::IPTCInfo("$testfile2");
         }
         elsif (-e $testfile1) {
            $source_iptc_info = new Image::IPTCInfo("$testfile1");
         }
      }
      elsif (-e $testfile1 or -e $testfile2) {
         for ($ext=1; $ext<100; $ext++) {
            $testfile1 = qq|$uploaddir/$base$ext.jpg|;
            $testfile2 = qq|$uploaddir/$base$ext.$extension|;
            if (!-e $testfile1 && !-e $testfile2) {
               $base = $base . $ext;
               last;
            }
         }
      }
      return ($base, $extension);
   }

   sub save_file {
      my ($infile, $outfile) = @_;
      my $file_path = "$uploaddir/$outfile";
      my $totalbytes = 0;
      open (OUTFILE, ">$file_path");
      binmode OUTFILE;
      while ($bytesread = read($infile, $buffer, 2048)) {
         $totalbytes += $bytesread;
         print OUTFILE $buffer; 
      }
      close (OUTFILE);
      chmod(0777,"$file_path");
      $infile = ();
      return $totalbytes;
   }


########################################################
# Error
# shows error message if form not filled out correctly
########################################################
sub Errorme{
local ($whoops) = @_;
die "\n\n$whoops\n\n";
#print qq|
#<html>
#<head>
#<title>Error!</title>
#
#<script language="JavaScript">
#<!--
#function help(){
#window.alert("Help\\n\\nThis error message is displayed either because I was not able to understand your input or your input was incorrect.");
#}
#//-->
#</script>
#
#</head>
#
#<body bgcolor="#ffffff" marginwidth=0 marginheight=0 topmargin=0 leftmargin=0>
#
#<form>
#
#<table border=0 cellspacing=0 cellpadding=0 width="100%" height="100%"><tr><td valign=middle align=center>
#<table border=2 cellspacing=0 cellpadding=0 width="450" bgcolor="#000000"><tr><td>
#<table border=0 cellspacing=0 cellpadding=3 width="450"><tr bgcolor="000000">
#<td nowrap><font face="Verdana,Arial,Helvetica" size="2" color="#ffffff"><strong>Error!</strong></font></td>
#<td align=right nowrap><font face="Verdana,Arial,Helvetica" size="2"><b><INPUT TYPE="button" VALUE=" ? " onClick="help()">&nbsp;<INPUT TYPE="button" VALUE=" X " onClick="history.go(-1)"></b></font></td></tr>
#
#<tr bgcolor="#eeeeee">
#<td colspan=2><table border=0 cellspacing=0 cellpadding=5 width="100%"><tr>
#<td><font face="Verdana,Arial,Helvetica" size="1"><b><font color="#ff0000">$whoops</font></b><br><br>If the button below does not take you back, please use your browser's back button to go back and try again.<br><br></font></td>
#</tr></table>
#
#<center><font face="Verdana,Arial,Helvetica" size="2"><INPUT TYPE="button" VALUE="     OK     " onClick="history.go(-1)"></font></center>
#
#</td></tr></table></td></tr></table></td></tr></table>
#</form>
#
#</body>
#</html>
#|;
$file1 = (); # Needed for win32 to remove the tempfile
$file2 = (); # Needed for win32 to remove the tempfile
$file3 = (); # Needed for win32 to remove the tempfile
exit;
}
1;