#!/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::Init;

# load modules
use strict;
use IT::Globals;

# ----------------------------------------------------------------------------
# Function    : loadCustomPatches
# Description : load optional customPatches.pl file that is used to adjust
#               encironment, etc settings from misconfigured webservers.
# Usage       : &IT::App::Init::loadCustomPatches("customPatches.pl");
# Usage       : &IT::App::Init::loadCustomPatches("../customPatches.pl");
# ----------------------------------------------------------------------------

sub loadCustomPatches {
  my $customCodeFile   = shift || die "no custom patches file specified!";
  my $absoluteFilepath = IT::File::makeRelativePathsAbsolute($customCodeFile, $CGIDIR);

  if (-e $absoluteFilepath) {
    require $absoluteFilepath;
  }

}

# ----------------------------------------------------------------------------
# Function    : appInit
# Description : call module init() routines, determine server info, setup global vars,
#               load libraries, define databases, etc
# Usage       : &IT::App::Init::appInit();
# ----------------------------------------------------------------------------

sub appInit {

  ### NOTE: Always call application init routine first to define extra settings fields

  # Load config.ini
  $INI = &IT::File::loadINI("$CGIDIR/config.ini");

  # Get datadir
  unless ($INI->{'dataDir'}) { die("data directory isn't defined in INI file!");  }
  $DATADIR = &IT::File::makeRelativePathsAbsolute($INI->{'dataDir'}, $CGIDIR);
  $DATADIR = &IT::File::cleanPath($DATADIR);
  unless (-d $DATADIR)       { die("data directory '$INI->{'dataDir'}' doesn't exist!"); }

  # load admin settings
  $SETTINGS_DATAFILE = "$DATADIR/settings.dat.cgi";
  $SETTINGS          = &IT::App::Menu::Admin::loadAdminSettingsFromFile();
  $TABLE_PREFIX      = $SETTINGS->{'tablePrefix'};
  $SCHEMA_FILEPATH   = "$DATADIR/database.schema.dat.cgi";

  # load cookies
  $COOKIE       = &IT::Cookie::getCookies();

  # error checking
  die("This program requires Perl v5.004 or better (Your version: Perl $])\n") if ($] < 5.004);
  die("This program can only be run through a web server.\n") if not $ENV{'SCRIPT_NAME'};
  if (ord("Ą") != 161) {  # error if corrupt by mac ftp upload
    die "Warning: Program corrupted during upload!<br/>\n This is usually caused by Mac FTP clients that have an \"Translate ISO characters\" setting enabled.<p>If you are using a Mac, try disabling this setting and re-uploading all the files, otherwise, contact support for assistance.";
  }
  if ($ENV{'MOD_PERL'} && !$INI->{'allowModPerl'}) {   # error if mod_perl enabled
    die "Program doesn't support mod_perl!<br/>\nYour server is running $ENV{MOD_PERL}<br><br>This program doesn't support mod_perl.  Please ask your server administrator to disable mod_perl for this program.";
  }

  my @errors;
  if ($SETTINGS->{'isInstalled'}) {
    unless (-d $SETTINGS->{'website_root_dir'}) { push @errors, "Invalid 'Website Root Directory': $SETTINGS->{'website_root_dir'}"; }
    unless (-d $SETTINGS->{'upload_dir'})       { push @errors, "Invalid 'Upload Directory': $SETTINGS->{'upload_dir'}"; }
    unless (-d $SETTINGS->{'publish_dir'})      { push @errors, "Invalid 'Publish Directory': $SETTINGS->{'publish_dir'}"; }
    if ($SETTINGS->{'send_mail_with'} eq 'SENDMAIL' &&
        !-f $SETTINGS->{'sendmail_path'})       { push @errors, "Invalid 'Sendmail Path': $SETTINGS->{'publish_dir'} (file doesn't exist)"; }
    if (@errors) {
      &IT::App::alert("<b>The following settings need to be updated in: Admin &gt; Server Settings:</b>", 'keepHTML');
      my $errors = join "\n", @errors;
      &IT::App::alert($errors);
    }
  }

  ### Misc Settings
  $|=1;                                         # Unbuffer output
  $^T = time();                                 # set $^T for mod_perl
  binmode(STDOUT);                             # comment for remote debugger to work
  # binmode - when we say \n we mean \x0A, not \x0D\x0A
  umask oct(000);                               # set umask for any files we create (published and uploaded)

  ### Initialize IT Modules

  &IT::Error::init({                      # initialize error FIRST
    'ERROR_LOG_FILEPATH' => "$DATADIR/error.log",
  });

  &IT::FileLock::init({                   # initialize filelocking SECOND
    'FILELOCK_FILEPATH' => "$DATADIR/filelock.lock",
  });

  &IT::App::Menu::Admin::init({
    'DEFINE_GLOBAL_PLACEHOLDERS' => \&main::defineGlobalPlaceholders,
  });

  &IT::DB::init($SCHEMA_FILEPATH);

  # load form input
  eval { &IT::ReadForm::init({
    'ALLOW_UPLOADS'        => 1,
    'UPLOAD_DIR'           => $SETTINGS->{'upload_dir'},
    'DISABLE_CODE_BLOCKS'  => $SETTINGS->{'disable_php_asp_code_from_input'},
  })};
  if ($@ && $SETTINGS->{'isInstalled'}) { &IT::App::alert("$@"); }  # display readform permissions errors
  &IT::ReadForm::readForm();  # sets globals: $FORM, $FORM_ARRAYS, and $FORM_UPLOADS


  my @templateDirs;
  push @templateDirs, &IT::File::makeRelativePathsAbsolute($INI->{'templateDir'}, $CGIDIR);   # program specific templates
  push @templateDirs, &IT::File::makeRelativePathsAbsolute($INI->{'templateDir2'}, $CGIDIR) if $INI->{'templateDir2'};

  &IT::Template::init({
    'TEMPLATE_DIRS'      => \@templateDirs,
    'OUTPUT_ID_COMMENTS' => $SETTINGS->{'displayTemplateIdTags'},
  });

  eval { &IT::SSIResolver::init({
    'SSI_PARSING'                            => $SETTINGS->{'dynamicSSIparsing'},
    'SERVER_RESOLVED_SSI_HTTP_AUTH_REQUIRED' => $SETTINGS->{'serverResolvedSSI_httpAuthRequired'},
    'SERVER_RESOLVED_SSI_HTTP_AUTH_USERNAME' => $SETTINGS->{'serverResolvedSSI_httpAuthUsername'},
    'SERVER_RESOLVED_SSI_HTTP_AUTH_PASSWORD' => $SETTINGS->{'serverResolvedSSI_httpAuthPassword'},
    'SERVER_RESOLVED_SSI_TEMPDIR_PATH'       => $SETTINGS->{'publish_dir'},
    'SERVER_RESOLVED_SSI_TEMPDIR_URL'        => $SETTINGS->{'publish_url'},
    'SERVER_RESOLVED_SSI_TEMPFILE_EXT'       => $SETTINGS->{'serverResolvedSSI_tempFileExtension'},
    'SERVER_RESOLVED_SSI_COOKIES_TO_SEND'    => $COOKIE,
    'EMULATED_SSI_DOCUMENT_ROOT'             => $SETTINGS->{'website_root_dir'},
    'EMULATED_SSI_USING_VIRTPATHS'           => $SETTINGS->{'emulatedSSI_usingVirtualDirs'},
    'EMULATED_SSI_VIRTPATHS_TO_FILEPATHS'    => $SETTINGS->{'emulatedSSI_virtualDirsToFilepaths'},
  })};
  if ($@ && $SETTINGS->{'isInstalled'}) { &IT::App::alert("Unable to initialize SSIResolver Module! (Check settings)"); }

  &IT::App::init({
    'LOGOFF_URL_REDIRECT' => $SETTINGS->{'logoff_url'},
    'HELP_URL'            => $SETTINGS->{'help_url'},
  });

  &IT::Date::init({
    'SHORT_MONTH_NAMES'   => $SETTINGS->{'short_month_names_array'},
    'FULL_MONTH_NAMES'    => $SETTINGS->{'long_month_names_array'},
    'SHORT_WEEKDAY_NAMES' => $SETTINGS->{'short_weekday_names_array'},
    'FULL_WEEKDAY_NAMES'  => $SETTINGS->{'long_weekday_names_array'},
    'SHORT_AMPM_NAMES'    => $SETTINGS->{'short_am_pm_names_array'},
    'FULL_AMPM_NAMES'     => $SETTINGS->{'long_am_pm_names_array'},
    'ORDINALS'            => $SETTINGS->{'ordinals_array'},
    'TIME_FORMAT'         => $SETTINGS->{'time_format'},
    'DATE_FORMAT'         => $SETTINGS->{'date_format'},
    'DATETIME_FORMAT'     => $SETTINGS->{'datetime_format'},
  });

  eval { &IT::Email::init({
    'SEND_MAIL_WITH'         => $SETTINGS->{'send_mail_with'},
    'SENDMAIL_PATH'          => $SETTINGS->{'sendmail_path'},
    'SMTP_HOST'              => $SETTINGS->{'smtp_hostname'},
    'POP3_LOGIN_BEFORE_SMTP' => $SETTINGS->{'pop3_login_required_before_smtp'},
    'POP3_HOST'              => $SETTINGS->{'pop3auth_hostname'},
    'POP3_USERNAME'          => $SETTINGS->{'pop3auth_username'},
    'POP3_PASSWORD'          => $SETTINGS->{'pop3auth_password'},
  })};
  if ($@ && $SETTINGS->{'isInstalled'}) { &IT::App::alert("Unable to initialize Email Module! (Check settings)"); }

  eval { &IT::Upload::init({
    'UPLOAD_DIR' => $SETTINGS->{'upload_dir'},
  })};
  if ($@ && $SETTINGS->{'isInstalled'}) { &IT::App::alert("Unable to initialize Upload Module! (Check settings)"); }

  # define global placeholders
  &main::defineGlobalPlaceholders() if defined &main::defineGlobalPlaceholders;


}

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

