###############################################################################
# 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.
###############################################################################
use Digest::Directory::BASE;
use File::Path;
use File::Copy;

eval qq{ require "$libpath/if_web_get.pl"; } or $no_socket_loading=1;
eval "use Archive::Zip qw(:CONSTANTS :ERROR_CODES);1;" or $donnotzip = 1;

$SKINSMANAGER = "active";
$version = '_lite';

sub skin_upload {
	my ($upload, $download) = @_;
#	my $info_OS = $^O;
	my $type = 'skin';   
	$type = 'zip' unless $donnotzip; 
	my ($extension) = ($upload =~ /\.([^.]+)$/);

	if (lc($extension) ne $type) {
		unlink("$tempuploaddir/$upload");

		&manual($download, "Upload file type must be .$type");
	} else {
		my $skins_dir = $base_skin_dir;

		&uncompress_skin("$tempuploaddir/$upload", $skins_dir, 0, "http://skins.imagefolio.com/skins$version/zip/$upload");
	}
}

sub manual {
	my ($download, $error) = @_;

	&get_header;

	print qq{
<script language="javascript">
function beginDownload() {
	document.write('<iframe height="0" width="0" frameborder="0" src="$download"></iframe>');
}
window.onLoad = beginDownload();
</script>
	} if $download;

	print qq{
<center>
<table border="0" width="100%" cellspacing=0 cellpadding=0 bgcolor="#000000">
  <tr>
    <td>
      <table border="0" width="100%" cellspacing=1 cellpadding=0>
        <tr bgcolor="#ffcc00">
          <td>
            <table border="0" width="100%" cellspacing=0 cellpadding=4>
              <tr>
                <td><$admin_big_font><b>ImageFolio Skins Manager</b></font></td>
                <td align=right><$admin_big_font><b>Manual Installation</b></font></td>
              </tr>
            </table>
          </td>
        </tr>
        <tr bgcolor="#ffffff">
          <td valign=top>
            <table border=0 cellspacing=1 cellpadding=5 width="100%">
              <tr>
                <td bgcolor="#eeeeee">
                  <center><$admin_font><font color=red>$error</font></font><br>
                  <form method="POST" action="$uploadurl" ENCTYPE="multipart/form-data">
                  <input type="hidden" name="download" value="$download">
                  <input type="hidden" name="uid" value="$FORM{'uid'}">
                  <input type="hidden" name="category" value="1">
                  <input type="hidden" name="admin_skin" value="1">
                  <input type="file" name="skin_upload">
                  <input type="submit" value="Upload File">
                  </form>
                  </center>
                </td>
              </tr>
	};

	if ($download) {
		print qq{	
              <tr>
                <td bgcolor="#eeeeee">
                  <$admin_font>There was an problem downloading the selected file. Please download this file to you harddrive then use the form below to 
                  upload into your skins directory.<p>
                  Your download should begin shortly. If it does not, try:<br>
                  <center><a href="$download">$download</a></center><p>
                </td>
              </tr>
		};
	} else {
#		my $info_OS = $^O;
		my $url = "http://skins.imagefolio.com/skins$version/tar/skins.js";
		$url = "http://skins.imagefolio.com/skins$version/zip/skins.js" unless $donnotzip; 

		print qq{	
              <tr>
                <td bgcolor="#eeeeee">
                  <$admin_font>Choose a skin from the following files. Once downloaded, use the above form to upload into your skins directory.</font><br>
                </td>
              </tr>
              <SCRIPT LANGUAGE="JavaScript" SRC="$url"></SCRIPT>
		};
	}

	print qq{
            </table>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
	};

	&get_footer;
	
	exit;
}

sub menu {
	my $error_display = '';

#	$error_display = 'You must install at least one skin and make it the default skin in order to continue.' if $default_skin_loaded;

	$pagetitle = "Skins Manager";

	my $manual = $FORM{'manual'};
	my $upload = $FORM{'upload'};
	my $download = $FORM{'download'};

	if ($manual) {
		if ($upload) {
			&skin_upload($upload, $download);
		} else {
			&manual;
		}
	}

	my $skins_dir = $base_skin_dir;
	
   &Error("Your skins directory ($skins_dir) must be writable. chmod 777") if !-w $skins_dir;
	
	my $skin_in = $FORM{'skin'};
	my $choice = $FORM{'choice'};
	my $default = $FORM{'default'};
	my $remove = $FORM{'remove'};
	my $install = $FORM{'install'};
	my $restore = $FORM{'restore'};
	my $duplicate = $FORM{'duplicate'};
	my $edit = $FORM{'edit'};

	if ($edit && $skin_in) {
		require "$admindir_directory/skin_edit.pl";
	
		&edit($skin_in);
	}

	my %all_skins;
	
	my $web_skins_file = "$data_directory/db/web_skins.txt";
	
#	my $response = getstore('http://skins.imagefolio.com/cgi-bin/skins.cgi', $web_skins_file);# if !-e $web_skins_file || -M $web_skins_file > 1;
   my $response = &if_web_get("http://skins.imagefolio.com/cgi-bin/skins.cgi?$version", "$web_skins_file") unless $no_socket_loading;

	my %web_skins;
	my $web_url;

	if (-e $web_skins_file) {
		open(WEBSKINS, $web_skins_file);
		my @web_skins = <WEBSKINS>;
		close(WEBSKINS);
	
		$web_url = shift(@web_skins);
		chomp($web_url);
	
		foreach my $skin(@web_skins) {
			chomp($skin);
	
			my ($name, $description, $digest, $option) = split(/\|/, $skin);
		
			$web_skins{$name} = [$description, $digest, $option];
		
			$all_skins{$name} = 1;
		
			if ($skin_in eq $name && ($install || $restore)) {
				my $skin_dir = $skins_dir . '/' . $name;
		
				rmtree($skin_dir) if -e $skin_dir;
		   
				$error_display = "Could not completely remove the skin at<br>$skin_dir<br>Please login through FTP to remove manually." if -e $skin_dir;
		    
#				my $info_OS = $^O;
			
				my $file = "$name.skin";
				my $url = "tar/$name.skin";
			
				unless ($donnotzip) {
					$file = "$name.zip";
					$url = "zip/$name.zip";
				}

				my $temp_file = $tempdir . '/' . $file;
				my $file_url = $web_url . '/' . $url;

#				my $skin_response = getstore($file_url, $temp_file);
            my $skin_response = &if_web_get($file_url, $temp_file) unless $no_socket_loading;

				if ($skin_response eq "done") {
					&uncompress_skin($temp_file, $skins_dir, 0, $file_url);
				} else {
					&manual($file_url);
				}
			}
		}
	}

	opendir(SKINS, $skins_dir);
	my @local_skins = grep !/^\./, readdir SKINS;
	closedir(SKINS);

	if (!$skin_name || !-e "$skins_dir/$skin_name") {
		$skin_name = '';

		foreach my $directory(@local_skins) {
			next unless -e $skins_dir . '/' . $directory . '/config_skin.pl';

			$default = 1;

			$skin_in = $directory;

			last;	
		}
	}

	if ($skin_in || !$skin_name) {
		if ($default && -e $skins_dir . '/' . $skin_in . '/config_skin.pl') {
			$skin_name = $skin_in;
		}

		my $write = '$skin_name = \'' . $skin_name .  '\';' . "\n";

		my @choices = @user_skin_choices;

		push(@choices, $skin_in) if $choice && $skin_in;


		@user_skin_choices = ();
		
		foreach my $skin(@local_skins) {
			my $skin_dir = $skins_dir . '/' . $skin;
        
			next unless -e $skin_dir . '/config_skin.pl';

			foreach my $choose(@choices) {
				if ($choose eq $skin) {
					push(@user_skin_choices, $skin) unless $skin eq $skin_in && !$choice;
                
					last;
				}
			}
		}

		if (!@user_skin_choices) {
			$write .= '@user_skin_choices = ();' . "\n";
		} else {
			$write .= '@user_skin_choices = (' . "'" . join("', '", @user_skin_choices) . "'" .  ');' . "\n";
		}

		unless ($admin_demo_mode) {
			open(CONFIG, ">$data_directory/config/skins.pl");
			flock(CONFIG, 2) if $useflock;
			print CONFIG "$write\n1;";
			flock(CONFIG, 8) if $useflock;
			close(CONIG);
			chmod(0777, "$data_directory/config/skins.pl");
		}
	}

   if (-e "$base_skin_dir/$skin_name/config_skin.pl" && $default_skin_loaded) {
      $skin_url = $base_skin_url . "/" . $skin_name;
      require "$base_skin_dir/$skin_name/config_skin.pl";
      $default_skin_loaded = 0;
   }

	$error_display = 'You must install at least one skin and make it the default skin in order to continue.' if $default_skin_loaded;


	my %local_skins;
	
	my $count = split(/\//, $skins_dir);

	foreach my $skin(@local_skins) {
		my $skin_dir = $skins_dir . '/' . $skin;
		
		if ($remove && $skin_in eq $skin) {
		   if ($skin eq $skin_name) {
			   $error_display = "You may not remove the default skin.";
		   } else {
			   rmtree($skin_dir) or $error_display = "Could not delete skin at<br>$skin_dir<br>Reason: $!";
		   
			   $error_display = "Could not completely remove the skin at<br>$skin_dir<br>Please login through FTP to remove manually." if -e $skin_dir;
		   }
		}
		
		if ($duplicate && $skin_in eq $skin) {
			my $new_name = $FORM{'name'};
			
			my $new_dir = $skins_dir . '/' . $new_name;
			
			if (-e $new_dir) {
				$error_display = "There is already a skin named $new_name.";
			} else {
				&skin_dir_copy($skin_dir, $new_dir);
				
				push(@local_skins, $new_name);
			}
		}
		
		next unless -e $skin_dir . '/config_skin.pl';
		
		my $description_file = $skin_dir . '/description.txt';

		my $description = '';

		if (-e $description_file) {
			open(DESC, $description_file); 
			my @description = <DESC>;
			close(DESC);

			$description = join(' ', @description);

			chomp($description);

			$description =~ s/\s+/ /g;
		}
		
		my $dirgest = Digest::Directory::BASE->new;
  
		$dirgest->quiet(1);
		$dirgest->include($skin_dir);
		$dirgest->trim($count);
		$dirgest->compute();

		my $digest = $dirgest->string(1, 0);
		
		chomp($digest);
		
		$local_skins{$skin} = [$description, $digest, $option];
		
		$all_skins{$skin} = 1;
	}

	my $list = ''; 
	
	foreach my $key(sort(keys(%all_skins))) {
		my ($local_description, $local_digest, $web_description, $web_digest);
		
		($local_description, $local_digest, $local_option) = @{$local_skins{$key}} if $local_skins{$key};
		
		($web_description, $web_digest, $web_option) = @{$web_skins{$key}} if $web_skins{$key};
		
		my $local = $local_digest ? 1 : 0;
		
		my $web = $web_digest ? 1 : 0;
		
		my $install = !$local && $web ? 1 : 0;
		
		my $remove = $local ? 1 : 0;
		
		my $restore = $local && $web && $web_digest ne $local_digest ? 1 : 0;
		
		my $description = $local_digest ? $local_description : $web_description;
		
		my $image = $local ? $base_skin_url . '/' . $key . '/images/screenshot.jpg' : 'http://skins.imagefolio.com/skins' . '/skins/' . $key . '/images/screenshot.jpg';

		my $buttons = '';

		my $boxes = '';

		my $default_checked = $skin_name eq $key ? 'checked' : '';
		my $default_disabled = $skin_name eq $key ? ' disabled' : ' onClick="this.form.submit()"';

#if ($local) {
#print "Content-type: text/plain\n\n$skin_name, $key\n";
#exit;
#}

		$remove = 0 if $default_checked;

		$choice_checked = '';

		foreach my $choice(@user_skin_choices) {
			if ($key eq $choice) {
				$choice_checked = 'checked';

				last;
			}
		}

      if ($web_option){
         $buttons .= qq{ <A HREF="http://imagefolio.com/purchase" class="roll2">$web_option</a> |}
      }
      else {

		$boxes = qq{
                  <br><span style="text-align:right">
                  <form method="post" action="$adminurl#$key">
                  <$admin_font>
                  <input type="hidden" name="admin" value="admin">
                  <input type="hidden" name="cgi" value="skins.pl">
                  <input type="hidden" name="uid" value="$FORM{'uid'}">
                  <input type="hidden" name="skin" value="$key">
                  Default Skin <input type="checkbox" name="default" value="yes" $default_checked$default_disabled>
                  &nbsp; &nbsp;
                  User Skin Choice <input type="checkbox" name="choice" value="yes" $choice_checked onClick="this.form.submit()">
                  </font>
                  </form></span>
		} if $local;

		$buttons .= qq{ <A HREF="$adminurl&cgi=skins.pl&skin=$key&install=yes&uid=$FORM{'uid'}#$key" class="roll2">install</a> |} if $install;
		$buttons .= qq{ <A HREF="$adminurl&cgi=skins.pl&skin=$key&remove=yes&uid=$FORM{'uid'}#$key" class="roll2">remove</a> |} if $remove;
#		$buttons .= qq{ <A HREF="$adminurl&cgi=skins.pl&skin=$key&restore=yes&uid=$FORM{'uid'}" class="roll2">restore</a> |} if $restore;
		$buttons .= qq{ <A HREF="javascript:restoreSkin('$key','$default_checked','$choice_checked')" class="roll2">restore</a> |} if $restore;
		$buttons .= qq{ <A HREF="javascript:duplicateSkin('$key')" class="roll2">duplicate</a> |} if $local;
#		$buttons .= qq{ <A HREF="javascript:alert('This feature is disabled in demo mode.')" class="roll2">share</a> |} if $local;
#		$buttons .= qq{ <A HREF="javascript:alert('This feature is disabled in demo mode.')" class="roll2">edit</a> |} if $local;
		$buttons .= qq{ <A HREF="$adminurl&cgi=skins.pl&skin=$key&edit=yes&uid=$FORM{'uid'}" class="roll2">edit</a> |} if $local;
      }
		chop($buttons);
		
		my $skin_dir = $skins_dir . '/' . $key;
		
		$buttons = "<$admin_font><font color=red><b>There is a problem with this skin.<br>Please login through FTP to remove the $key skin manually.</b></font></font>" if !$local && -e $skin_dir;
		
		$list .= qq{		
              <tr bgcolor="#eeeeee">
                <td bgcolor="#eeeeee" align=left>
                <a name="$key">
	          <img src="$image" align=left border=0 vspace=3 hspace=10 width=150>
                  <$admin_font><b>$key</b></font><br>
                  <$admin_font>$description<br></font><br>
                  <center>$buttons</center>
                  $boxes
                 </td>
               </tr>
		};
	}

	$list .= qq{
              <tr bgcolor="#eeeeee">
                <td bgcolor="#eeeeee" align=center>
                  <$admin_font><a href="$adminurl&cgi=skins.pl&manual=yes&uid=$FORM{'uid'}" class="roll2">Install New Skins Manually</a></font><br>
                 </td>
               </tr>
	};

	&get_header;
	
	print qq{
<script language="javascript">
function duplicateSkin(skinName) {
        var newName = prompt('New Skin Name?', skinName);

        if (newName) {
        	window.location = '$adminurl&cgi=skins.pl&skin=' + skinName + '&duplicate=yes&name=' + newName + '&uid=$FORM{'uid'}#' + skinName;
        }
}
function restoreSkin(skinName, skinDefault, skinChoice) {
        var doRestore = confirm('Are you sure you want to restore this skin? Any changes you have made to this skin will be lost.');

        if (doRestore) {
        	window.location = '$adminurl&cgi=skins.pl&skin=' + skinName + '&default=' + skinDefault + '&choice=' + skinChoice + '&restore=yes&uid=$FORM{'uid'}#' + skinName;
        }
}
</script>
<center>
<table border="0" width="100%" cellspacing=0 cellpadding=0 bgcolor="#000000">
  <tr>
    <td>
      <table border="0" width="100%" cellspacing=1 cellpadding=0>
        <tr bgcolor="#ffcc00">
          <td>
            <table border="0" width="100%" cellspacing=0 cellpadding=4>
              <tr>
                <td><$admin_big_font><b>ImageFolio Skins Manager</b></font></td>
                <td align=right><$admin_big_font><b>Menu</b></font></td>
              </tr>
            </table>
          </td>
        </tr>
        <tr bgcolor="#ffffff">
          <td valign=top>
            <table border=0 cellspacing=1 cellpadding=5 width="100%">

	};


	if ($error_display) {
		print qq{
              <tr bgcolor="#eeeeee">
                <td bgcolor="#eeeeee" align=center>
                  <$admin_font><font color=red><b>$error_display</b></font></font><br>
                 </td>
               </tr>
		};
	}		
	
	print $list;
              
	print qq{
            </table>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
	};

	&get_footer;
	
	exit;
}

sub uncompress_skin {
   my ($uc_file, $uc_path, $uc_save, $uc_dl) = @_;
   my $this_skin_name = $uc_file;
   $this_skin_name =~ s!^.*(\\|\/)!!;
  ($this_skin_name) = $this_skin_name =~ m,^(.*)\.\w+$,;
   if ($uc_file =~ /.zip$/i) {
      require Archive::Zip;
      my $ic_zip = Archive::Zip->new();
      $ic_zip->read("$uc_file");
      my @members = $ic_zip->memberNames();
      foreach $member (@members) {
         $ic_zip->extractMember($member, "$uc_path/$member");
      }
      if (!$uc_save) {
         unlink("$uc_file");
      }
   }
   elsif ($uc_file =~ /.skin$/i) {
      $uc_dl =~ s/\.skin$/\.zip/ig;
      $uc_dl =~ s/\/tar\//\/zip\//ig;
      if (-e "/usr/local/bin/tar") {$info_TAR = "/usr/local/bin/tar";}
      elsif (-e "/usr/bin/tar") {$info_TAR = "/usr/bin/tar";}
      elsif (-e "/usr/local/tar") {$info_TAR = "/usr/local/tar";}
      elsif (-e "/bin/tar") {$info_TAR = "/bin/tar";}
      if (!$info_TAR) { $info_TAR = `which tar`;}
      if ($info_TAR) {
         system "$info_TAR -xzf $uc_file -C $uc_path";
         if (!$uc_save) {
            unlink("$uc_file");
         }
      }
#      unless (-e "$uc_path/$this_skin_name/config_skin.pl") {
#         require Archive::TarGzip;
#         Archive::TarGzip->untar( {tar_file=>"$uc_file", dest_dir=>"$uc_path"} );
#      }
   }



   my @directories = ("$uc_path/$this_skin_name");
   my $totaldir = 1;

   for ($i=0; $i<$totaldir; $i++) {
      $directory = @directories[$i];
      opendir(DIR,$directory);
      my @listings = readdir(DIR);
      closedir(DIR);

      foreach my $listing (@listings) {
         next if $listing =~ /^\.\.?$/;
         my $fullpath = "$directory/$listing";
         if (-d $fullpath) {
            $totaldir++;
            push(@directories,$fullpath);
            chmod(0777,$fullpath);
         }
         else {
            chmod(0666,$fullpath);
         }
      }
   }

   unless (-e "$uc_path/$this_skin_name/config_skin.pl") {
      my $er_msg = qq|<table width="500" border="0" cellspacing="0" cellpadding="0">Were unable to install the skin for you. Please follow these steps to download, upload and install the skin manually:<br><br><ol><li>Download <a href="$uc_dl">this</a> file.</li><li>Unzip it and upload the containing files with FTP into the "skins/$this_skin_name" directory.</li><li>Set the permission to writable (CHMOD 777) on ALL the files/directories you just uploaded.</li><li>Click <a href="$adminurl&cgi=skins.pl&uid=$FORM{'uid'}&ct=$current_time#$this_skin_name">here</a> to finish the installation.</li></ol></td></tr></table>|;
      &Error($er_msg);
   }
}

sub skin_dir_copy {
   my ($skin_from_dir, $skin_target_dir) = @_;
   my @skin_from_dirs = ($skin_from_dir);
   my @skin_target_dirs = ($skin_target_dir);
   my $totaldir = 1;

   for ($i=0; $i<$totaldir; $i++) {
      $skin_from_dir = @skin_from_dirs[$i];
      $skin_target_dir = @skin_target_dirs[$i];
      mkdir ("$skin_target_dir", "0777");
      chmod(0777,"$skin_target_dir");
      opendir(DIR,$skin_from_dir);
      my @listings = readdir(DIR);
      closedir(DIR);

      foreach my $listing (@listings) {
         next if $listing =~ /^\.\.?$/;
         my $from_fullpath = "$skin_from_dir/$listing";
         my $target_fullpath = "$skin_target_dir/$listing";
         if (-d $from_fullpath) {
            $totaldir++;
            push(@skin_from_dirs,$from_fullpath);
            push(@skin_target_dirs,$target_fullpath);
         }
         else {
            &File::Copy::copy ($from_fullpath, $target_fullpath);
            chmod(0777,$target_fullpath);
         }
      }
   }
}

1;
