#!/usr/bin/perl
# ----------------------------------------------------------------------------
# This software is Copyright (C) 2007, All Rights Reserved
# ----------------------------------------------------------------------------
# This program is protected by local and international copyright laws. Any
# use of this program is subject to the the terms of the license agreement
# included as part of this distribution archive. Any other uses are strictly
# prohibited without the written permission of the Vendor and all
# other rights are reserved.
# -----------------------------------------------------------------------------
# Warning : Modifying this program violates your license agreement!
# -----------------------------------------------------------------------------

package IT::App::Menu::Admin::TemplateEditor;

use IT::Globals;

use strict;

# ------------------------------------------------------------------------------
# Function    : main
# Description :
# Usage       : &IT::App::Menu::Admin::TemplateEditor::main();
# ------------------------------------------------------------------------------

sub main {

  &IT::App::demoModeAlertAndAction("Template Editor is disabled in demo mode.", sub { &IT::App::Menu::Admin::showMenu('homepage'); });

  if    ($FORM->{'load'})     { &editTemplate(); }
  elsif ($FORM->{'download'}) { &downloadTemplate(); }
  elsif ($FORM->{'create'})   { &createTemplate(); }
  elsif ($FORM->{'erase'})    { &eraseTemplate(); }
  elsif ($FORM->{'save'})     { &saveTemplate(); }
  else                        { &editTemplate(); }

}

# ----------------------------------------------------------------------------
# Function    : editTemplate
# Description :
# Usage       : &editTemplate($errors, $selectedTemplate);
# ----------------------------------------------------------------------------

sub editTemplate {
  my $errors = shift;
  my $selectedTemplate = shift;
  my $placeholders = {};

  # display errors
  if ($errors) { &IT::App::alert($errors); }

  # get selected template
  if (!$selectedTemplate && $FORM->{'load'}) { $selectedTemplate = $FORM->{'selectedTemplate'}; }

  # get template list
  $placeholders->{'templateOptions'} = "";
  my $templateArray = &IT::Template::getTemplateList('relativePaths');
  foreach my $template (sort @$templateArray) {
    if ($template =~ m|admin/menus/|) { next; }
    if ($template =~ m|admin/popups/|) { next; }
    if ($template =~ m|\.zip$|) { next; }
    $placeholders->{'templateOptions'} .= qq|<option>$template</option>\n|;
  }

  # load selected template
  $placeholders->{'newFilepath'}     = $FORM->{'newFilepath'};
  $placeholders->{'currentTemplate'} = '';
  $placeholders->{'templateContent'} = '';
  my $templatePath = &IT::Template::templateExists($selectedTemplate) if $selectedTemplate;
  if    ($FORM->{'load'}   && !$selectedTemplate) { &IT::App::alert("No template selected!"); }
  elsif ($selectedTemplate && !$templatePath)     { &IT::App::alert("Couldn't find template '$selectedTemplate'!"); }
  elsif ($selectedTemplate && !-w $templatePath)  { &IT::App::alert("Template isn't writable, change permissions!"); }
  elsif ($selectedTemplate) {
    $placeholders->{'currentTemplate'} = $selectedTemplate;
    $placeholders->{'templateContent'} = &IT::File::readFile($templatePath, 'WITHOUT_FILELOCKING');
  }

  ### display page
  &IT::App::displayInterface({
    'template'           => "admin/menus/admin/templateEditor.html",
    'templatecell'       => "editTemplate",
    'selectedMenuOption' => 'admin',
    'placeholders'       => $placeholders,
  });

}

# ----------------------------------------------------------------------------
# Function    : downloadTemplate
# Description :
# Usage       : &downloadTemplate();
# Notes       : IE5.5 Issues: http://support.microsoft.com/kb/q279667/
#               IE workaround: http://www.bme.ie/resource/php/phpapp_filedownload_en.htm
# ----------------------------------------------------------------------------

sub downloadTemplate {
  my $templatePath = &IT::Template::templateExists($FORM->{'selectedTemplate'}) if $FORM->{'selectedTemplate'};

  # error checking
  if (!$FORM->{'selectedTemplate'}) { &editTemplate("No template selected!"); }
  if (!$templatePath)               { &editTemplate("Couldn't find template '$FORM->{'selectedTemplate'}'!"); }

  # generate template filename
  my $localTime  = &IT::App::Common::getTimeAdjustedToMatchGMT( time );
  my $dateString = &IT::Date::formatDate("(MMM d, yyyy - h.mm.sstt)", $localTime); # eg: (Jan 4 2006, 1.39PM), this format will sort by date in directory lists
  my $filename = $FORM->{'selectedTemplate'};
  $filename =~ s|[\\\/]+|_|g;
  $filename =~ s/\.([^\.]+)$/ $dateString.$1/ || die "Couldn't insert datestring into backup filename '$filename'!";

  # download template
  my $templateContent = &IT::File::readFile($templatePath, 'WITHOUT_FILELOCKING');
  my $contentBytes    = length $templateContent;
#  print "Content-Type: application/x-force-download\n";  # alternative if octet stream doesn't work
  print "Content-Type: application/octet-stream\n";
  print "Content-Length: $contentBytes\n";
  print "Content-Disposition: attachment; filename=\"$filename\"\n\n";
  print $templateContent;
  exit;

}

# ----------------------------------------------------------------------------
# Function    : createTemplate
# Description :
# Usage       : &IT::App::Menu::Admin::TemplateEditor::createTemplate();
# ----------------------------------------------------------------------------

sub createTemplate {
  my $currentTemplate = $FORM->{'newFilepath'};
  my $templateDir1    = &IT::File::makeRelativePathsAbsolute($INI->{'templateDir'}, $CGIDIR);
  my $templatePath    = &IT::File::cleanPath("$templateDir1/$currentTemplate");
  my $templateContent = $FORM->{'templateContent'};

  # error checking
  if (!$currentTemplate)         { &editTemplate("Please enter a filepath for the new template."); }
  if (&IT::Template::templateExists($currentTemplate) ||  # template might exists in 2nd template dir even if filepath is different
      -e $templatePath)          { &editTemplate("A file or directory already exists with that filepath."); }
  if ($templatePath !~ /\.\w+$/) { &editTemplate("New template files must have an extension such as .html or .txt"); }

  # create directory if needed
  my $parentDir = &IT::File::getParentDirectory($templatePath);
  unless (-e $parentDir) {
    &IT::File::createDirPath($parentDir) || &editTemplate("Couldn't create '$parentDir' : $!");
  }

  # create template
  &IT::FileLock::getLock('exclusive');
  my $tempFile = "${templatePath}.temp";
  &IT::File::writeFile($tempFile, $templateContent) || &editTemplate("Unable to write file '$tempFile': $!");
  rename($tempFile, $templatePath) || &editTemplate("Couldn't rename file '$tempFile' to '$templatePath'! $!\n");
  &IT::FileLock::releaseLock();

  # blank out newFilepath
  &IT::Template::setGlobalPlaceholder('newFilepath', '');

  # return to edit page
  &editTemplate("Template created: $currentTemplate", $currentTemplate);
  exit;

}

# ----------------------------------------------------------------------------
# Function    : eraseTemplate
# Description :
# Usage       : &IT::App::Menu::Admin::TemplateEditor::eraseTemplate();
# ----------------------------------------------------------------------------

sub eraseTemplate {
  my $currentTemplate = $FORM->{'currentTemplate'};
  my $templatePath    = &IT::Template::templateExists($currentTemplate) if $currentTemplate;

  # error checking
  if (!$currentTemplate) { &editTemplate("No template was selected to erase."); }
  if (!$templatePath)    { &editTemplate("Couldn't find template '$currentTemplate'!"); }

  # erase template
  unlink($templatePath) || &editTemplate("Couldn't erase '$templatePath'. $!");

  # return to edit page
  &editTemplate("Template erased: $currentTemplate", '');
  exit;

}

# ----------------------------------------------------------------------------
# Function    : saveTemplate
# Description :
# Usage       : &IT::App::Menu::Admin::TemplateEditor::saveTemplate();
# ----------------------------------------------------------------------------

sub saveTemplate {
  my $currentTemplate = $FORM->{'currentTemplate'};
  my $templateContent = $FORM->{'templateContent'};
  my $templatePath    = &IT::Template::templateExists($currentTemplate) if $currentTemplate;

  # remove "<!-- (CODE BLOCK DISABLED)" code that was added to disable PHP/ASP blocks
  $templateContent = &IT::ReadForm::reEnableDisabledCodeBlocks($templateContent);

  # error checking
  if (!$currentTemplate) { &editTemplate("You must select a template to modify before saving."); }
  if (!$templatePath)    { &editTemplate("Couldn't find template '$currentTemplate'!"); }

  # save template
  &IT::FileLock::getLock('exclusive');

  my $tempFile = "${templatePath}.temp";
  &IT::File::writeFile($tempFile, $templateContent) || &editTemplate("Unable to write file '$tempFile': $!");
  rename($tempFile, $templatePath) || &editTemplate("Couldn't rename file '$tempFile' to '$templatePath'! $!\n");

  &IT::FileLock::releaseLock();

  # return to edit page
  &editTemplate("Template saved: $currentTemplate", $currentTemplate);
  exit;

}

# ----------------------------------------------------------------------------
# end of file
1;

