use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);

require "../config/main.pl";
require "../config/variables.pl";
require "../write_back.pl";

# hopefully not being overly cynical here...
$program="the Web Wizard";
$company="My-hosts";
$support_email="support\@my-hosts.com";

$user_details="/home/vhosts/default/data/";
$user_details.="/" unless ($user_details =~ m~/$~); # ensure trailing /
$templatepos="/templates";
$hash="You really do not want passwords to be in plain text";
$default_cgi="/cgi-bin/.admin/templates";
$image_dir="http://hosted.my-hosts.com/gfx";

#$servername=$ENV{HTTP_HOST};
$servername="cluster1.my-hosts.com";
#$serverroot=$ENV{DOCUMENT_ROOT};
$serverroot="/home/vhosts/default/webpages/";
$serverroot=$1 if ($serverroot=~ m~^(.*)/$~);

$homesite="";
$template="";
$colourscheme="";
$created=0;

$uniqueid =substr("00".(gmtime)[5],-2,2);
$uniqueid.=substr("00".((gmtime)[4]+1),-2,2);
$uniqueid.=substr("00".(gmtime)[3],-2,2);
$uniqueid.=substr("00".(gmtime)[2],-2,2);
$uniqueid.=substr("00".(gmtime)[1],-2,2);
$uniqueid.=substr("00".(gmtime)[0],-2,2);
$uniqueid.=substr("0000".(int(rand(1000))),-4,4);

sub header {
  my $header_title=$_[0];
  my $cookie_make=$_[1];
  my $header_section=$_[2];
  if ($cookie_make eq "in") {
    cookie_make(0,"Wed, 16-Jun-2010 00:00:00 GMT","");
    #cookie_set();
  } elsif ($cookie_make eq "out") {
    cookie_make(1,"Wed, 31-Dec-1997 00:00:00 GMT","http://$servername/");
    #cookie_unset();
  } elsif ($cookie_make eq "wipe") {
    cookie_make(2,"Wed, 31-Dec-1997 00:00:00 GMT","");
    #cookie_wipe();
  } else {
    if ($cookie_make eq "refresh") {
      print "Location: $default_cgi/edit\n";
    }
    print "Content-type: text/html\n\n";
  }
  cookie_read();

  if ($template ne "") {
    $templateroot="$serverroot/templates/$template/schemes";
#    $templatedir="${serverroot}$templateroot";
    $templatedir="$templateroot";
  }

  if ($header_section eq "edit_page") {
    $bodytext=stream("ssi/header2.inc",1);
    $page_to_edit=param("page");
  } else {
    $bodytext=stream("ssi/header.inc",1);
  }
  $bodytext=~ s/\[wiz-host-company\]/$company/sig;
  $bodytext=~ s/\[wiz-section\]/$header_title/sig;
  

  if ($cookie_make eq "wipe") {
    $bodytext=~ s/\[wiz-logged-in-as\]/[logging&nbsp;out]/sig;
    $bodytext=~ s/\[wiz-log-in-or-out\]/&nbsp;[logging&nbsp;out]&nbsp;/sig;
  } else {
    $bodytext=~ s/\[wiz-logged-in-as\]/$logged_in_as/sig;
    if ($user eq "") {
      $bodytext=~ s/\[wiz-log-in-or-out\]/&nbsp;<a href="$default_cgi\/login">Log&nbsp;in<\/a>&nbsp;/sig;
    } else {
      $bodytext=~ s/\[wiz-log-in-or-out\]/&nbsp;<a href="$default_cgi\/logout">Log&nbsp;out<\/a>&nbsp;/sig;
    }
  }
  

  $bodytext=~ s/\[wiz-edit-page\]/&nbsp;<a href="$default_cgi\/edit_page?page=$page_to_edit">Edit Page<\/a>&nbsp;/sig;
  if ($header_section eq "home") {$section_colour="FF3300"}else{$section_colour="999999"} ;
  $bodytext=~ s/\[wiz-is-home\]/$section_colour/sig;
  if (($header_section eq "login") || ($header_section eq "logout")) {$section_colour="FF3300"}else{$section_colour="999999"};
  $bodytext=~ s/\[wiz-is-login\]/$section_colour/sig;
  if ($header_section eq "edit") {$section_colour="FF3300"}else{$section_colour="999999"} ;
  $bodytext=~ s/\[wiz-is-edit\]/$section_colour/sig;
  if ($header_section eq "edit_page") {$section_colour="FF3300"}else{$section_colour="999999"} ;
  $bodytext=~ s/\[wiz-is-edit-page\]/$section_colour/sig;
  if ($header_section eq "add") {$section_colour="FF3300"}else{$section_colour="999999"} ;
  $bodytext=~ s/\[wiz-is-add\]/$section_colour/sig;
  if ($header_section eq "upload") {$section_colour="FF3300"}else{$section_colour="999999"} ;
  $bodytext=~ s/\[wiz-is-upload\]/$section_colour/sig;
  
  if ($cookie_make eq "wipe") {
    $bodytext=~ s~</title>~</title>\n<meta http-equiv="refresh" content="5; URL=/index.html">~si;
  }
  
  if ($cookie_make eq "in") {
    $bodytext=~ s~</title>~</title>\n<meta http-equiv="refresh" content="3; URL=$default_cgi/edit">~si;
  }

  print $bodytext;
}

sub footer {
  stream("ssi/footer.inc",0);
}

sub stream {
  my $streamfile = $_[0];
  my $outputtype = $_[1];
  # 0=output, 1=return
  $bodytext="";
  open STREAM, "<$serverroot/$streamfile";
  while ($line = <STREAM>) {
    if ($outputtype == 0) {
      print $line;
    } else {
      $bodytext.=$line;
    }
  }
  close STREAM;
  return $bodytext if ($outputtype == 1);
}

sub page_name {
  my $read_name=$_[0];
  $read_name=~ s/\.html?//ig;
  #$read_new_name=ucfirst(lc($read_name));
  $read_new_name=ucfirst($read_name);
  $read_new_name=~ s/_/ /g;
  $read_new_name="Home page"  if ($read_name eq "index");
  $read_new_name="C.V."       if ($read_name eq "cv");
  $read_new_name="What's new" if ($read_name eq "whats_new");
  $read_new_name="IT"         if ($read_name eq "it");
  return $read_new_name;
}

sub nowdate {
  convert_time(time());
    $year=$temp_year;
   $month=$temp_month;
     $day=$temp_monthdate;
 $weekday=$temp_weekday;
    $hour=$temp_hour;
  $minute=$temp_minute;
  $second=$temp_second;
    $time=$temp_time;
$now_date=$date=$temp_now_date;

  $pubdate=substr($temp_weekday,0,3) . ", " . sprintf("%-.2d",((localtime(time))[3])) . " " . substr($temp_month,0,3) . " $temp_year";
  $lastupdate="<!-- lastupdate -->$temp_month $temp_monthdate $temp_year $temp_time<!-- / lastupdate -->";
}

sub file_date {
  my $file_to_read=$_[0];
  $mtime=(stat($file_to_read))[9];
  convert_time($mtime);
  $file_date = "$weekday, $monthdate $month $year";
  convert_time(time());
  $now_date = $temp_now_date;
  $time=$temp_time;
  
  if ($now_date ne $file_date) {
    $file_date="$time (<small>$file_date</small>)";
  } else {
    $file_date="<b><font color=\"#ffffff\"><span style=\"color:white\">$time</span></font></b>";
  }
}

sub convert_time {
my $timestamp=$_[0];
  $temp_weekday=(qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday))[(localtime($timestamp))[6]];
  $temp_month=(qw(January February March April May June July August September October November December))[(localtime($timestamp))[4]];
  $temp_monthdate=(qw(unknown 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th 31st))[(localtime($timestamp))[3]];
  $temp_year=1900+(localtime($timestamp))[5];
  $temp_hour  =sprintf ("%-.2d",((localtime(time))[2]));
  $temp_minute=sprintf ("%-.2d",((localtime(time))[1]));
  $temp_second=sprintf ("%-.2d",((localtime(time))[0]));
  $temp_isdst=(localtime($timestamp))[8];
  $temp_time="$temp_hour:$temp_minute";
  $temp_now_date = "$temp_weekday, $temp_monthdate $temp_month $temp_year";
}

sub cookie_read {
  $tempuser     = cookie("wizarduser");
  $temppasshash = cookie("wizardpass");
  get_user_details($tempuser);

  if ( (defined($tempuser)) && (defined($temppasshash)) ) {
    if ($passhash eq $temppasshash) {
      $logged_in_as="Logged in as <font color=\"#CC3300\">$user</font>\n<br><a href=\"$default_cgi/logout\">Log out</a>\n";
      $user=$tempuser;
      $passhash=$temppass;
    } else {
      # passwords do not match - go away!
      $user="";
      $pass="";
      $passhash="";
      $homesite="";
      $logged_in_as="Incorrect details. <a href=\"$default_cgi/login\">Log in</a>.\n";
    }
  } else {
    $user="";
    $pass="";
    $passhash="";
    $homesite="";
    $logged_in_as="Not <a href=\"$default_cgi/login\">logged in</a>.\n";
  }
}

sub cookie_make {
  my $cookie_type=$_[0];
  my $expires=    $_[1];
  my $redirect=   $_[2];
  print "Content-type: text/html\n";
  if ($cookie_type == 0) {
    print "Set-Cookie: wizarduser=$loginname; path=/; expires=$expires;\n";
    print "Set-Cookie: wizardpass=$passhash; path=/;  expires=$expires;\n";
  } else {
    print "Set-Cookie: wizarduser=##unset; path=/; expires=$expires;\n";
    print "Set-Cookie: wizardpass=##unset; path=/; expires=$expires;\n";
  }
  print "Cache-Control: must-realidate\n";
  print "Cache-Control: no-cache\n";
  print "Pragma: no-cache\n";
  print "Expires: 0\n";
  convert_time(time());
  $last_mod=substr($temp_weekday,0,3) . ", " . sprintf("%-.2d",((localtime(time))[3])) . " " . substr($temp_month,0,3) . " $temp_year $temp_hour:$temp_minute:$temp_second ";
  if ($temp_isdst == 0) {
    $last_mod.="GMT";
  } else {
    $last_mod.="BST";
  }
  print "Last-Modified: $last_mod\n";
  print "Location: $redirect\n" if ($redirect ne "");
  print "\n";
}

sub headline {
  my $headline_text   =$_[0];
  my $headline_colour =$_[1];
  my $headline_align  =$_[2];
  my $headline_explain=$_[3];
  my $headline="<h2";
  if ($headline_align ne "") {
    $headline.=" align=\"$headline_align\"";
  }
  $headline.=">";
  my $print_colour="";
  if ($headline_colour ne "") {
    $print_colour="#ff0000" if ($headline_colour eq "red");
    $print_colour="#00CC00" if ($headline_colour eq "green");
    $print_colour="#0000CC" if ($headline_colour eq "blue");
    $print_colour="#CC9900" if ($headline_colour eq "yellow");
    $print_colour="#00BBCC" if ($headline_colour eq "cyan");
    $print_colour="#CC00CC" if ($headline_colour eq "magenta");
    $print_colour="#000000" if ($headline_colour eq "black");
    $print_colour="#ffffff" if ($headline_colour eq "white");
    $print_colour="#FF9900" if ($headline_colour eq "orange");
    $print_colour="#9900CC" if ($headline_colour eq "purple");
    $headline.="<font color=\"$print_colour\">" if ($print_colour ne "");
  }
  $headline.=$headline_text;
  $headline.="</font>" if ($print_colour ne "");
  $headline.="</h2>\n";
  print $headline;
  print "$headline_explain\n" if ($headline_explain ne "");
}

sub get_user_details {
  my $user_to_fetch=$_[0];
  $pass="";
  $homesite="";
  $baseurl="";
  # check $tempuser name, get details for that user, extract password,
  # hash, check they are the same.  Makes sure cookie is not fudged,
  # password has not been changed, gets site location for that user etc.
  $file_to_load="$user_details$user_to_fetch.txt";
  if (-r $file_to_load) {
    $err=0;
    open INPUT, "<$file_to_load" or ($err=1);
    
    if ($err == 0) {
      $user=$user_to_fetch;
      $pass="";
      $homesite="";
      $baseurl="";
      
      while ($line = <INPUT>) {
        chomp $line;
        $pass=$1     if ($line =~ m~^pass:(.+?)$~si);
        $homesite=$1 if ($line =~ m~^homesite:(.+?)$~si);
        $baseurl=$1  if ($line =~ m~^baseurl:(.+?)$~si);
      }
      close INPUT;
      $passhash=crypt($pass,$hash);
  
      $homesite.="/" unless ($homesite =~ m~/$~); # add trailing slash
      $baseurl = $1 if ($baseurl =~ m~^((.*?)/)[^/]+\.[^/]+$~i); # strip index.html et al
      $baseurl.="/" unless ($baseurl =~ m~/$~); # add trailing slash
      $baseurl="http://$baseurl" unless ($baseurl =~ m~^[a-z]+:/~); # add protocol
  
      # fetch other details - colours, scheme etc.
      if (-r "${homesite}.wiz_cols") {
        open DETAILS, "<${homesite}.wiz_cols";
        while ($line = <DETAILS>) {
          if ($line =~ m~^colours:\s+(.*?)$~i) {
            $colourscheme=$1;
          }
        }
      }
      
      if (-r "${homesite}.wiz_style") {
        open DETAILS, "<${homesite}.wiz_style";
        while ($line = <DETAILS>) {
          if ($line =~ m~^template:\s+(.*?)$~i) {
            $template=$1;
          }
        }
      }
      
      if (-e "${homesite}.wiz_track") {
        $created=1;
        $last_major=0;
        read_last_major();
      }
      
      if ($template ne "") {
        $templateroot="$templatepos/$template/schemes";
        $templatedir="${serverroot}$templateroot";
        if (colourscheme ne "") {
          unless (-d "$templatedir/$colourcheme") {
            $colourscheme="";
          }
        }
      }
      
      if (-r "${homesite}.wiz_details") {
        open DETAILS, "<${homesite}.wiz_details";
        while ($line = <DETAILS>) {
          chomp $line;
          if ($line =~ m~^([a-z]+):\s+(.*?)$~i) {
            $command=$1;
            $data=$2;
            $user_longorg     = $data if ($command eq "longorg");
            $user_shortorg    = $data if ($command eq "shortorg");
            $user_contact     = $data if ($command eq "contact");
            $user_address     = $data if ($command eq "address");
            $user_postcode    = $data if ($command eq "postcode");
            $user_phone       = $data if ($command eq "phone");
            $user_fax         = $data if ($command eq "fax");
            $user_email       = $data if ($command eq "email");
            $user_description = $data if ($command eq "description");
            $user_keywords    = $data if ($command eq "keywords");
            $user_link_prefs  = $data if ($command eq "linkprefs");
            
            $user_address =~ s~<br>~\n~sig;
          }
        }
      }
    } else {
      die("Unable to open user file :(");
    }
    
  } else {
    ##$user="";
    ##$pass="";
    ##$passhash="bugger off!";
  }
  # ...or just fudge it ;)
}

sub set_change_date {
  $err=0;
  open OUTPUT, ">${homesite}.wiz_track" or ($err=1);
  if ($err== 1) {
    headline("Error: can't make site marker","red","","The site marker (a file that lets the site creator know that the site has been properly created, and also when the last major upgrade took place) couldn't be created; this means the program will not know that the site has been updated.  Please contact <a href=\"mailto:$support_email\">$company support</a>.");
  } else {
    $last_major=time();
    print OUTPUT $last_major;
    close OUTPUT;
  }
}

sub read_last_major {
my $major_err=0;
open LASTMAJOR, "<${homesite}.wiz_track" or ($major_err = 1);
  if ($major_err == 0) {
    $last_major=<LASTMAJOR>;
    close LASTMAJOR;
  } else {
    $last_major=0;
  }
}

sub nuke_paragraphs {
  undef @para_title;
  undef @para_text;
  undef @para_type;
  undef @para_pic;
  undef @para_align;
  undef @para_caption;
  undef @para_morelink;
}

sub load_paragraphs {
  my $temp_paratype="";
  my $temp_textblock="";
  my $temp_paratext="";
  my $temp_image="";
  my $temp_caption="";
  my $temp_align="";
  my $temp_headline="";
  my $temp_linkurl="";
  my $temp_img_block="";
  my $err=0;
  open INPUT, "<$homesite$page_to_edit" or $err=1;
  if ($err == 0) {
    nuke_paragraphs();
    $text="";
    while ($line = <INPUT>) {
      $text.=$line;
    }
    close INPUT;


    while ($text =~ m~<!-- #BeginEditable "(.*?)" -->\s*(.*?)\s*<!-- #EndEditable -->~sgi) {
      $temp_paratype=$1;
      $temp_textblock=$2;
      $temp_paratext="";
      $temp_image="";
      $temp_caption="";
      $temp_align="";
      $temp_headline="";
      $temp_linkurl="";
      $temp_img_block="";
      
      unless ($temp_textblock =~ m~<!--\s+/\s+image\s+-->~si) {
        $temp_textblock.="<!-- / image -->";
      }

      if ($temp_textblock =~ m~<!--\s+image\s+align="(.*?)"\s+-->(.*?)<!--\s+/\s+image\s+-->~si) {
        $temp_align=$1;
        $temp_img_block=$2;
        if ($temp_align eq "right") {
          if ($temp_textblock =~ m~<h([1-4]).*?>\s*(.*?)\s*</h\1>\s*<table.*?>\s*<tr.*?>\s*<td.*?>\s*(.*?)\s*</td>\s*<td.*?>\s*<!--\s+image~si) {
            $temp_headline=$2;
            $temp_paratext=$3;
            $temp_image=$4;
            if ($temp_img_block =~ m~<img\s+src="(.*?)".*?>~si) {
              $temp_image=$1;
            }
          }

        } elsif ($temp_align eq "left") {
          if ($temp_textblock =~ m~<h([1-4]).*?>\s*(.*?)\s*</h\1>\s*<table.*?>.*?<td>\s*(.*?)</td>\s*</tr>\s*</table>~si) {
            $temp_headline=$2;
            $temp_paratext=$3;
            if ($temp_img_block =~ m~<img\s+src="(.*?)".*?>~si) {
              $temp_image=$1;
            }
          }

        } elsif ($temp_align eq "center") {
          $temp_textblock=~ s/\s*<p align="center">\s*<img/<img/sgi;
          if ($temp_textblock =~ m~<h([1-4]).*?>\s*(.*?)\s*</h\1>\s*(.*?)\s*<!--~si) {
            $temp_headline=$2;
            $temp_paratext=$3;
            if ($temp_img_block =~ m~<img\s+src="(.*?)".*?>~si) {
              $temp_image=$1;
            }
          }
        } else {
          $temp_align="";
        }
      }

      if ($temp_align eq "") {
        if ($temp_textblock =~ m~<h([1-4]).*?>\s*(.*?)\s*</h\1>\s*(.*)\s*$~si){
            $temp_headline=$2;
            $temp_paratext=$3;
        }
#        if ($temp_textblock =~ m~<img\s+src="(.*?)".*?>~si) {
#          $temp_image=$1;
#        }
      }
      

###################      
      if ($temp_textblock =~ m~<!--\s+caption\s+-->\s+(.*?)\s<!--\s+/\s*caption\s+-->~si) {
        $temp_caption=$1;
      }
      if ($temp_textblock =~ m~(<!--\s+link\s+-->\s*<a href="(.*?)">.*?</a>\s*<!--\s+/\s*link\s+-->)~si) {
        $temp_paratext.=$1;
      }
###################

      if ($temp_caption ne "") {
        $temp_caption =~ s~</?small>~~sgi;
        $temp_caption =~ s~</?i>~~sgi;
      }

      if ($temp_paratext =~ m~^(.*?)\s*(<br>)?<!--\s+link\s+-->\s*<a href="(.*?)">.*?</a>\s*<!--\s+/\s*link\s+-->~si) {
        $temp_paratext=$1;
        $temp_linkurl=$3;
      }

      $temp_paratext=~ s/\s$//sgi;
      ##$temp_paratext=~ s/\s*<p align="center">\s*$//sgi;

      push @para_title, $temp_headline;
      push @para_text, $temp_paratext;
      push @para_type, $temp_paratype;
      push @para_pic, $temp_image;
      push @para_align, $temp_align;
      push @para_caption, $temp_caption;
      push @para_morelink, $temp_linkurl;
    }
  } else {
    headline("Error: Unable to open file '".page_name($page_to_edit)."' for reading","red","","The file $page_to_edit could not be opened for reading, and so that page cannot be edited.  Please contact <a href=\"mailto:$support_email\">$company support</a> to rectify this.");
  }
}


sub copy_template_images {
  my $source_dir = "$serverroot/templates/$template/schemes/$colourscheme/gfx";
  my $backup_dir = "$serverroot/templates/$template/gfx";
  unless (-d $source_dir) {
    $source_dir = $backup_dir;
  }
  print "<br>\n";
  if (-d $source_dir) {
    #print "Source exists...<br>\n";
    my $dir_made = 1;
    unless (-d "${homesite}gfx") {
      #print "Creating destination...<br>\n";
      $dir_made = 0;
      system "mkdir ${homesite}gfx" or $dir_made = 0;
      system "chmod 777 ${homesite}gfx" if ($dir_made == 1);
    }
    if ($dir_made == 1) {
      #print "Copying files...<br>\n";
      system "cp -r $source_dir/* ${homesite}gfx/";
      system "chmod -R 777 ${homesite}gfx/*";
    }
  }
}
