F:\WEBSITES\testbed\zipped\yabb_svn_new\branches\2.5.2\cgi-bin\yabb2\Sources\Subs.pl F:\WEBSITES\testbed\zipped\yabb_svn_new\trunk\cgi-bin\yabb2\Sources\Subs.pm
############################################################################### ###############################################################################
# Subs.pl                                                                     # # Subs.pm                                                                     #
  # $Date: 01.05.16 $                                                           #
############################################################################### ###############################################################################
# YaBB: Yet another Bulletin Board                                            # # YaBB: Yet another Bulletin Board                                            #
# Open-Source Community Software for Webmasters                               # # Open-Source Community Software for Webmasters                               #
# Version:        YaBB 2.5.2                                                  # # Version:        YaBB 2.6.12                                                 #
# Packaged:       October 21, 2012                                            # # Packaged:       January 5, 2016                                             #
# Distributed by: http://www.yabbforum.com                                    # # Distributed by: http://www.yabbforum.com                                    #
# =========================================================================== # # =========================================================================== #
# Copyright (c) 2000-2012 YaBB (www.yabbforum.com) - All Rights Reserved.     # # Copyright (c) 2000-2016 YaBB (www.yabbforum.com) - All Rights Reserved.     #
# Software by:  The YaBB Development Team                                     # # Software by:  The YaBB Development Team                                     #
#               with assistance from the YaBB community.                      # #               with assistance from the YaBB community.                      #
############################################################################### ###############################################################################
  # use strict;
  # use warnings;
  no warnings qw(uninitialized once redefine);
  use CGI::Carp qw(fatalsToBrowser);
  use English qw(-no_match_vars);
  our $VERSION = '2.6.12';
   
$subsplver = 'YaBB 2.5.2 $Revision: 1.5 $'; $subspmver = 'YaBB 2.6.12 $Revision: 1717 $';
if ($debug) { &LoadLanguage('Debug'); }  
   
use subs 'exit'; use subs 'exit';
   
$yymain = '';  $yymain       = q{}; 
$yyjavascript = '';  $yyjavascript = q{}; 
$langopt = '';  $langopt      = q{}; 
   
# set line wrap limit in Display. # set line wrap limit in Display.
$linewrap = 80; $linewrap = 80;
$newswrap = 0; $newswrap = 0;
   
# get the current date/time # get the current date/time
$date = int(time() + $timecorrection);  
  $date = int( time() + $timecorrection );
   
# check if browser accepts encoded output # check if browser accepts encoded output
$gzaccept = $ENV{'HTTP_ACCEPT_ENCODING'} =~ /\bgzip\b/ || $gzforce; $gzaccept = $ENV{'HTTP_ACCEPT_ENCODING'} =~ /\bgzip\b/sm || $gzforce;
   
# parse the query string # parse the query string
&readform;  readform(); 
   
$uid = substr($date, length($date) - 3, 3);  $uid = substr $date, length($date) - 3, 3; 
$session_id = $cookiesession_name; $session_id = $cookiesession_name;
   
$randaction = substr($date,0,length($date)-2);  $randaction = substr $date, 0, length($date) - 2; 
   
$user_ip = $ENV{'REMOTE_ADDR'}; $user_ip = $ENV{'REMOTE_ADDR'};
if ($user_ip eq "127.0.0.1") { if ( $user_ip eq '127.0.0.1' ) {
   if    ($ENV{'HTTP_CLIENT_IP'}       && $ENV{'HTTP_CLIENT_IP'}       ne "127.0.0.1") { $user_ip = $ENV{'HTTP_CLIENT_IP'}; }     if ( $ENV{'HTTP_CLIENT_IP'} && $ENV{'HTTP_CLIENT_IP'} ne '127.0.0.1' ) { 
   elsif ($ENV{'X_CLIENT_IP'}          && $ENV{'X_CLIENT_IP'}          ne "127.0.0.1") { $user_ip = $ENV{'X_CLIENT_IP'}; }         $user_ip = $ENV{'HTTP_CLIENT_IP'}; 
   elsif ($ENV{'HTTP_X_FORWARDED_FOR'} && $ENV{'HTTP_X_FORWARDED_FOR'} ne "127.0.0.1") { $user_ip = $ENV{'HTTP_X_FORWARDED_FOR'}; }    }
}     elsif ( $ENV{'X_CLIENT_IP'} && $ENV{'X_CLIENT_IP'} ne '127.0.0.1' ) { 
         $user_ip = $ENV{'X_CLIENT_IP'};
if (-e "$yyexec.cgi") { $yyext = "cgi"; }    }
else { $yyext = "pl"; }     elsif ($ENV{'HTTP_X_FORWARDED_FOR'} 
if (-e "AdminIndex.cgi") { $yyaext = "cgi"; }         && $ENV{'HTTP_X_FORWARDED_FOR'} ne '127.0.0.1' ) 
else { $yyaext = "pl"; }     { 
         $user_ip = $ENV{'HTTP_X_FORWARDED_FOR'};
     }
  }
   
  if   ( -e "$yyexec.cgi" ) { $yyext = 'cgi'; }
  else                      { $yyext = 'pl'; }
  if   ( -e 'AdminIndex.cgi' ) { $yyaext = 'cgi'; }
  else                         { $yyaext = 'pl'; }
   
sub automaintenance { sub automaintenance {
   my $maction = $_[0];     my ( $maction, $mreason ) = @_; 
   my $mreason = $_[1];     if ( lc($maction) eq 'on' ) { 
   if (lc($maction) eq "on") {         fopen( MAINT, ">$vardir/maintenance.lock" ); 
       fopen (MAINT, ">$vardir/maintenance.lock");         print {MAINT} 
       print MAINT qq~Remove this file if your board is in maintenance for no reason\n~;           qq~$maintxt{'maint'}\n~ 
       fclose (MAINT);           or croak qq~$maintxt{'maint'}~; 
       if ($mreason eq "low_disk"){         fclose(MAINT); 
           &LoadLanguage('Error');         if ( $mreason eq 'low_disk' ) { 
           &alertbox($error_txt{'low_diskspace'});             LoadLanguage('Error'); 
       }             alertbox( $error_txt{'low_diskspace'} ); 
       $maintenance = 2 if !$maintenance;         } 
   } elsif (lc($maction) eq "off") {         if ( !$maintenance ) { $maintenance = 2; } 
       unlink "$vardir/maintenance.lock" || &admin_fatal_error("cannot_open_dir","$vardir/maintenance.lock");     } 
       $maintenance = 0 if $maintenance == 2;     elsif ( lc($maction) eq 'off' ) { 
   }         unlink "$vardir/maintenance.lock" 
           or fatal_error( 'cannot_open_dir', "$vardir/maintenance.lock" );
         if ( $maintenance == 2 ) { $maintenance = 0; }
     }
     return;
} }
   
sub getnewid { sub getnewid {
   my $newid = $date;    my $newid = $date;
   while (-e "$datadir/$newid.txt") { ++$newid; }    while ( -e "$datadir/$newid.txt" ) { ++$newid; }
   return $newid;    return $newid;
} }
   
sub undupe { sub undupe {
   my (@out,$duped,$check);     my (@indup) = @_; 
   foreach $check (@_) {     my ( @out, $duped, ); 
       $duped = 0;     foreach my $check (@indup) { 
       foreach (@out) { if ($_ eq $check) { $duped = 1; last; } }         $duped = 0; 
       if (!$duped) { push(@out, $check); }         foreach (@out) { 
   }            if ( $_ eq $check ) { $duped = 1; last; }
   return @out;         } 
         if ( !$duped ) { push @out, $check; }
     }
     return @out;
} }
   
sub exit { sub exit {
   local $| = 1;     my ($inexit)                = @_; 
   local $\ = '';     my $OUTPUT_AUTOFLUSH        = 1; 
   print '';     my $OUTPUT_RECORD_SEPARATOR = q{}; 
   wait if $child_pid;     print q{}; 
   CORE::exit($_[0] || 0);     if ($child_pid) { wait; } 
     CORE::exit( $inexit || 0 );
     return;
} }
   
sub print_output_header { sub print_output_header {
   $headerstatus ||= '200 OK';     if ($header_already_printed) { return; } 
   $contenttype  ||= 'text/html';     $yyxml_lang = $abbr_lang; 
     $header_already_printed = 1;
   my $ret = $yyIIS ? "HTTP/1.0 $headerstatus\n" : "Status: $headerstatus\n";     $headerstatus ||= '200 OK'; 
     $contenttype  ||= 'text/html';
   foreach ($yySetCookies1,$yySetCookies2,$yySetCookies3) { $ret .= "Set-Cookie: $_\n" if $_; }  
     my $ret = $yyIIS ? "HTTP/1.0 $headerstatus\n" : "Status: $headerstatus\n";
   if ($yySetLocation) {  
       $ret .= "Location: $yySetLocation";     foreach ( $yySetCookies1, $yySetCookies2, $yySetCookies3, @otherCookies ) { 
   } else {         if ($_) { $ret .= "Set-Cookie: $_\n"; } 
       $ret .= "Cache-Control: no-cache, must-revalidate\nPragma: no-cache\n" if !$cachebehaviour;     } 
       $ret .= "ETag: \"$ETag\"\n" if $ETag;  
       $ret .= "Last-Modified: $LastModified\n" if $LastModified;     if ( !$no_error_page ) { 
       $ret .= "Content-Encoding: gzip\n" if $gzcomp && $gzaccept;         if ($yySetLocation) { 
       $ret .= "Content-Type: $contenttype";             $ret .= "Location: $yySetLocation"; 
       $ret .= "; charset=$yycharset" if $yycharset;         } 
   }         else { 
   print $ret . "\r\n\r\n";             if ( !$cachebehaviour ) { 
                 $ret .=
  "Cache-Control: no-cache, must-revalidate\nPragma: no-cache\n";
             }
             if ($ETag)         { $ret .= "ETag: \"$ETag\"\n"; }
             if ($LastModified) { $ret .= "Last-Modified: $LastModified\n"; }
             if ( $gzcomp && $gzaccept ) { $ret .= "Content-Encoding: gzip\n"; }
             $ret .= "Content-Type: $contenttype";
             if ($yycharset) {$yymycharset = $yycharset;}
             if ($yymycharset) { $ret .= "; charset=$yymycharset"; }
        }
     }
     print $ret . "\r\n\r\n" or croak "$croak{'print'} ret";
     return;
} }
   
sub print_HTML_output_and_finish { sub print_HTML_output_and_finish {
   if ($gzcomp && $gzaccept) {    if ( $gzcomp && $gzaccept ) {
       my $filehandle_exists = fileno GZIP;        my $filehandle_exists = fileno GZIP;
       if ($gzcomp == 1 || $filehandle_exists) {        if ( $gzcomp == 1 || $filehandle_exists ) {
           $| = 1;            $OUTPUT_AUTOFLUSH = 1;
           open(GZIP, "| gzip -f") unless $filehandle_exists;             if ( !$filehandle_exists ) { 
           print GZIP $output;                 open GZIP, '| gzip -f' or croak "$croak{'open'} GZIP"; 
           close(GZIP);             } 
       } else {             print {GZIP} $output or croak "$croak{'print'} GZIP"; 
           require Compress::Zlib;             close GZIP or croak "$croak{'close'}"; 
           binmode STDOUT;         } 
           print Compress::Zlib::memGzip($output);         else { 
       }             require Compress::Zlib; 
   } else {             binmode STDOUT; 
       print $output;             print Compress::Zlib::memGzip($output) 
   }               or croak "$croak{'print'} ZLib"; 
   exit;         } 
     }
     else {
         print $output;    # or croak "$croak{'print'} output";
     }
     exit;
} }
   
sub write_cookie { sub write_cookie {
   my %params = @_;    my %params = @_;
   
   if ($params{'-expires'} =~ /\+(\d+)m/) {    if ( $params{'-expires'} =~ /\+(\d+)m/xsm ) {
       my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($date + $1 * 60);         my ( $sec, $min, $hour, $mday, $mon, $year, $wday ) = 
           gmtime( $date + $1 * 60 );
   
         $year += 1900;
         my @mos = qw(
           Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
         );
         my @dys = qw( Sun Mon Tue Wed Thu Fri Sat );
         $mon  = $mos[$mon];
         $wday = $dys[$wday];
   
         $params{'-expires'} = sprintf '%s, %02i-%s-%04i %02i:%02i:%02i GMT',
           $wday, $mday, $mon, $year, $hour, $min, $sec;
     }
   
     if ( $params{'-path'} ) { $params{'-path'} = " path=$params{'-path'};"; }
     if ( $params{'-expires'} ) {
         $params{'-expires'} = " expires=$params{'-expires'};";
     }
   
       $year += 1900;     return 
       my @mos = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");       "$params{'-name'}=$params{'-value'};$params{'-path'}$params{'-expires'}"; 
       my @dys = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");  
       $mon  = $mos[$mon];  
       $wday = $dys[$wday];  
   
       $params{'-expires'} = sprintf("%s, %02i-%s-%04i %02i:%02i:%02i GMT", $wday, $mday, $mon, $year, $hour, $min, $sec);  
   }  
   
   $params{'-path'}    = " path=$params{'-path'};"       if $params{'-path'};  
   $params{'-expires'} = " expires=$params{'-expires'};" if $params{'-expires'};  
   
   "$params{'-name'}=$params{'-value'};$params{'-path'}$params{'-expires'}";  
} }
   
sub redirectexit { sub redirectexit {
   $headerstatus = '302 Moved Temporarily';    $headerstatus = '302 Moved Temporarily';
   &print_output_header;     print_output_header(); 
   exit;    exit;
  }
   
  sub redirectmove {
     require Sources::MessageIndex;
     MessageIndex();
     return;
} }
   
sub redirectinternal { sub redirectinternal {
   if ($currentboard) {    if ($currentboard) {
       if ($INFO{'num'}) { require "$sourcedir/Display.pl"; &Display; }        if   ( $INFO{'num'} ) { require Sources::Display;      Display(); }
       else { require "$sourcedir/MessageIndex.pl"; &MessageIndex; }        else                  { require Sources::MessageIndex; MessageIndex(); }
   } else {     } 
       require "$sourcedir/BoardIndex.pl";     else { 
       &BoardIndex;         require Sources::BoardIndex; 
   }         BoardIndex(); 
     }
     return;
} }
   
sub ImgLoc { sub ImgLoc {
   return (!-e "$forumstylesdir/$useimages/$_[0]" ? qq~$forumstylesurl/default/$_[0]~ : qq~$imagesdir/$_[0]~);     @img = @_; 
     if ( exists $img_locs{ $img[0] } ) {
         $img_locs{ $img[0] } = $img_locs{ $img[0] };
     }
     elsif ( -e "$htmldir/Templates/Forum/$useimages/$img[0]" ) {
         $img_locs{ $img[0] } = qq~$imagesdir/$img[0]~;
     }
     else {
         $img_locs{ $img[0] } = qq~$defaultimagesdir/$img[0]~;
     }
     return $img_locs{ $img[0] };
} }
   
sub template { sub template {
   &print_output_header;     print_output_header(); 
   
   if ($yytitle ne $maintxt{'error_description'}) {    if ( $yytitle ne $maintxt{'error_description'} ) {
       if ((!$iamguest || ($iamguest && $guestaccess == 1)) && !$maintenance ) { $yyforumjump = &jumpto; }         if ( ( !$iamguest || ( $iamguest && $guestaccess == 1 ) ) 
       else { $yyforumjump = ' '; }             && !$maintenance ) 
   }         { 
   $yyposition      = $yytitle;             $yyforumjump = jumpto(); 
   $yytitle         = "$mbname - $yytitle";         } 
   $yyimages        = $imagesdir;         else { $yyforumjump = ' '; } 
   $yydefaultimages = $defaultimagesdir;     } 
     $yyposition      = $yytitle;
   $yystyle  = qq~<link rel="stylesheet" href="$forumstylesurl/$usestyle.css" type="text/css" />\n~;     $yytitle         = "$mbname - $yytitle"; 
   $yystyle  =~ s~$usestyle\/~~g;     $yyimages        = $imagesdir; 
   $yystyle  .= qq~<link rel="stylesheet" href="$yyhtml_root/shjs/styles/sh_style.css" type="text/css" />\n~;     $yydefaultimages = $defaultimagesdir; 
   $yystyle .= $yyinlinestyle; # This is for the Help Center and anywhere else that wants to add inline CSS.     $yysyntax_js     = q{}; 
$yysyntax_js = qq~     $yygreyboxstyle  = q{}; 
<script language="JavaScript1.2" type="text/javascript" src="$yyhtml_root/shjs/sh_main.js"></script>     $yygrayscript    = q{}; 
<script language="JavaScript1.2" type="text/javascript" src="$yyhtml_root/shjs/sh_cpp.js"></script>  
<script language="JavaScript1.2" type="text/javascript" src="$yyhtml_root/shjs/sh_css.js"></script>     if ( 
<script language="JavaScript1.2" type="text/javascript" src="$yyhtml_root/shjs/sh_html.js"></script>            $INFO{'num'} 
<script language="JavaScript1.2" type="text/javascript" src="$yyhtml_root/shjs/sh_java.js"></script>         || $action eq 'post' 
<script language="JavaScript1.2" type="text/javascript" src="$yyhtml_root/shjs/sh_javascript.js"></script>         || $action eq 'modify' 
<script language="JavaScript1.2" type="text/javascript" src="$yyhtml_root/shjs/sh_pascal.js"></script>         || $action eq 'preview' 
<script language="JavaScript1.2" type="text/javascript" src="$yyhtml_root/shjs/sh_perl.js"></script>         || $action eq 'search2' 
<script language="JavaScript1.2" type="text/javascript" src="$yyhtml_root/shjs/sh_php.js"></script>         || $action eq 'imshow' 
<script language="JavaScript1.2" type="text/javascript" src="$yyhtml_root/shjs/sh_sql.js"></script>         || $action eq 'imsend' 
         || $action eq 'myviewprofile' 
         || $action eq 'eventcal' 
         || $action eq 'help' 
         || $action eq 'recenttopics' 
         || $action eq 'recent' 
         || $action eq 'usersrecentposts' 
         || $action eq 'myusersrecentposts' 
        )
     {
         $yysyntax_js = qq~
  <script type="text/javascript" src="$yyhtml_root/shjs/sh_main.js"></script>
  <script type="text/javascript" src="$yyhtml_root/shjs/sh_cpp.js"></script>
  <script type="text/javascript" src="$yyhtml_root/shjs/sh_css.js"></script>
  <script type="text/javascript" src="$yyhtml_root/shjs/sh_html.js"></script>
  <script type="text/javascript" src="$yyhtml_root/shjs/sh_java.js"></script>
  <script type="text/javascript" src="$yyhtml_root/shjs/sh_javascript.js"></script>
  <script type="text/javascript" src="$yyhtml_root/shjs/sh_pascal.js"></script>
  <script type="text/javascript" src="$yyhtml_root/shjs/sh_perl.js"></script>
  <script type="text/javascript" src="$yyhtml_root/shjs/sh_php.js"></script>
  <script type="text/javascript" src="$yyhtml_root/shjs/sh_sql.js"></script>
~; ~;
         $yyjsstyle =
  qq~<link rel="stylesheet" href="$yyhtml_root/shjs/styles/sh_style.css" type="text/css" />\n~;
         $yyhigh = q~<script type="text/javascript">
     sh_highlightDocument();
  </script>~;
   
   # add 'back to top' Button on the end of each page         if ($img_greybox) { 
   $yynavback .= qq~<img src="$imagesdir/tabsep211.png" border="0" alt="" style="vertical-align: middle;" />~ if !$yynavback;             $yygreyboxstyle = 
   $yynavback .= qq~ <a href="#pagetop" class="nav">$img_txt{'102'}</a> <img src="$imagesdir/tabsep211.png" border="0" alt="" style="vertical-align: middle;" />~;  qq~<link href="$yyhtml_root/greybox/gb_styles.css" rel="stylesheet" type="text/css" />\n~; 
   
   if (!$usehead) { $usehead = qq~default~; }             $yygrayscript = qq~ 
   $yytemplate = "$templatesdir/$usehead/$usehead.html";  <script type="text/javascript"> 
   fopen(TEMPLATE, $yytemplate) || die("$maintxt{'23'}: $yytemplate");     var GB_ROOT_DIR = "$yyhtml_root/greybox/"; 
   $output = join('', <TEMPLATE>);  </script> 
   fclose(TEMPLATE);  <script type="text/javascript" src="$yyhtml_root/AJS.js"></script> 
  <script type="text/javascript" src="$yyhtml_root/AJS_fx.js"></script>
   if ($iamadmin || $iamgmod) {  <script type="text/javascript" src="$yyhtml_root/greybox/gb_scripts.js"></script> 
       if ($maintenance) { $yyadmin_alert .= qq~<br /><span class="highlight"><b>$load_txt{'616'}</b></span>~; }  ~;
       if ($iamadmin && $rememberbackup) {         } 
           if ($lastbackup && $date > $rememberbackup + $lastbackup) {     } 
               $yyadmin_alert .= qq~<br /><span class="highlight"><b>$load_txt{'617'} ~ . &timeformat($lastbackup) . qq~</b></span>~;  
           }  
       }  
   }  
   
   $yyboardname = "$mbname";  
   $yyboardlink = qq~<a href="$scripturl">$mbname</a>~;  
   
   # static/dynamic clock  
   $yytime = &timeformat($date, 1);  
   if ($mytimeselected != 7 && (($iamguest && $dynamic_clock) || ${$uid.$username}{'dynamic_clock'})) {  
       $yytime =~ /(.*?)\d+:\d+((\w+)|:\d+)?/;  
       my ($a,$b) = ($1,$3);  
       $a =~ s/<.+?>//g;  
       $b = ' ' if $mytimeselected == 6;  
       $yytime = qq~&nbsp;<script language="javascript" type="text/javascript">\n<!--\nWriteClock('yabbclock','$a','$b');\n//-->\n</script>~;  
       $yyjavascript .= qq~\n\nvar OurTime = ~ . ($date + (3600 * $toffs)) . qq~000;\nvar YaBBTime = new Date();\nvar TimeDif = YaBBTime.getTime() - (YaBBTime.getTimezoneOffset() * 60000) - OurTime - 1000; // - 1000 compromise to transmission time~;  
   }  
   
   $yyjavascript .= qq~  
   
   function txtInFields(thefield, defaulttxt) {  
       if (thefield.value == defaulttxt) thefield.value = "";  
       else { if (thefield.value == "") thefield.value = defaulttxt; }  
   }  
   ~;  
   if ($output =~ /\{yabb tabmenu\}/) {  
       require "$sourcedir/TabMenu.pl";  
       &mainMenu;  
   
   } else {  
       $yymenu = qq~<a href="$scripturl">$img{'home'}</a>$menusep<a href="$scripturl?action=help" style="cursor:help;">$img{'help'}</a>~;  
       # remove search from menu if disabled by the admin  
       if ($maxsearchdisplay > -1) {  
           $yymenu .= qq~$menusep<a href="$scripturl?action=search">$img{'search'}</a>~;  
       }  
       if (!$ML_Allowed || ($ML_Allowed == 1 && !$iamguest) || ($ML_Allowed == 2 && $staff) || ($ML_Allowed == 3 && ($iamadmin || $iamgmod))) {  
           $yymenu .= qq~$menusep<a href="$scripturl?action=ml">$img{'memberlist'}</a>~;  
       }  
   
       if ($iamadmin) { $yymenu .= qq~$menusep<a href="$boardurl/AdminIndex.$yyaext">$img{'admin'}</a>~; }  
       if ($iamgmod) {  
           if (-e ("$vardir/gmodsettings.txt")) {  
               require "$vardir/gmodsettings.txt";  
           }  
           if ($allow_gmod_admin) { $yymenu .= qq~$menusep<a href="$boardurl/AdminIndex.$yyaext">$img{'admin'}</a>~; }  
       }  
       if ($sessionvalid == 0 && !$iamguest) {  
           my $sesredir;  
           unless (!$testenv || $action eq "revalidatesession" || $action eq "revalidatesession2") {  
               $sesredir = $testenv;  
               $sesredir =~ s/\=/\~/g;  
               $sesredir =~ s/;/x3B/g;  
               $sesredir = qq~;sesredir=$sesredir~;  
           }  
           $yymenu .= qq~$menusep<a href="$scripturl?action=revalidatesession$sesredir">$img{'sessreval'}</a>~;  
       }  
       if ($iamguest) {  
           my $sesredir;  
           if ($testenv) {  
               $sesredir = $testenv;  
               $sesredir =~ s/\=/\~/g;  
               $sesredir =~ s/;/x3B/g;  
               $sesredir = qq~;sesredir=$sesredir~;  
           }  
           $yymenu .= qq~$menusep<a href="~ . ($loginform ? "javascript:if(jumptologin>1)alert('$maintxt{'35'}');jumptologin++;window.scrollTo(0,10000);document.loginform.username.focus();" : "$scripturl?action=login$sesredir") . qq~">$img{'login'}</a>~;  
           if ($regtype != 0) { $yymenu .= qq~$menusep<a href="$scripturl?action=register">$img{'register'}</a>~; }  
           if ($PMenableGuestButton && $PM_level > 0 && $PMenableBm_level > 0) {  
               $yymenu .= qq~$menusep<a href="$scripturl?action=guestpm">$img{'pmadmin'}</a>~; }  
   
       } else {  
           ## pointing towards pm now  
           $yymenu .= qq~$menusep<a href="$scripturl?action=mycenter">$img{'mycenter'}</a>~;  
           $yymenu .= qq~$menusep<a href="$scripturl?action=logout">$img{'logout'}</a>~;  
       }  
   }  
   
   $yylangChooser = "";  
   if (($iamguest && !$guestLang) && $enable_guestlanguage && $guestaccess) {  
       if (!$langopt) {&guestLangSel;}  
       if ($morelang > 1) {  
           $yylangChooser = qq~$guest_txt{'sellanguage'}: <form action="$scripturl?action=guestlang" method="post" name="sellanguage">  
           <select name="guestlang" onchange="submit();">  
           $langopt  
           </select>  
           <noscript><input type="submit" value="$maintxt{'32'}" class="button" /></noscript>  
           </form>~;  
       }  
   
   } elsif (($iamguest && $guestLang) && $enable_guestlanguage && $guestaccess) {  
       if (!$langopt) {&guestLangSel;}  
       if ($morelang > 1) {  
           $yylangChooser = qq~$guest_txt{'changelanguage'}: <form action="$scripturl?action=guestlang" method="post" name="changelanguage">  
           <select name="guestlang" onchange="submit();">  
           $langopt  
           </select>  
           <noscript><input type="submit" value="$maintxt{'32'}" class="button" /></noscript>  
           </form>~;  
       }  
   }  
   
   my $wmessage;  
   if    ($hour >= 12 && $hour < 18) { $wmessage = $maintxt{'247a'}; } # Afternoon  
   elsif ($hour <  12 && $hour >= 0) { $wmessage = $maintxt{'247m'}; } # Morning  
   else                              { $wmessage = $maintxt{'247e'}; } # Evening  
   if ($iamguest) {  
       $yyuname = qq~$maintxt{'248'} $maintxt{'28'}. $maintxt{'249'} <a href="~ . ($loginform ? "javascript:if(jumptologin>1)alert('$maintxt{'35'}');jumptologin++;window.scrollTo(0,10000);document.loginform.username.focus();" : "$scripturl?action=login") . qq~">$maintxt{'34'}</a>~;  
       $yyuname .= qq~ $maintxt{'377'} <a href="$scripturl?action=register">$maintxt{'97'}</a>~ if $regtype;  
       $yyjavascript .= "\njumptologin = 1;";  
   } else {  
       if (${$uid.$username}{'bday'} ne '') {  
           my ($usermonth, $userday, $useryear) = split(/\//, ${$uid.$username}{'bday'});  
           if ($usermonth == $mon_num && $userday == $mday) { $wmessage = $maintxt{'247bday'}; }  
       }  
       $yyuname = ($PM_level == 0 || ($PM_level == 2 && !$iamadmin && !$iamgmod && !$iammod) || ($PM_level == 3 && !$iamadmin && !$iamgmod)) ? "$wmessage ${$uid.$username}{'realname'}" : "$wmessage ${$uid.$username}{'realname'}, ";  
   }  
   
   # Add new notifications if allowed  
   if (!$iamguest && $NewNotificationAlert) {  
       unless ($board_notify || $thread_notify) {  
           require "$sourcedir/Notify.pl";  
           ($board_notify,$thread_notify) = &NotificationAlert;  
       }  
       my ($bo_num,$th_num);  
       foreach (keys %$board_notify) { # boardname, boardnotifytype , new  
           $bo_num++ if ${$$board_notify{$_}}[2];  
       }  
       foreach (keys %$thread_notify) { # mythread, msub, new, username_link, catname_link, boardname_link, lastpostdate  
           $th_num++ if ${$$thread_notify{$_}}[2];  
       }  
       if ($bo_num || $th_num) {  
           my $noti_text = ($bo_num ? "$notify_txt{'201'} $notify_txt{'205'} ($bo_num)" : "") . ($th_num ? ($bo_num ? " $notify_txt{'202'} " : "") . "$notify_txt{'201'}  $notify_txt{'206'} ($th_num)" : "");  
           $yyadmin_alert = qq~<br />$notify_txt{'200'} <a href="$scripturl?action=shownotify">$noti_text</a>.$yyadmin_alert~;  
           $yymain .= qq~<script language="javascript" type="text/javascript">  
           <!--  
           window.setTimeout("Noti_Popup();", 1000);  
           function Noti_Popup() {  
               if (confirm('$notify_txt{'200'} $noti_text.\\n$notify_txt{'203'}'))  
                   window.location.href='$scripturl?action=shownotify';  
           }  
           //-->  
           </script>~ if ${$uid.$username}{'onlinealert'} and $boardindex_template;  
       }  
   }  
   
   # This next line fixes problems created when a fatal_error is called before Security.pl is loaded  
   # We don't want to require since it's an error and trying to do anything extra for an error could be bad  
   if ($output =~ m~<yabb copyright>~ || $output =~ m~{yabb copyright}~) { $yycopyin = 1; } ## new template style in also  
   $yysearchbox = '';  
   unless ($iamguest && $guestaccess == 0) {  
       if ($maxsearchdisplay > -1) {  
           $yysearchbox = qq~  
       <script language="JavaScript1.2" src="$yyhtml_root/ubbc.js" type="text/javascript"></script>  
       <form action="$scripturl?action=search2" method="post">  
       <input type="hidden" name="searchtype" value="allwords" />  
       <input type="hidden" name="userkind" value="any" />  
       <input type="hidden" name="subfield" value="on" />  
       <input type="hidden" name="msgfield" value="on" />  
       <input type="hidden" name="age" value="31" />  
       <input type="hidden" name="numberreturned" value="$maxsearchdisplay" />  
       <input type="hidden" name="oneperthread" value="1" />  
       <input type="hidden" name="searchboards" value="!all" />  
       <input type="text" name="search" size="16" id="search1" value="$img_txt{'182'}" style="font-size: 11px;" onfocus="txtInFields(this, '$img_txt{'182'}');" onblur="txtInFields(this, '$img_txt{'182'}')" />  
       <input type="image" src="$imagesdir/search.gif" style="border: 0; background-color: transparent; margin-right: 5px; vertical-align: middle;" />  
       </form>  
       ~;  
       }  
   }  
   if ($enable_news && -s "$vardir/news.txt" > 5) {  
       fopen(NEWS, "$vardir/news.txt");  
       my @newsmessages = <NEWS>;  
       fclose(NEWS);  
       chomp(@newsmessages);  
       my $startnews = int(rand(@newsmessages));  
       my $newstitle = qq~<b>$maintxt{'102'}:</b>~;  
       $newstitle =~ s/'/\\'/g;  
       $guest_media_disallowed = 0;  
       $newswrap = 40;  
       if ($shownewsfader) {  
           $fadedelay = $maxsteps * $stepdelay;  
           $yynews .= qq~  
           <script language="JavaScript1.2" type="text/javascript">  
               <!--  
                   var index = $startnews;  
                   var maxsteps = "$maxsteps";  
                   var stepdelay = "$stepdelay";  
                   var fadelinks = $fadelinks;  
                   var delay = "$fadedelay";  
                   function convProp(thecolor) {  
                       if(thecolor.charAt(0) == "#") {  
                           if(thecolor.length == 4) thecolor=thecolor.replace(/(\\#)([a-f A-F 0-10]{1,1})([a-f A-F 0-10]{1,1})([a-f A-F 0-10]{1,1})\/i, "\$1\$2\$2\$3\$3\$4\$4");  
                           var thiscolor = new Array(HexToR(thecolor), HexToG(thecolor), HexToB(thecolor));  
                           return thiscolor;  
                       }  
                       else if(thecolor.charAt(3) == "(") {  
                           thecolor=thecolor.replace(/rgb\\((\\d+?\\%*?)\\,(\\s*?)(\\d+?\\%*?)\\,(\\s*?)(\\d+?\\%*?)\\)/i, "\$1|\$3|\$5");  
                           var thiscolor = thecolor.split("|");  
                           return thiscolor;  
                       }  
                       else {  
                           thecolor=thecolor.replace(/\\"/g, "");  
                           thecolor=thecolor.replace(/maroon/ig, "128|0|0");  
                           thecolor=thecolor.replace(/red/i, "255|0|0");  
                           thecolor=thecolor.replace(/orange/i, "255|165|0");  
                           thecolor=thecolor.replace(/olive/i, "128|128|0");  
                           thecolor=thecolor.replace(/yellow/i, "255|255|0");  
                           thecolor=thecolor.replace(/purple/i, "128|0|128");  
                           thecolor=thecolor.replace(/fuchsia/i, "255|0|255");  
                           thecolor=thecolor.replace(/white/i, "255|255|255");  
                           thecolor=thecolor.replace(/lime/i, "00|255|00");  
                           thecolor=thecolor.replace(/green/i, "0|128|0");  
                           thecolor=thecolor.replace(/navy/i, "0|0|128");  
                           thecolor=thecolor.replace(/blue/i, "0|0|255");  
                           thecolor=thecolor.replace(/aqua/i, "0|255|255");  
                           thecolor=thecolor.replace(/teal/i, "0|128|128");  
                           thecolor=thecolor.replace(/black/i, "0|0|0");  
                           thecolor=thecolor.replace(/silver/i, "192|192|192");  
                           thecolor=thecolor.replace(/gray/i, "128|128|128");  
                           var thiscolor = thecolor.split("|");  
                           return thiscolor;  
                       }  
                   } //" make my syntax checker happy;  
   
                   if (ie4 || DOM2) document.write('$newstitle<div class="windowbg2" id="fadestylebak" style="display: none;"><div class="newsfader" id="fadestyle" style="display: none;"> </div></div>');  
   
                   if (document.getElementById('fadestyle').currentStyle) {  
                       tcolor = document.getElementById('fadestyle').currentStyle['color'];  
                       bcolor = document.getElementById('fadestyle').currentStyle['backgroundColor'];  
                       fntsize = document.getElementById('fadestyle').currentStyle['fontSize'];  
                       fntstyle = document.getElementById('fadestyle').currentStyle['fontStyle'];  
                       fntweight = document.getElementById('fadestyle').currentStyle['fontWeight'];  
                       fntfamily = document.getElementById('fadestyle').currentStyle['fontFamily'];  
                       txtdecoration = document.getElementById('fadestyle').currentStyle['textDecoration'];  
                   }  
                   else if (window.getComputedStyle) {  
                       tcolor = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('color');  
                       bcolor = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('background-color');  
                       fntsize = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('font-size');  
                       fntstyle = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('font-style');  
                       fntweight = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('font-weight');  
                       fntfamily = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('font-family');  
                       txtdecoration = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('text-decoration');  
                   }  
                   if (bcolor == "transparent" || bcolor == "rgba\\(0\\, 0\\, 0\\, 0\\)") {  
                       if (document.getElementById('fadestylebak').currentStyle) {  
                           tcolor = document.getElementById('fadestylebak').currentStyle['color'];  
                           bcolor = document.getElementById('fadestylebak').currentStyle['backgroundColor'];  
                       }  
                       else if (window.getComputedStyle) {  
                           tcolor = window.getComputedStyle(document.getElementById('fadestylebak'), null).getPropertyValue('color');  
                           bcolor = window.getComputedStyle(document.getElementById('fadestylebak'), null).getPropertyValue('background-color');  
                       }  
                   }  
                   txtdecoration = txtdecoration.replace(/\'/g, "");  
                   var endcolor = convProp(tcolor);  
                   var startcolor = convProp(bcolor);~;  
           my $greybox = $img_greybox;  
           $img_greybox = 0;  
           for (my $j = 0; $j < @newsmessages; $j++) {  
               $message = $newsmessages[$j];  
               &wrap;  
               if ($enable_ubbc) {  
                   if (!$yyYaBBCloaded) { require "$sourcedir/YaBBC.pl"; }  
                   $ns = "";  
                   &DoUBBC;  
                   $message =~ s/ style="display:none"/ style="display:block"/g;  
               }  
               &wrap2;  
               $message =~ s/"/\\"/g;  
               &ToChars($message);  
               $yynews .= qq~                    fcontent[$j] = "$message";\n~;  
           }  
           $img_greybox = $greybox;  
           $yynews .= qq~  
                   if (ie4 || DOM2) document.write('<div style="font-size: ' + fntsize + '\\; font-weight: ' + fntweight + '\\; font-style: ' + fntstyle + '\\; font-family: ' + fntfamily + '\\; text-decoration: ' + txtdecoration + '\\;" id="fscroller"></div>');  
   
                   if (window.addEventListener)  
                       window.addEventListener("load", changecontent, false);  
                   else if (window.attachEvent)  
                       window.attachEvent("onload", changecontent);  
                   else if (document.getElementById)  
                       window.onload = changecontent;  
               // -->  
           </script>  
       ~;  
       } else {  
           $message = $newsmessages[$startnews];  
           &wrap;  
           if ($enable_ubbc) {  
               if (!$yyYaBBCloaded) { require "$sourcedir/YaBBC.pl"; }  
               &DoUBBC;  
               $message =~ s/ style="display:none"/ style="display:block"/g;  
           }  
           &wrap2;  
           &ToChars($message);  
           $yynews = $message;  
       }  
       $newswrap = 0;  
   } else {  
       $yynews = '&nbsp;';  
   }  
   # Moved this down here so it shows more  
   ##  pushed to own file for flexibility  
   if ($debug == 1 or ($debug == 2 && $iamadmin)) { require "$sourcedir/Debug.pl"; &Debug; }  
   $yyurl      = $scripturl;  
   ## new and old tag template style decoding ##  
   while ($output =~ s~(<|{)yabb\s+(\w+)(}|>)~${"yy$2"}~g) {}  
   $output =~ s~(a href=\S+?action=viewprofile;username=.+?)>~$1 rel="nofollow">~isg;  
   if ($imagesdir ne $defaultimagesdir) {  
       $output =~ s~img src=(\\*"|')$imagesdir/(.+?)(\1)~ "img src=$1" . &ImgLoc($2) . $3 ~eisg;  
       $output =~ s~\.src='$imagesdir/(.+?)'~ ".src='" . &ImgLoc($1) . "'" ~eisg; # For Javascript generated images  
       $output =~ s~input type="image" src="$imagesdir/(.+?)"~ 'input type="image" src="' . &ImgLoc($1) . '"' ~eisg; # For input images  
       $output =~ s~option value="$imagesdir/(.+?)"~ 'option value="' . &ImgLoc($1) . '"' ~eisg; # For the post page  
   }  
   $output =~ s~</form>~<input type="hidden" name="formsession" value="$formsession" /></form>~g;  
   
   &image_resize;  
   
   # Start workaround to substitute all ';' by '&' in all URLs  
   # This workaround solves problems with servers that use mod_security  
   # in a very strict way. (error 406)  
   # Take the comments out of the following two lines if you had this problem.  
   # $output =~ s/($scripturl\?)([^'"]+)/ $1 . &URL_modify($2) /eg;  
   # sub URL_modify { my $x = shift; $x =~ s/;/&/g; $x; }  
   # End of workaround  
   
   if ($yycopyin == 0) {  
       $output = q~<center><h1><b>Sorry, the copyright tag <yabb copyright> must be in the template.<br />Please notify this forum's administrator that this site is using an ILLEGAL copy of YaBB!</b></h1></center>~;  
   }  
   
   &print_HTML_output_and_finish;     $yystyle = 
  qq~<link rel="stylesheet" href="$yyhtml_root/Templates/Forum/$usestyle.css" type="text/css" />\n~;
     $yystyle =~ s/$usestyle\///gxsm;
     $yystyle .= $yyjsstyle;
     $yystyle .= $yygreyboxstyle;
     $yystyle .= $yyinlinestyle;
   
     if ( $action eq 'register' || $action eq 'guestpm' || $action eq 'modalert' || $action eq 'post' || $action eq 'imsend' || ( $action eq 'eventcal' && $INFO{'addnew'} == 1 ) ) {
         $yystyle .= '<meta name ="robots" content="noindex, nofollow" />';
     }
   
     # Carsten's 'backtotop';
     if ( !$yynavback ) { $yynavback .= q~ ~; }
     $yynavback .=
  qq~$tabsep <span onclick="toTop(0)" class="cursor">$img_txt{'102'}</span> &nbsp; $tabsep~;
   
     if ( !$usehead ) { $usehead = q~default~; }
     $yytemplate = "$templatesdir/$usehead/$usehead.html";
     fopen( TEMPLATE, $yytemplate ) or croak("$maintxt{'23'}: $yytemplate");
     @whole_file = <TEMPLATE>;
     $output = join q{}, @whole_file;
     fclose(TEMPLATE);
   
     if ( $iamadmin || $iamgmod ) {
         if ($maintenance) {
             if   ($do_scramble_id) { $user = cloak($username); }
             else                   { $user = $username; }
             $yyadmin_alert .=
               qq~<br /><span class="highlight"><b>$load_txt{'616'}</b></span>~;
             $yyadmin_alert =~ s/USER/$user/sm;
         }
         $rememberbackup ||= 0;
         if ( $iamadmin && $rememberbackup > 0 ) {
             if ( $lastbackup && $date > $rememberbackup + $lastbackup ) {
                 $yyadmin_alert .=
                     qq~<br /><span class="highlight"><b>$load_txt{'617'} ~
                   . timeformat($lastbackup)
                   . q~</b></span>~;
             }
         }
     }
   
     # to top button for fixed menu
     $yyfixtop  = qq~$img_txt{'to_top'}~;
   
     $yyboardname = "$mbname";
     $yyboardlink = qq~<a href="$scripturl">$mbname</a>~;
   
     # static/dynamic clock
     $yytime = timeformat( $date, 1 );
     my $zone = q{};
     if ( ($iamguest && $default_tz eq 'UTC') || (${ $uid . $username }{'user_tz'} eq 'UTC') || ( !$default_tz  &&  !${ $uid . $username }{'user_tz'} ) ) {
         $zone = qq~ $maintxt{'UTC'}~;
     }
     my $toffs = 0;
     if ( $enabletz ) {
         $toffs = toffs($date);
     }
     if (
         $mytimeselected != 7
         && ( ( $iamguest && $dynamic_clock )
             || ${ $uid . $username }{'dynamic_clock'} )
       )
     {
         if ( $yytime =~ /(.*?)\d+:\d+((\w+)|:\d+)?/xsm ) {
             ( $aa, $bb ) = ( $1, $3 );
         }
         $aa =~ s/<.+?>//gxsm;
         if ( $mytimeselected == 6 ) { $bb = q{ }; }
         $yytime =
  qq~&nbsp;<script  type="text/javascript">\nWriteClock('yabbclock','$aa','$bb');\n</script>~;
         $yyjavascripta .=
             qq~
         var OurTime = ~
           . sprintf( '%d', ( $date + $toffs ) )
           . qq~000;\nvar YaBBTime = new Date();\nvar TimeDif = YaBBTime.getTime() - (YaBBTime.getTimezoneOffset() * 60000) - OurTime - 1000; // - 1000 compromise to transmission time~;
     }
     $yytime .= $zone;
   
     $yyjavascripta .= qq~
     var imagedir = "$imagesdir";
     function toTop(scrpoint) {
         window.scrollTo(0,scrpoint);
     }~;
   
     $yyjavascript .= q~
     function txtInFields(thefield, defaulttxt) {
         if (thefield.value == defaulttxt) thefield.value = "";
         else { if (thefield.value === "") thefield.value = defaulttxt; }
     }
     function selectAllCode(thefield) {
         var elem = document.getElementById('code' + thefield);
         if (document.selection) {
             document.selection.empty();
             var txt = document.body.createTextRange();
             txt.moveToElementText(elem);
             txt.select();
         }
         else {
             window.getSelection().removeAllRanges();
             txt = document.createRange();
             txt.setStartBefore(elem);
             txt.setEndAfter(elem);
             window.getSelection().addRange(txt);
         }
     }
     ~;
     require Sources::TabMenu;
     mainMenu();
   
   
     $yylangChooser = q{};
     if ( ( $iamguest && !$guestLang ) && $enable_guestlanguage && $guestaccess )
     {
         if ( !$langopt ) { guestLangSel(); }
         if ( $morelang > 1 ) {
             $yylangChooser =
  qq~$guest_txt{'sellanguage'}: <form action="$scripturl?action=guestlang" method="post" name="sellanguage">
             <select name="guestlang" onchange="submit();">
             $langopt
             </select>
             </form>~;
         }
     }
     elsif (( $iamguest && $guestLang )
         && $enable_guestlanguage
         && $guestaccess )
     {
         if ( !$langopt ) { guestLangSel(); }
         if ( $morelang > 1 ) {
             $yylangChooser =
  qq~$guest_txt{'changelanguage'}: <form action="$scripturl?action=guestlang" method="post" name="changelanguage">
             <select name="guestlang" onchange="submit();">
             $langopt
             </select>
             </form>~;
         }
     }
   
     my $wmessage;
     if ( $hour >= 12 && $hour < 18 ) {
         $wmessage = $maintxt{'247a'};
     }    # Afternoon
     elsif ( $hour < 12 && $hour >= 0 ) {
         $wmessage = $maintxt{'247m'};
     }    # Morning
     else { $wmessage = $maintxt{'247e'}; }    # Evening
     if ($iamguest) {
         $yyuname = qq~$maintxt{'248'} $maintxt{'28'}. $maintxt{'249'} <a href="~
           . (
             $loginform
             ? "javascript:if(jumptologin>1)alert('$maintxt{'35'}');jumptologin++;window.scrollTo(0,10000);document.loginform.username.focus();" 
             : "$scripturl?action=login" 
           ) . qq~">$maintxt{'34'}</a>~;
         if ($regtype) {
             $yyuname .=
  qq~ $maintxt{'377'} <a href="$scripturl?action=register">$maintxt{'97'}</a>~;
         }
         $yyjavascript .= q~        jumptologin = 1;~;
     }
     else {
         if ( ${ $uid . $username }{'bday'} ne q{} ) {
             my ( $usermonth, $userday, $useryear ) =
               split /\//xsm, ${ $uid . $username }{'bday'};
             if ( $usermonth == $mon_num && $userday == $mday ) {
                 $wmessage = $maintxt{'247bday'};
             }
         }
         $yyuname =
           (      $PM_level == 0
               || ( $PM_level == 2 && !$staff )
               || ( $PM_level == 3 && !$iamadmin && !$iamgmod )
               || ( $PM_level == 4 && !$iamadmin && !$iamgmod && !$iamfmod ) )
           ? "$wmessage ${$uid.$username}{'realname'}" 
           : "$wmessage ${$uid.$username}{'realname'}, ";
     }
   
     # Add new notifications if allowed
     if ( !$iamguest && $NewNotificationAlert ) {
         if ( !$board_notify && !$thread_notify ) {
             require Sources::Notify;
             ( $board_notify, $thread_notify ) = NotificationAlert();
         }
         my ( $bo_num, $th_num );
         foreach ( keys %{$board_notify} ) {   # boardname, boardnotifytype , new
             if ( ${ $$board_notify{$_} }[2] ) { $bo_num++; }
         }
         foreach ( keys %{$thread_notify} )
         { # mythread, msub, new, username_link, catname_link, boardname_link, lastpostdate
             if ( ${ $$thread_notify{$_} }[2] ) { $th_num++; }
         }
         if ( $bo_num || $th_num ) {
             my $noti_text = (
                 $bo_num
                 ? "$notify_txt{'201'} $notify_txt{'205'} ($bo_num)" 
                 : q{}
               )
               . (
                 $th_num
                 ? ( $bo_num ? " $notify_txt{'202'} " : q{} )
                   . "$notify_txt{'201'}  $notify_txt{'206'} ($th_num)" 
                 : q{}
               );
             if ( ${ $uid . $username }{'onlinealert'} && $boardindex_template )
             {
                 $yyadmin_alert =
  qq~<br />$notify_txt{'200'} <a href="$scripturl?action=shownotify">$noti_text</a>.$yyadmin_alert~;
                 $yymain .= qq~<script type="text/javascript">
             window.setTimeout("Noti_Popup();", 1000);
             function Noti_Popup() {
                 if (confirm('$notify_txt{'200'} $noti_text.\\n$notify_txt{'203'}'))
                     window.location.href='$scripturl?action=shownotify';
             }
              </script>~;
             }
         }
     }
   
  # check for copyright for special error - angle brackets no longer supported for yabb tags
     if ( $output =~ m/{yabb\ copyright}/xsm ) {
         $yycopyin = 1;
     }
   
     $yysearchbox = q{};
     if ( !$iamguest || $guestaccess != 0 ) {
         if ( $maxsearchdisplay > -1 && $qcksearchaccess eq 'granted' ) {
             my $blurb = qq~$maintxt{'searchimg'} $qckage $maintxt{'searchimg2'}~;
             if ( $qckage == 0 ) {
                 $blurb = qq~$maintxt{'searchimg3'}~;
             }
             $yysearchbox = qq~<div class="yabb_searchbox">
                     <form action="$scripturl?action=search2" method="post" accept-charset="$yymycharset">
                         <input type="hidden" name="searchtype" value="$qcksearchtype" />
                         <input type="hidden" name="userkind" value="any" />
                         <input type="hidden" name="subfield" value="on" />
                         <input type="hidden" name="msgfield" value="on" />
                         <input type="hidden" name="age" value="$qckage" />
                         <input type="hidden" name="oneperthread" value="1" />
                         <input type="hidden" name="searchboards" value="!all" />
                         <input type="text" name="search" size="16" id="search1" value="$img_txt{'182'}" style="font-size: 11px;" onfocus="txtInFields(this, '$img_txt{'182'}');" onblur="txtInFields(this, '$img_txt{'182'}')" />
                         <input type="image" src="$imagesdir/search.png" alt="$blurb" title="$blurb" style="background-color: transparent; margin-right: 5px; vertical-align: middle;" />
                     </form>
                     </div>
  ~;
         }
     }
     if ( $enable_news && ( -s "$vardir/news.txt" ) > 5 ) {
         fopen( NEWS, "$vardir/news.txt" );
         my @newsmessages = <NEWS>;
         fclose(NEWS);
         chomp @newsmessages;
         my $startnews = int rand @newsmessages;
         $yynewstitle = qq~<b>$maintxt{'102'}:</b>  <span id="newsdiv"></span>~;
         $yynewstitle =~ s/\x27/\\\x27/gxsm;
         $guest_media_disallowed = 0;
         $newswrap               = 40;
   
         if ($shownewsfader) {
             $fadedelay = $maxsteps * $stepdelay;
             $yynews .= qq~
             <script type="text/javascript">//<![CDATA[
                     var index = $startnews;
                     var maxsteps = "$maxsteps";
                     var stepdelay = "$stepdelay";
                     var fadelinks = $fadelinks;
                     var delay = "$fadedelay";
                     function convProp(thecolor) {
                         if(thecolor.charAt(0) == "#") {
                             if(thecolor.length == 4) thecolor=thecolor.replace(/(\\#)([a-f A-F 0-10]{1,1})([a-f A-F 0-10]{1,1})([a-f A-F 0-10]{1,1})\/i, "\$1\$2\$2\$3\$3\$4\$4");
                             var thiscolor = new Array(HexToR(thecolor), HexToG(thecolor), HexToB(thecolor));
                             return thiscolor;
                         }
                         else if(thecolor.charAt(3) == "(") {
                             thecolor=thecolor.replace(/rgb\\((\\d+?\\%*?)\\,(\\s*?)(\\d+?\\%*?)\\,(\\s*?)(\\d+?\\%*?)\\)/i, "\$1|\$3|\$5");
                             thiscolor = thecolor.split("|");
                             return thiscolor;
                         }
                         else {
                             thecolor=thecolor.replace(/\\"/g, "");
                             thecolor=thecolor.replace(/maroon/ig, "128|0|0");
                             thecolor=thecolor.replace(/red/i, "255|0|0");
                             thecolor=thecolor.replace(/orange/i, "255|165|0");
                             thecolor=thecolor.replace(/olive/i, "128|128|0");
                             thecolor=thecolor.replace(/yellow/i, "255|255|0");
                             thecolor=thecolor.replace(/purple/i, "128|0|128");
                             thecolor=thecolor.replace(/fuchsia/i, "255|0|255");
                             thecolor=thecolor.replace(/white/i, "255|255|255");
                             thecolor=thecolor.replace(/lime/i, "00|255|00");
                             thecolor=thecolor.replace(/green/i, "0|128|0");
                             thecolor=thecolor.replace(/navy/i, "0|0|128");
                             thecolor=thecolor.replace(/blue/i, "0|0|255");
                             thecolor=thecolor.replace(/aqua/i, "0|255|255");
                             thecolor=thecolor.replace(/teal/i, "0|128|128");
                             thecolor=thecolor.replace(/black/i, "0|0|0");
                             thecolor=thecolor.replace(/silver/i, "192|192|192");
                             thecolor=thecolor.replace(/gray/i, "128|128|128");
                             thiscolor = thecolor.split("|");
                             return thiscolor;
                         }
                     }
                     if (ie4 || DOM2) var news = ('<span class="windowbg2" id="fadestylebak" style="display: none;"><span class="newsfader" id="fadestyle" style="display: none;"> </span></span>');
                     var div = document.getElementById("newsdiv");
                     div.innerHTML = news;
                     if (document.getElementById('fadestyle').currentStyle) {
                         tcolor = document.getElementById('fadestyle').currentStyle['color'];
                         bcolor = document.getElementById('fadestyle').currentStyle['backgroundColor'];
                         nfntsize = document.getElementById('fadestyle').currentStyle['fontSize'];
                         fntstyle = document.getElementById('fadestyle').currentStyle['fontStyle'];
                         fntweight = document.getElementById('fadestyle').currentStyle['fontWeight'];
                         fntfamily = document.getElementById('fadestyle').currentStyle['fontFamily'];
                         txtdecoration = document.getElementById('fadestyle').currentStyle['textDecoration'];
                     }
                     else if (window.getComputedStyle) {
                         tcolor = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('color');
                         bcolor = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('background-color');
                         nfntsize = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('font-size');
                         fntstyle = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('font-style');
                         fntweight = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('font-weight');
                         fntfamily = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('font-family');
                         txtdecoration = window.getComputedStyle(document.getElementById('fadestyle'), null).getPropertyValue('text-decoration');
                     }
                     if (bcolor == "transparent" || bcolor == "rgba\\(0\\, 0\\, 0\\, 0\\)") {
                         if (document.getElementById('fadestylebak').currentStyle) {
                             tcolor = document.getElementById('fadestylebak').currentStyle['color'];
                             bcolor = document.getElementById('fadestylebak').currentStyle['backgroundColor'];
                         }
                         else if (window.getComputedStyle) {
                             tcolor = window.getComputedStyle(document.getElementById('fadestylebak'), null).getPropertyValue('color');
                             bcolor = window.getComputedStyle(document.getElementById('fadestylebak'), null).getPropertyValue('background-color');
                         }
                     }
                     txtdecoration = txtdecoration.replace(/\x27/g, "");
                     var endcolor = convProp(tcolor);
                     var startcolor = convProp(bcolor);~;
             my $greybox = $img_greybox;
             $img_greybox = 0;
             foreach my $j ( 0 .. $#newsmessages ) {
                 $message = $newsmessages[$j];
                 wrap();
                 if ($enable_ubbc) {
                     enable_yabbc();
                     $ns = q{};
                     DoUBBC();
                     $message =~
                       s/ style="display:none"/ style="display:block"/gsm;
                 }
                 wrap2();
                 $message =~ s/\x22/\\\x22/gxsm;
                 ToChars($message);
                 $message =~ s/\x27/&\x2339;/xsm;
                 $yynews .= qq~                  fcontent[$j] = '$message';\n~;
             }
             $img_greybox = $greybox;
             $yynews .= q~
                         document.getElementById("newsdiv").style.fontSize=nfntsize;
                         document.getElementById("newsdiv").style.fontWeight=fntweight;
                         document.getElementById("newsdiv").style.fontStyle=fntstyle;
                         document.getElementById("newsdiv").style.fontFamily=fntfamily;
                         document.getElementById("newsdiv").style.textDecoration=txtdecoration;
   
                     if (window.addEventListener)
                         window.addEventListener("load", changecontent, false);
                     else if (window.attachEvent)
                         window.attachEvent("onload", changecontent);
                     else if (document.getElementById)
                         window.onload = changecontent;
             //]]></script>
         ~;
         }
         else {
             $message = $newsmessages[$startnews];
             wrap();
             if ($enable_ubbc) {
                 enable_yabbc();
                 DoUBBC();
                 $message =~ s/ style="display:none"/ style="display:block"/gsm;
             }
             wrap2();
             ToChars($message);
             $message =~ s/\x27/&\x2339;/xsm;
             $yynews = qq~
             <script type="text/javascript">
                 if (ie4 || DOM2) var news = '$message';
                 var div = document.getElementById("newsdiv");
                 div.innerHTML = news;
             </script>~;
         }
         $newswrap = 0;
     }
     else {
         $yynews = '&nbsp;';
     }
   
     if ( $debug == 1 || ( $debug == 2 && $iamadmin ) || $debug == 3 ) {
         require Sources::Debug;
         LoadLanguage('Debug');
         Debug();
     }
   
     $yyurl = $scripturl;
     my $copyright = $output =~ m/{yabb\ copyright}/xsm ? 1 : 0;
   
     while ( $output =~ s/({)yabb\s+(\w+)(})/${"yy$2"}/gxsm ) { }
   
     # check if image exists, otherwise use the default template image
     if ( $imagesdir ne $defaultimagesdir ) {
         my %img_locs;
   
         $output =~
  s/(src|value|url)(=|\()("|'| )$imagesdir\/([^'" ]+)./ "$1$2$3" . ImgLoc($4) . $3 /eisgm;
     }
   
     # add formsession to each <form ..>-tag
     $output =~
  s/<\/form>/ <input type="hidden" name="formsession" value="$formsession" \/>\n                    <\/form>/gsm;
   
     image_resize();
   
     # Start workaround to substitute all ';' by '&' in all URLs
     # This workaround solves problems with servers that use mod_security
     # in a very strict way. (error 406)
     # Take the comments out of the following two lines if you had this problem.
     # $output =~ s/($scripturl\?)([^'"]+)/ $1 . URL_modify($2) /eg;
     # sub URL_modify { my $x = shift; $x =~ s/;/&amp;/g; $x; }
     # End of workaround
   
     if ( !$copyright ) {
         $output =
  qq~<h1 class="center"><b>Sorry, the copyright tag &\x23123;yabb copyright&\x23125; must be in the template.<br />Please notify this forum&\x2339;s administrator that this site is using an ILLEGAL copy of YaBB!</b></h1>~;
     }
   
     print_HTML_output_and_finish();
     return;
  }
   
  sub PMlev {
     my $pm_lev = 0;
     if (   $PM_level == 1
         || ( $PM_level == 2 && $staff )
         || ( $PM_level == 3 && ( $iamadmin || $iamgmod ) )
         || ( $PM_level == 4 && ( $iamadmin || $iamgmod || $iamfmod ) ) )
     {
         $pm_lev = 1;
     }
     return $pm_lev;
} }
   
sub image_resize { sub image_resize {
   my ($resize_js,$resize_num);     my ( $resize_js, $resize_num ); 
   my $perl_do_it = 0; # Hardcoded! Set to 1 for Perl to do the fix...size work here. Set to 0 for the javascript within the browser do this work.     my $perl_do_it = 0; 
   $output =~ s/"((avatar|post|attach|signat)_img_resize)"([^>]*>)/ &check_image_resize($1,$2,$3) /ge;  
  # Hardcoded! Set to 1 for Perl to do the fix...size work here. Set to 0 for the javascript within the browser do this work.
   sub check_image_resize {  
       my @x = @_;     *check_image_resize = sub { 
       if ($fix_avatar_img_size && $perl_do_it == 1 && $x[1] eq 'avatar') {         my @x  = @_; 
           if ($max_avatar_width  && $x[2] !~ / width=./)  { $x[2] =~ s/( style=.)/$1width:$max_avatar_width\px;/; }         my $px = 'px'; 
           if ($max_avatar_height && $x[2] !~ / height=./) { $x[2] =~ s/( style=.)/$1height:$max_avatar_height\px;/; }         if ( $fix_avatar_img_size && $perl_do_it == 1 && $x[1] eq 'avatar' ) { 
           $x[2] =~ s/display:none/display:inline/;             if ( $max_avatar_width && $x[2] !~ / width=./sm ) { 
       } elsif ($fix_post_img_size && $perl_do_it == 1 && $x[1] eq 'post') {                 $x[2] =~ s/( style=.)/$1width:$max_avatar_width$px;/sm; 
           if ($max_post_width  && $x[2] !~ / width=./)  { $x[2] =~ s/( style=.)/$1width:$max_post_width\px;/; }            }
           if ($max_post_height && $x[2] !~ / height=./) { $x[2] =~ s/( style=.)/$1height:$max_post_height\px;/; }             if ( $max_avatar_height && $x[2] !~ / height=./sm ) { 
           $x[2] =~ s/display:none/display:inline/;                 $x[2] =~ s/( style=.)/$1height:$max_avatar_height$px;/sm; 
       } elsif ($fix_attach_img_size && $perl_do_it == 1 && $x[1] eq 'attach') {             } 
           if ($max_attach_width  && $x[2] !~ / width=./)  { $x[2] =~ s/( style=.)/$1width:$max_attach_width\px;/; }             $x[2] =~ s/display:none/display:inline/sm; 
           if ($max_attach_height && $x[2] !~ / height=./) { $x[2] =~ s/( style=.)/$1height:$max_attach_height\px;/; }        }
           $x[2] =~ s/display:none/display:inline/;         elsif ($fix_avatarml_img_size 
       } elsif ($fix_signat_img_size && $perl_do_it == 1 && $x[1] eq 'signat') {             && $perl_do_it == 1 
           if ($max_signat_width  && $x[2] !~ / width=./)  { $x[2] =~ s/( style=.)/$1width:$max_signat_width\px;/; }             && $x[1] eq 'avatarml' ) 
           if ($max_signat_height && $x[2] !~ / height=./) { $x[2] =~ s/( style=.)/$1height:$max_signat_height\px;/; }         { 
           $x[2] =~ s/display:none/display:inline/;             if ( $max_avatarml_width && $x[2] !~ / width=./sm ) { 
       } else {                 $x[2] =~ s/( style=.)/$1width:$max_avatarml_width$px;/sm; 
           $resize_num++;             } 
           $x[0] .= "_$resize_num";             if ( $max_avatarml_height && $x[2] !~ / height=./sm ) { 
           $resize_js .= "'$x[0]',";                 $x[2] =~ s/( style=.)/$1height:$max_avatarml_height$px;/sm; 
       }            }
       qq~"$x[0]"$x[2]~;             $x[2] =~ s/display:none/display:inline/sm; 
   }        }
         elsif ( $fix_post_img_size && $perl_do_it == 1 && $x[1] eq 'post' ) {
   if ($resize_num) {            if ( $max_post_width && $x[2] !~ / width=./sm ) {
       $resize_js =~ s/,$//;                 $x[2] =~ s/( style=.)/$1width:$max_post_width$px;/sm; 
       $resize_js = qq~<script language="JavaScript1.2" type="text/javascript">             } 
<!--             if ( $max_post_height && $x[2] !~ / height=./sm ) { 
   // resize image start                 $x[2] =~ s/( style=.)/$1height:$max_post_height$px;/sm; 
   var resize_time = 2;             } 
   var img_resize_names = new Array ($resize_js);             $x[2] =~ s/display:none/display:inline/xsm; 
         }
   var avatar_img_w    = $max_avatar_width;         elsif ( $fix_attach_img_size && $perl_do_it == 1 && $x[1] eq 'attach' ) 
   var avatar_img_h    = $max_avatar_height;         { 
   var fix_avatar_size = $fix_avatar_img_size;             if ( $max_attach_width && $x[2] !~ / width=./sm ) { 
   var post_img_w      = $max_post_img_width;                 $x[2] =~ s/( style=.)/$1width:$max_attach_width$px;/sm; 
   var post_img_h      = $max_post_img_height;             } 
   var fix_post_size   = $fix_post_img_size;             if ( $max_attach_height && $x[2] !~ / height=./sm ) { 
   var attach_img_w    = $max_attach_img_width;                 $x[2] =~ s/( style=.)/$1height:$max_attach_height$px;/sm; 
   var attach_img_h    = $max_attach_img_height;             } 
   var fix_attach_size = $fix_attach_img_size;             $x[2] =~ s/display:none/display:inline/xsm; 
   var signat_img_w    = $max_signat_img_width;         } 
   var signat_img_h    = $max_signat_img_height;         elsif ( $fix_signat_img_size && $perl_do_it == 1 && $x[1] eq 'signat' ) 
   var fix_signat_size = $fix_signat_img_size;         { 
             if ( $max_signat_width && $x[2] !~ / width=./sm ) {
   noimgdir   = '$imagesdir';                 $x[2] =~ s/( style=.)/$1width:$max_signat_width$px;/sm; 
   noimgtitle = '$maintxt{'171'}';             } 
             if ( $max_signat_height && $x[2] !~ / height=./sm ) {
   resize_images();                 $x[2] =~ s/( style=.)/$1height:$max_signat_height$px;/sm; 
   // resize image end             } 
// -->             $x[2] =~ s/display:none/display:inline/xsm; 
         }
         elsif ( $fix_brd_img_size  && $perl_do_it == 1 && $x[1] eq 'brd' )
         {
             if ( $max_brd_img_width && $x[2] !~ / width=./sm ) {
                 $x[2] =~ s/( style=.)/$1width:$max_brd_img_width$px;/sm;
             }
             if ( $max_brd_img_height && $x[2] !~ / height=./sm ) {
                 $x[2] =~ s/( style=.)/$1height:$max_brd_img_height$px;/sm;
             }
             $x[2] =~ s/display:none/display:inline/sm;
         }
         else {
             $resize_num++;
             $x[0] .= "_$resize_num";
             $resize_js .= "'$x[0]',";
         }
         return qq~"$x[0]"$x[2]~;
     };
     $output =~
  s/"((avatar|avatarml|post|attach|signat|brd)_img_resize)"([^>]*>)/ check_image_resize($1,$2,$3) /gesm;
   
     if ($resize_num) {
         $avatar_img_w    = isempty( $max_avatar_width, 65 );
         $avatar_img_h    = isempty( $max_avatar_height, 65 );
         $avatarml_img_w  = isempty( $max_avatarml_width, 65 );
         $avatarml_img_h  = isempty( $max_avatarml_height, 65 );
         $post_img_w      = isempty( $max_post_img_width, 0 );
         $post_img_h      = isempty( $max_post_img_height, 0 );
         $attach_img_w    = isempty( $max_attach_img_width, 0 );
         $attach_img_h    = isempty( $max_attach_img_height, 0 );
         $signat_img_w    = isempty( $max_signat_img_width, 0 );
         $signat_img_h    = isempty( $max_signat_img_height, 0 );
         $brd_img_w       = isempty( $max_brd_img_width, 50 );
         $brd_img_h       = isempty( $max_brd_img_height, 50 );
         $fix_brd_img_size = isempty( $fix_brd_img_size, 0 );
   
         $resize_js =~ s/,$//xsm;
         $resize_js = qq~<script type="text/javascript">
     // resize image start
     var resize_time = 2;
     var img_resize_names = new Array ($resize_js);
   
     var avatar_img_w    = $avatar_img_w;
     var avatar_img_h    = $avatar_img_h;
     var fix_avatar_size = $fix_avatar_img_size;
     var avatarml_img_w    = $avatarml_img_w;
     var avatarml_img_h    = $avatarml_img_h;
     var fix_avatarml_size = $fix_avatarml_img_size;
     var post_img_w      = $post_img_w;
     var post_img_h      = $post_img_h;
     var fix_post_size   = $fix_post_img_size;
     var attach_img_w    = $attach_img_w;
     var attach_img_h    = $attach_img_h;
     var fix_attach_size = $fix_attach_img_size;
     var signat_img_w    = $signat_img_w;
     var signat_img_h    = $signat_img_h;
     var fix_signat_size = $fix_signat_img_size;
     var brd_img_w       = $brd_img_w;
     var brd_img_h       = $brd_img_h;
     var fix_brd_size    = $fix_brd_img_size;
   
     noimgdir   = '$imagesdir';
     noimgtitle = '$maintxt{'171'}';
   
     resize_images();
     // resize image end
</script>~; </script>~;
   
       $output =~ s|(</body>)|$resize_js\n$1|;         $output =~ s/(<\/body>)/$resize_js\n$1/sm; 
   }    }
     return;
} }
   
sub fatal_error_logging { sub get_caller {
   my $tmperror = $_[0];  
     # Gets filename and line where fatal_error/debug was called.
   # This flaw was brought to our attention by S M <savy91@msn.com> Italy     # Need to go further back to get correct subroutine name, 
   # Thanks! We couldn't make YaBB successful without the help from the bug testers.     # otherwise will print fatal_error/debug as current subroutine! 
   &ToHTML($action);     my ( undef, $filename, $line ) = caller 1; 
   &ToHTML($INFO{'num'});     my ( undef, undef, undef, $subroutine ) = caller 2; 
   &ToHTML($currentboard);     return ( $filename, $line, $subroutine ); 
   
   $tmperror =~ s/\n//ig;  
   fopen(ERRORLOG, "+<$vardir/errorlog.txt");  
   seek ERRORLOG, 0, 0;  
   my @errorlog = <ERRORLOG>;  
   truncate ERRORLOG, 0;  
   seek ERRORLOG, 0, 0;  
   chomp @errorlog;  
   $errorcount = @errorlog;  
   
   if ($elrotate) {  
       while ($errorcount >= $elmax) {  
           shift @errorlog;  
           $errorcount = @errorlog;  
       }  
   }  
   
   foreach my $formdata (keys %FORM) {  
       chomp $FORM{$formdata};  
       $FORM{$formdata} =~ s/\n//ig;  
   }  
   
   if ($iamguest) {  
       push @errorlog, int(time()) . "|$date|$user_ip|$tmperror|$action|$INFO{'num'}|$currentboard|$FORM{'username'}|$FORM{'passwrd'}";  
   } else {  
       push @errorlog, int(time()) . "|$date|$user_ip|$tmperror|$action|$INFO{'num'}|$currentboard|$username|$FORM{'passwrd'}";  
   }  
   foreach (@errorlog) {  
       chomp;  
       if ($_ ne "") {  
           print ERRORLOG $_ . "\n";  
       }  
   }  
   fclose(ERRORLOG);  
} }
   
sub fatal_error { sub fatal_error {
   my $verbose = $!;     my @x       = @_; 
     my $verbose = $!;
   
   &LoadLanguage('Error');     LoadLanguage('Error'); 
   my $errormessage = "$error_txt{$_[0]} $_[1]";     get_template('Other'); 
   
   # Gets filename and line where fatal_error was called.     my $errormessage = $x[0] ? ( $error_txt{$x[0]} . ( $x[1] ? " $x[1]" : q{} ) ) : isempty( $x[1], q{} ); 
   # Need to go further back to get correct subroutine name,  
   # otherwise will print fatal_error as current subroutine!  
   (undef, $e_filename, $e_line) = caller(0);  
   (undef, undef, undef, $e_subroutine) = caller(1);  
   (undef, $e_subroutine) = split(/::/, $e_subroutine);  
   if (($debug == 1 || ($debug == 2 && $iamadmin)) && ($e_filename || $e_line || $e_subroutine)) { $errormessage .= "<br />$maintxt{'error_location'}: $e_filename<br />$maintxt{'error_line'}: $e_line<br />$maintxt{'error_subroutine'}: $e_subroutine"; }  
   
   if ($_[2]) { $errormessage .= "<br />$maintxt{'error_verbose'}: $verbose"; }  
   
   if ($elenable) { &fatal_error_logging($errormessage); }  
   
   if ($_[0] =~ /no_access|members_only|no_perm/) {  
       $headerstatus = "403 Forbidden";  
   } elsif ($_[0] =~ /cannot_open|no.+_found/) {  
       $headerstatus = "404 Not Found";  
   }  
   
   $yymain .= qq~  
<table border="0" width="80%" cellspacing="1" class="bordercolor" align="center" cellpadding="4">  
   <tr>  
       <td class="titlebg"><span class="text1"><b>$maintxt{'error_description'}</b></span></td>  
   </tr><tr>  
       <td class="windowbg"><br /><span class="text1">$errormessage</span><br /><br /></td>  
   </tr>  
</table>  
<center><br /><a href="javascript:history.go(-1)">$maintxt{'193'}</a></center>  
~;  
   
   $yytitle = "$maintxt{'error_description'}";     my ( $filename, $line, $subroutine ) = get_caller(); 
   &template;     if (   ( $debug == 1 || ( $debug == 2 && $iamadmin ) ) 
         && ( $filename || $line || $subroutine ) )
     {
         LoadLanguage('Debug');
         $errormessage .=
  qq~<br />$maintxt{'error_location'}: $filename<br />$maintxt{'error_line'}: $line<br />$maintxt{'error_subroutine'}: $subroutine~;
     }
   
     if ( $x[2] ) {
         $errormessage .= "<br />$maintxt{'error_verbose'}: $verbose";
     }
   
     if ($elenable) { fatal_error_logging($errormessage); }
   
     # for ajax calls that return errors, so no page is generated
     if ($no_error_page) {
         print "Content-type: text/plain\n\nerror$errormessage" 
           or croak "$croak{'print'} error";
         CORE::exit;    # This is here only to avoid server error log entries!
     }
   
     $yymain .= $my_show_error;
     $yymain =~ s/{yabb errormessage}/$errormessage/sm;
     $yytitle = "$maintxt{'error_description'}";
   
     if ( $adminscreen && $action ne 'admincheck2' ) {
         AdminTemplate();
     }
     else {
         if ( $x[0] =~ /no_access|members_only|no_perm/xsm ) {
             $headerstatus = '403 Forbidden';
         }
         elsif ( $x[0] =~ /cannot_open|no.+_found/xsm ) {
             $headerstatus = '404 Not Found';
         }
         template();
     }
     return;
} }
   
sub admin_fatal_error { sub fatal_error_logging {
   my $verbose = $!;     my ($tmperror) = @_; 
   
   &LoadLanguage('Error');  
   my $errormessage = "$error_txt{$_[0]} $_[1]";  
   
   # Gets filename and line where fatal_error was called.  
   # Need to go further back to get correct subroutine name,  
   # otherwise will print fatal_error as current subroutine!  
   (undef, $e_filename, $e_line) = caller(0);  
   (undef, undef, undef, $e_subroutine) = caller(1);  
   (undef, $e_subroutine) = split(/::/, $e_subroutine);  
   if (($debug == 1 || ($debug == 2 && $iamadmin)) && ($e_filename || $e_line || $e_subroutine)) { $errormessage .= "<br />$maintxt{'error_location'}: $e_filename<br />$maintxt{'error_line'}: $e_line<br />$maintxt{'error_subroutine'}: $e_subroutine"; }  
   
   if ($_[2]) { $errormessage .= "<br />$maintxt{'error_verbose'}: $verbose"; }  
   
   if ($elenable) { &fatal_error_logging($errormessage); }  
   
   $yymain .= qq~  
<table border="0" width="80%" cellspacing="1" class="bordercolor" align="center" cellpadding="4">  
   <tr>  
       <td class="titlebg"><span class="text1"><b>$maintxt{'error_description'}</b></span></td>  
   </tr><tr>  
       <td class="windowbg"><br /><span class="text1">$errormessage</span><br /><br /></td>  
   </tr>  
</table>  
<center><br /><a href="javascript:history.go(-1)">$admin_txt{'193'}</a></center>  
~;  
   
   $yytitle = "$maintxt{'error_description'}";  # This flaw was brought to our attention by S M <savy91@msn.com> Italy 
   &AdminTemplate;  # Thanks! We couldn't make YaBB successful without the help from the bug testers. 
     ToHTML($action);
     ToHTML( $INFO{'num'} );
     ToHTML($currentboard);
   
     $tmperror =~ s/\n//igsm;
     fopen( ERRORLOG, "<$vardir/errorlog.txt" );
     my @errorlog = <ERRORLOG>;
     fclose( ERRORLOG );
     chomp @errorlog;
     $errorcount = @errorlog;
   
     if ($elrotate) {
         while ( $errorcount >= $elmax ) {
             shift @errorlog;
             $errorcount = @errorlog;
         }
     }
   
     foreach my $formdata ( keys %FORM ) {
         chomp $FORM{$formdata};
         $FORM{$formdata} =~ s/\n//igsm;
     }
   
     if ($iamguest) {
         push @errorlog,
           int(time)
           . "|$date|$user_ip|$tmperror|$action|$INFO{'num'}|$currentboard|$FORM{'username'}|$FORM{'passwrd'}\n";
     }
     else {
         push @errorlog,
           int(time)
           . "|$date|$user_ip|$tmperror|$action|$INFO{'num'}|$currentboard|$username|$FORM{'passwrd'}\n";
     }
     fopen( ERRORLOG, ">$vardir/errorlog.txt" );
     foreach (@errorlog) {
         chomp;
         if ( $_ ne q{} ) {
             print {ERRORLOG} $_ . "\n" or croak "$croak{'print'} ERRORLOG";
         }
     }
     fclose(ERRORLOG);
     return;
} }
   
sub FindPermalink { sub FindPermalink {
   $old_env = $_[0];     my ($old_env) = @_; 
   $old_env = substr($old_env,1, length($old_env));     $old_env        = substr $old_env, 1, length $old_env; 
   $permtopicfound = 0;    $permtopicfound = 0;
   $permboardfound = 0;    $permboardfound = 0;
   $is_perm = 1;    $is_perm        = 1;
   ## strip off symlink for redirectlike e.g. /articles/ ##    ## strip off symlink for redirectlike e.g. /articles/ ##
   $old_env =~ s~$symlink~~g;     $old_env =~ s/$symlink//gxsm; 
   ## get date/time/board/topic from permalink    ## get date/time/board/topic from permalink
   
   ($permyear, $permmonth, $permday, $permboard, $permnum) = split (/\//, $old_env);     ( $permyear, $permmonth, $permday, $permboard, $permnum ) = 
   if(-e "$boardsdir/$permboard.txt") {       split /\//xsm, $old_env; 
       $permboardfound = 1;     if ( -e "$boardsdir/$permboard.txt" ) { 
       if($permnum ne "" && -e "$datadir/$permnum.txt") {         $permboardfound = 1; 
           $new_env = qq~num=$permnum~;         if ( $permnum ne q{} && -e "$datadir/$permnum.txt" ) { 
           $permtopicfound = 1;             $new_env        = qq~num=$permnum~; 
       } else { $new_env = qq~board=$permboard~; }             $permtopicfound = 1; 
   }        }
   return $new_env;         else { $new_env = qq~board=$permboard~; } 
     }
     return $new_env;
} }
   
sub permtimer { sub permtimer {
   my $thetime = $_[0];     my ($thetime) = @_; 
   my (undef, $pmin, $phour, $pmday, $pmon, $pyear, undef, undef, undef) = gmtime($thetime + (3600 * $timeoffset));     my $mynewtime =  $thetime; 
   my $pmon_num = $pmon + 1;  
   $phour = sprintf("%02d", $phour);     my ( undef, $pmin, $phour, $pmday, $pmon, $pyear, undef, undef, undef ) = 
   $pmin = sprintf("%02d", $pmin);       gmtime( $mynewtime ); 
   $pyear = 1900 + $pyear;     my $pmon_num = $pmon + 1; 
   $pmon_num = sprintf("%02d", $pmon_num);     $phour    = sprintf '%02d', $phour; 
   $pmday = sprintf("%02d", $pmday);     $pmin     = sprintf '%02d', $pmin; 
   $pyear = sprintf("%04d", $pyear);     $pyear    = 1900 + $pyear; 
   return "$pyear/$pmon_num/$pmday";     $pmon_num = sprintf '%02d', $pmon_num; 
     $pmday    = sprintf '%02d', $pmday;
     $pyear    = sprintf '%04d', $pyear;
     return "$pyear/$pmon_num/$pmday";
} }
   
sub readform { sub readform {
   my (@pairs, $pair, $name, $value);     my ( @pairs, $pair, $name, $value ); 
   if (substr($ENV{QUERY_STRING},0,1) eq "/" && $accept_permalink) { $ENV{QUERY_STRING} = &FindPermalink($ENV{QUERY_STRING}); }     if ( substr( $ENV{QUERY_STRING}, 0, 1 ) eq q{/} && $accept_permalink ) { 
   if ($ENV{QUERY_STRING} =~ m/action\=dereferer/) {         $ENV{QUERY_STRING} = FindPermalink( $ENV{QUERY_STRING} ); 
       $INFO{'action'} = "dereferer";     } 
       $urlstart = index($ENV{QUERY_STRING}, "url=");     if ( $ENV{QUERY_STRING} =~ m/action\=dereferer/xsm ) { 
       $INFO{'url'} = substr($ENV{QUERY_STRING}, $urlstart + 4, length($ENV{QUERY_STRING}) - $urlstart + 3);         $INFO{'action'} = 'dereferer'; 
       $INFO{'url'} =~ s/\;anch\=/#/g;         $urlstart = index $ENV{QUERY_STRING}, 'url='; 
       $testenv = "";         $INFO{'url'} = substr 
   } else {           $ENV{QUERY_STRING}, 
       $testenv = $ENV{QUERY_STRING};           $urlstart + 4, 
       $testenv =~ s/\&/\;/g;           length( $ENV{QUERY_STRING} ) - $urlstart + 3; 
       if ($testenv && $debug) { $getpairs = qq~<br /><u>$debug_txt{'getpairs'}:</u><br />~; }         $INFO{'url'} =~ s/\;anch\=/\x23/gxsm; 
   }         $testenv = q{}; 
   # URL encoding for web.de http://www.blooberry.com/indexdot/html/topics/urlencoding.htm     } 
   $testenv =~ s/\%3B/;/ig; # search must be case insensitiv for some servers!     else { 
   $testenv =~ s/\%26/&/g;         $testenv = $ENV{QUERY_STRING}; 
         $testenv =~ s/\&/\;/gxsm;
   &split_string(\$testenv, \%INFO, 1);         if ( $testenv && $debug ) { 
   if ($ENV{'SERVER_SOFTWARE'} =~ /IIS/) {             LoadLanguage('Debug'); 
       ($dummy,$IISver) = split( '\/', $ENV{'SERVER_SOFTWARE'});             $getpairs = 
       ($IISver,$IISverM) = split( '.',$IISver);  qq~<br /><span class="under">$debug_txt{'getpairs'}:</span><br />~; 
       if (int($IISver) < 6 && int($IISverM) < 1) { eval 'use CGI qw(:standard)'; }        }
   }    }
   if ($ENV{REQUEST_METHOD} eq 'POST') {  
       if ($debug) { $getpairs .= qq~<br /><u>$debug_txt{'postpairs'}:</u><br />~; }  # URL encoding for web.de http://www.blooberry.com/indexdot/html/topics/urlencoding.htm 
       if ($ENV{CONTENT_TYPE} =~ /multipart\/form-data/) {     $testenv =~ s/\%3B/;/igxsm; 
           require CGI;  
           # A possible attack is for the remote user to force CGI.pm to accept     # search must be case insensitive for some servers! 
           # a huge file upload. CGI.pm will accept the upload and store it in     $testenv =~ s/\%26/&/gxsm; 
           # a temporary directory even if your script doesn't expect to receive  
           # an uploaded file. CGI.pm will delete the file automatically when it     split_string( \$testenv, \%INFO, 1 ); 
           # terminates, but in the meantime the remote user may have filled up     if ( $ENV{'SERVER_SOFTWARE'} =~ /IIS/sm ) { 
           # the server's disk space, causing problems for other programs.         ( $dummy,  $IISver )  = split /\//xsm, $ENV{'SERVER_SOFTWARE'}; 
           # The best way to avoid denial of service attacks is to limit the         ( $IISver, $IISverM ) = split /./xsm,  $IISver; 
           # amount of memory, CPU time and disk space that CGI scripts can use.         if ( int($IISver) < 6 && int($IISverM) < 1 ) { 
           # If $CGI::POST_MAX is set to a non-negative integer, this variable             eval { use CGI qw(:standard) }; 
           # puts a ceiling on the size of POSTings, in bytes. If CGI.pm detects         } 
           # a POST that is greater than the ceiling, it will immediately exit     } 
           # with an error message like this:     if ( $ENV{REQUEST_METHOD} eq 'POST' ) { 
           # "413 Request entity too large"         if ($debug) { 
           # This value will affect both ordinary POSTs and multipart POSTs,             LoadLanguage('Debug'); 
           # meaning that it limits the maximum size of file uploads as well.             $getpairs .= 
           if ($allowattach && $ENV{'QUERY_STRING'} =~ /action=(post|modify)2\b/) {  qq~<br /><span class="under">$debug_txt{'postpairs'}:</span><br />~; 
               $CGI::POST_MAX = int(1024 * $limit * $allowattach);         } 
               $CGI::POST_MAX += 1000000 if $CGI::POST_MAX; # *         if ( $ENV{CONTENT_TYPE} =~ /multipart\/form-data/xsm ) { 
           } elsif ($upload_useravatar && $ENV{'QUERY_STRING'} =~ /action=profileOptions2\b/) {             require CGI; 
               $CGI::POST_MAX = int(1024 * $avatar_limit);  
               $CGI::POST_MAX += 1000000 if $CGI::POST_MAX; # *            # A possible attack is for the remote user to force CGI.pm to accept 
           } else {            # a huge file upload. CGI.pm will accept the upload and store it in 
               # If NO uploads are allowed YaBB sets this default limit            # a temporary directory even if your script doesn't expect to receive 
               # to 1 MB. Change this values if you get error messages.            # an uploaded file. CGI.pm will delete the file automatically when it 
               $CGI::POST_MAX = 1000000;            # terminates, but in the meantime the remote user may have filled up 
           }            # the server's disk space, causing problems for other programs. 
           # * adds volume, if a upload limit is set, to not get error if the other            # The best way to avoid denial of service attacks is to limit the 
           # uploaded data is larger. Change this values if you get error messages.            # amount of memory, CPU time and disk space that CGI scripts can use. 
           $CGI_query = new CGI; # $CGI_query must be a global variable           # If $CGI::POST_MAX is set to a non-negative integer, this variable
           my ($name, @value);            # puts a ceiling on the size of POSTings, in bytes. If CGI.pm detects 
           foreach $name ($CGI_query->param()) {            # a POST that is greater than the ceiling, it will immediately exit 
               next if $name =~ /^file(\d+|_avatar)$/; # files are directly called in Profile.pl, Post.pl and ModifyMessages.pl            # with an error message like this: 
               @value = $CGI_query->param($name);            # "413 Request entity too large" 
               if ($debug) { $getpairs .= qq~[$debug_txt{'name'}-&gt;]$name=@value\[&lt;-$debug_txt{'value'}]<br />~; }            # This value will affect both ordinary POSTs and multipart POSTs, 
               $FORM{$name} = join(', ', @value); # multiple values are joined            # meaning that it limits the maximum size of file uploads as well. 
           }             $allowattach   ||= 0; 
       } else {             $allowAttachIM ||= 0; 
           read(STDIN, my $input, $ENV{CONTENT_LENGTH});             $limit         ||= 0; 
           &split_string(\$input, \%FORM);             $pmFileLimit   ||= 0; 
       }             if (   $allowattach > 0 
   }                 && $ENV{'QUERY_STRING'} =~ /action=(post|modify)2\b/xsm ) 
   $action = $INFO{'action'} || $FORM{'action'};             { 
   # Formsession checking moved to YaBB.pl to fix a bug.                 $CGI::POST_MAX = int( 1024 * $limit * $allowattach ); 
   if ($INFO{'username'} && $do_scramble_id && $action ne 'view_regentry' && $action ne 'del_regentry' && $action ne 'activate' ) { $INFO{'username'} = &decloak($INFO{'username'}); }                if ($CGI::POST_MAX) { $CGI::POST_MAX += 1048576; }
   if ($FORM{'username'} && $do_scramble_id && $action ne "login2" && $action ne "reminder2" && $action ne "register2" && $action ne "profile2" && $action ne 'admin_descision') { $FORM{'username'} = &decloak($FORM{'username'}); }            }
   if ($INFO{'to'} && $do_scramble_id) { $INFO{'to'} = &decloak($INFO{'to'}); }             elsif ( $allowAttachIM > 0 
   if ($FORM{'to'} && $do_scramble_id) { $FORM{'to'} = &decloak($FORM{'to'}); }                 && $ENV{'QUERY_STRING'} =~ /action=(imsend|imsend2)\b/xsm ) 
   # Dont do this here or you get problems with foreign characters!!!!             { 
   #if ($action eq 'search2') { &FromHTML($FORM{'search'}); }                 $CGI::POST_MAX = int( 1024 * $pmFileLimit * $allowAttachIM ); 
   #&ToHTML($INFO{'title'});                 if ($CGI::POST_MAX) { $CGI::POST_MAX += 1048576; } 
   #&ToHTML($FORM{'title'});             } 
   #&ToHTML($INFO{'subject'});             elsif ( $upload_useravatar 
   #&ToHTML($FORM{'subject'});                 && $ENV{'QUERY_STRING'} =~ /action=profileOptions2\b/xsm ) 
             {
   sub split_string {                 $avatar_limit ||= 0; 
       my ($string, $hash, $altdelim) = @_;                 $CGI::POST_MAX = int( 1024 * $avatar_limit ); 
                 if ($CGI::POST_MAX) { $CGI::POST_MAX += 1048576; }
       if ($altdelim && $$string =~ m~;~) { @pairs = split(/;/, $$string); }            }
       else { @pairs = split(/&/, $$string); }             else { 
       foreach $pair (@pairs) {  
           my ($name, $value) = split(/=/, $pair);                 # If NO uploads are allowed YaBB sets this default limit 
           $name  =~ tr/+/ /;                 # to 1 MB. Change this values if you get error messages. 
           $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;                 $CGI::POST_MAX = 1048576; 
           $value =~ tr/+/ /;             } 
           $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;  
           if ($debug) { $getpairs .= qq~[$debug_txt{'name'}-&gt;]$name=$value\[&lt;-$debug_txt{'value'}]<br />~; }         # * adds volume, if a upload limit is set, to not get error if the other 
           if (exists($hash->{$name})) {         # uploaded data is larger. Change this values if you get error messages. 
               $hash->{$name} .= ", $value";             $CGI_query = CGI->new; 
           } else {  
               $hash->{$name} = $value;             # $CGI_query must be a global variable 
           }             my (@value); 
       }             foreach my $name ( $CGI_query->param() ) { 
   }                if ( $name =~ /^file(\d+|_avatar)$/xsm ) { next; }
   
         # files are directly called in Profile.pm, Post.pm and ModifyMessages.pl
                 @value = $CGI_query->param($name);
                 if ($debug) {
                     LoadLanguage('Debug');
                     $getpairs .=
  qq~[$debug_txt{'name'}-&gt;]$name=@value\[&lt;-$debug_txt{'value'}]<br />~;
                 }
                 $FORM{$name} = join q{, }, @value;  # multiple values are joined
             }
         }
         else {
             read STDIN, my $input, $ENV{CONTENT_LENGTH};
             split_string( \$input, \%FORM );
         }
     }
     $action = $INFO{'action'} || $FORM{'action'};
   
     if (   $INFO{'username'}
         && $do_scramble_id
         && $action ne 'view_regentry' 
         && $action ne 'del_regentry' 
         && $action ne 'activate' )
     {
         $INFO{'username'} = decloak( $INFO{'username'} );
     }
     if (   $FORM{'username'}
         && $do_scramble_id
         && $action ne 'login2' 
         && $action ne 'reminder2' 
         && $action ne 'register2' 
         && $action ne 'profile2' 
         && $action ne 'admin_descision' )
     {
         $FORM{'username'} = decloak( $FORM{'username'} );
     }
     if ( $INFO{'to'} && $do_scramble_id ) {
         $INFO{'to'} = decloak( $INFO{'to'} );
     }
     if ( $FORM{'to'} && $do_scramble_id ) {
         $FORM{'to'} = decloak( $FORM{'to'} );
     }
     return;
  }
   
  sub split_string {
     my ( $string, $hash, $altdelim ) = @_;
   
     if ( $altdelim && ${$string} =~ m{;}sm ) {
         @pairs = split /;/xsm, ${$string};
     }
     else { @pairs = split /&/xsm, ${$string}; }
     foreach my $pair (@pairs) {
         my ( $name, $value ) = split /=/xsm, $pair;
         $name  =~ tr/+/ /;
         $name  =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack('C', hex($1))/egsm;
         $value =~ tr/+/ /;
         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack('C', hex($1))/egsm;
         if ($debug) {
             LoadLanguage('Debug');
             $getpairs .=
  qq~[$debug_txt{'name'}-&gt;]$name=$value\[&lt;-$debug_txt{'value'}]<br />~;
         }
         if ( exists( $hash->{$name} ) ) {
             $hash->{$name} .= ", $value";
         }
         else {
             $hash->{$name} = $value;
         }
     }
     return;
} }
   
sub getlog { sub getlog {
   return if %yyuserlog || $iamguest || !$max_log_days_old || !-e "$memberdir/$username.log";     return 
       if %yyuserlog
   %yyuserlog = ();           || $iamguest 
   fopen(GETLOG, "$memberdir/$username.log");           || !$max_log_days_old 
   my @logentries = <GETLOG>;           || !-e "$memberdir/$username.log"; 
   fclose(GETLOG);  
   chomp(@logentries);     %yyuserlog = (); 
     fopen( GETLOG, "$memberdir/$username.log" );
   my ($name,$thistime);     my @logentries = <GETLOG>; 
   foreach (@logentries) {     fclose(GETLOG); 
       ($name,$thistime) = split(/\|/, $_);     chomp @logentries; 
       if ($name && $thistime) { $yyuserlog{$name} = $thistime; }  
   }     foreach (@logentries) { 
         my ( $name, $thistime ) = split /\|/xsm, $_;
         if ( $name && $thistime ) { $yyuserlog{$name} = $thistime; }
     }
     return;
} }
   
sub dumplog { sub dumplog {
   return if $iamguest || !$max_log_days_old;     my @dum = @_; 
     return if $iamguest || !$max_log_days_old;
   
   if ($_[0]) {    if ( $dum[0] ) {
       &getlog;         getlog(); 
       $yyuserlog{$_[0]} = $_[1] || $date;        $yyuserlog{ $dum[0] } = $dum[1] || $date;
   }    }
   if (%yyuserlog) {    if (%yyuserlog) {
       my $name;        my $name;
       $date2 = $date;        $date2 = $date;
       fopen(DUMPLOG, ">$memberdir/$username.log");         fopen( DUMPLOG, ">$memberdir/$username.log" ); 
       while (($name,$date1) = each(%yyuserlog)) {        while ( ( $name, $date1 ) = each %yyuserlog ) {
           &calcdifference; # output => $result             $result = calcdifference( $date1, $date2 );    # output => $result 
           if ($result <= $max_log_days_old) {            if ( $result <= $max_log_days_old ) {
               print DUMPLOG qq~$name|$date1\n~;                 print {DUMPLOG} qq~$name|$date1\n~ 
           }                   or croak "$croak{'print'} DUMPLOG"; 
       }            }
       fclose(DUMPLOG);         } 
   }         fclose(DUMPLOG); 
     }
     return;
} }
   
## standard jump to menu ## standard jump to menu
sub jumpto { sub jumpto {
   my (@masterdata, $category, @data, $found, $tmp, @memgroups, @newcatdata, $boardname);     ## jump links to messages/favorites/notifications. 
   ## jump links to messages/favourites/notifications.     my $action = 'action=jump'; 
   my $action = 'action=jump';     my $onchange = 
   my $onchange = qq~ onchange="if(this.options[this.selectedIndex].value) window.location.href='$scripturl?' + this.options[this.selectedIndex].value;"~; qq~ onchange="if(this.options[this.selectedIndex].value) window.location.href='$scripturl?' + this.options[this.selectedIndex].value;"~;
   if ($templatejump == 1) {    if ( $templatejump == 1 ) {
       $action = 'action=';        $action   = 'action=';
       $onchange = '';         $onchange = q{}; 
   }    }
   $selecthtml = qq~    $selecthtml = qq~
<form method="post" action="$scripturl?$action" name="jump" style="display: inline;">            <form method="post" action="$scripturl?$action" style="display: inline;">
<select name="values"$onchange>                <select name="values"$onchange>
   <option value="" class="forumjump">$jumpto_txt{'to'}</option>\n                     <option value="" class="forumjump">$jumpto_txt{'to'}</option> 
   <option value="gohome">$img_txt{'103'}</option>\n~;                     <option value="gohome">$img_txt{'103'}</option>~; 
   
   ## as guests don't have these, why show them?    ## as guests do not have these, why show them?
   if (!$iamguest) {    if ( !$iamguest ) {
       $selecthtml .= qq~         $pm_lev = PMlev(); 
   <option value="action=im" class="forumjumpcatm">$jumpto_txt{'mess'}</option>~ if $PM_level == 1 || ($PM_level == 2 && ($iamadmin || $iamgmod || $iammod)) || ($PM_level == 3 && ($iamadmin || $iamgmod));         if ( $pm_lev == 1 ) { 
       $selecthtml .= qq~            $selecthtml .= qq~
   <option value="action=shownotify" class="forumjumpcatmf">$jumpto_txt{'note'}</option>                     <option value="action=im" class="forumjumpcatm">$jumpto_txt{'mess'}</option>~; 
   <option value="action=favorites" class="forumjumpcatm">$jumpto_txt{'fav'}</option>~;         } 
   }         $selecthtml .= qq~ 
                     <option value="action=shownotify" class="forumjumpcatmf">$jumpto_txt{'note'}</option>
   # drop in recent topics/posts lists. guests can see if browsing permitted                     <option value="action=favorites" class="forumjumpcatm">$jumpto_txt{'fav'}</option>~; 
   $selecthtml .= qq~     } 
   <option value="action=recent;display=10">$recent_txt{'recentposts'}</option>  
   <option value="action=recenttopics;display=10">$recent_txt{'recenttopic'}</option>\n~;     # drop in recent topics/posts lists. guests can see if browsing permitted 
     $selecthtml .= qq~
   unless ($mloaded == 1) { require "$boardsdir/forum.master"; }                     <option value="action=recent;display=10">$recent_txt{'recentposts'}</option> 
   foreach $catid (@categoryorder) {                     <option value="action=recenttopics;display=10">$recent_txt{'recenttopic'}</option>\n~; 
       @bdlist = split(/,/, $cat{$catid});  
       ($catname, $catperms) = split(/\|/, $catinfo{"$catid"});     get_forum_master(); 
     foreach my $catid (@categoryorder) {
       $cataccess = &CatAccess($catperms);         my @bdlist = split /,/xsm, $cat{$catid}; 
       if (!$cataccess) { next; }         my ( $catname, $catperms ) = split /\|/xsm, $catinfo{"$catid"}; 
       &ToChars($catname);  
       ## I've removed the dashed bands and css handles the cat highlighting.         my $cataccess = CatAccess($catperms); 
       $selecthtml .= $INFO{'catselect'} eq $catid ? qq~    <option selected=\"selected\" value="catselect=$catid" class="forumjumpcat">&raquo;&raquo; $catname</option>\n~ : qq~ <option value="catselect=$catid" class="forumjumpcat">$catname</option>\n~;         if ( !$cataccess ) { next; } 
       foreach $board (@bdlist) {         ToChars($catname); 
           ($boardname, $boardperms, $boardview) = split(/\|/, $board{"$board"});  
           &ToChars($boardname);         $selecthtml .= 
           my $access = &AccessCheck($board, '', $boardperms);           $INFO{'catselect'} eq $catid 
           if (!$iamadmin && $access ne "granted" && $boardview != 1) { next; }           ? qq~    <option selected="selected" value="catselect=$catid" class="forumjumpcat">&raquo;&raquo; $catname</option>\n~ 
           if ($board eq $annboard && !$iamadmin && !$iamgmod) { next; }           : qq~    <option value="catselect=$catid" class="forumjumpcat">$catname</option>\n~; 
   
           if ($board eq $currentboard) { $selecthtml .= $INFO{'num'} ? "   <option value=\"board=$board\" class=\"forumcurrentboard\">&nbsp; - $boardname &#171;&#171;</option>\n" : "   <option selected=\"selected\" value=\"board=$board\" class=\"forumcurrentboard\">&raquo;&raquo; $boardname</option>\n"; }         my $indent = -2; 
           else { $selecthtml .= "   <option value=\"board=$board\">&nbsp; - $boardname</option>\n"; }  
       }         *jump_subboards = sub { 
   }             my @x = @_; 
   $selecthtml .= qq~</select>             $indent += 2; 
<noscript><input type="submit" value="$maintxt{'32'}" class="button" /></noscript>             foreach my $board (@x) { 
</form>~;                 my $dash; 
                 if ( $indent > 0 ) { $dash = q{-}; }
   
                 my ( $boardname, $boardperms, $boardview ) =
                   split /\|/xsm, $board{"$board"};
                 ToChars($boardname);
                 my $access = AccessCheck( $board, q{}, $boardperms );
                 if ( !$iamadmin && $access ne 'granted' && $boardview != 1 ) {
                     next;
                 }
                 if ( ${ $uid . $board }{'brdpasswr'} ) {
                     my $bdmods = ${ $uid . $board }{'mods'};
                     $bdmods =~ s/\, /\,/gsm;
                     $bdmods =~ s/\ /\,/gsm;
                     my %moderators = ();
                     my $pswiammod  = 0;
                     foreach my $curuser ( split /\,/xsm, $bdmods ) {
                         if ( $username eq $curuser ) { $pswiammod = 1; }
                     }
                     my $bdmodgroups = ${ $uid . $board }{'modgroups'};
                     $bdmodgroups =~ s/\, /\,/gsm;
                     my %moderatorgroups = ();
   
                     foreach my $curgroup ( split /\,/xsm, $bdmodgroups ) {
                         if ( ${ $uid . $username }{'position'} eq $curgroup ) {
                             $pswiammod = 1;
                         }
                         foreach my $memberaddgroups ( split /\, /sm,
                             ${ $uid . $username }{'addgroups'} )
                         {
                             chomp $memberaddgroups;
                             if ( $memberaddgroups eq $curgroup ) {
                                 $pswiammod = 1;
                                 last;
                             }
                         }
                     }
                     my $cookiename = "$cookiepassword$board$username";
                     my $crypass    = ${ $uid . $board }{'brdpassw'};
   
                     if (   !$iamadmin
                         && !$iamgmod
                         && !$pswiammod
                         && $yyCookies{$cookiename} ne $crypass )
                     {
                         next;
                     }
                 }
                 if (   $board eq $annboard
                     && !$iamadmin
                     && !$iamgmod
                     && !$iamfmod )
                 {
                     next;
                 }
   
                 if ( $board eq $currentboard ) {
                     $selecthtml .=
                       $INFO{'num'}
                       ? qq~    <option value="board=$board" class="forumcurrentboard">&nbsp;~
                       . ( '&nbsp;' x $indent )
                       . ( $dash x ( $indent / 2 ) )
                       . qq~ $boardname &\x23171;&\x23171;</option>\n~
                       : qq~    <option selected="selected" value="board=$board" class="forumcurrentboard">&raquo;&raquo; $boardname</option>\n~;
                 }
                 elsif ( !${ $uid . $board }{'canpost'} && $subboard{$board} ) {
                     $selecthtml .=
                         qq~    <option value="boardselect=$board">&nbsp;~
                       . ( '&nbsp;' x $indent )
                       . ( $dash x ( $indent / 2 ) )
                       . qq~ $boardname</option>\n~;
                 }
                 else {
                     $selecthtml .=
                         qq~    <option value="board=$board">&nbsp;~
                       . ( '&nbsp;' x $indent )
                       . ( $dash x ( $indent / 2 ) )
                       . qq~ $boardname</option>\n~;
                 }
   
                 if ( $subboard{$board} ) {
                     jump_subboards( split /\|/xsm, $subboard{$board} );
                 }
             }
             $indent -= 2;
         };
         jump_subboards(@bdlist);
     }
     $selecthtml .= qq~</select>
             </form>~;
     return $selecthtml;
} }
   
sub dojump { sub dojump {
   $yySetLocation = $scripturl . $FORM{'values'};    $yySetLocation = $scripturl . $FORM{'values'};
   &redirectexit;     redirectexit(); 
     return;
} }
   
sub spam_protection { sub spam_protection {
   unless ($timeout) { return; }     return if !$timeout || $iamadmin; 
   my ($time, $flood_ip, $flood_time, $flood, @floodcontrol);     my ( $flood_ip, $flood_time, $flood, @floodcontrol ); 
   
   if (-e "$vardir/flood.txt") {    if ( -e "$vardir/flood.txt" ) {
       fopen(FLOOD, "$vardir/flood.txt");         fopen( FLOOD, "$vardir/flood.txt" ); 
       push(@floodcontrol, "$user_ip|$date\n");         push @floodcontrol, "$user_ip|$date\n"; 
       while (<FLOOD>) {        while (<FLOOD>) {
           chomp($_);             chomp $_; 
           ($flood_ip, $flood_time) = split(/\|/, $_);             ( $flood_ip, $flood_time ) = split /\|/xsm, $_; 
           if ($user_ip eq $flood_ip && $date - $flood_time <= $timeout) { $flood = 1; }             if ( $user_ip eq $flood_ip && $date - $flood_time <= $timeout ) { 
           elsif ($date - $flood_time < $timeout) { push(@floodcontrol, "$_\n"); }                 $flood = 1; 
       }            }
       fclose(FLOOD);             elsif ( $date - $flood_time < $timeout ) { 
   }                 push @floodcontrol, "$_\n"; 
   if ($flood && !$iamadmin && $action eq 'post2') { &Preview("$maintxt{'409'} $timeout $maintxt{'410'}"); }            }
   if ($flood && !$iamadmin) {         } 
       &fatal_error("post_flooding","$timeout $maintxt{'410'}");         fclose(FLOOD); 
   }    }
   fopen(FLOOD, ">$vardir/flood.txt", 1);     if ( $flood && !$iamadmin ) { 
   print FLOOD @floodcontrol;         if ( $action eq 'post2' ) { 
   fclose(FLOOD);             Preview("$maintxt{'409'} $timeout $maintxt{'410'}"); 
         }
         else {
             fatal_error( 'post_flooding', "$timeout $maintxt{'410'}" );
         }
     }
     fopen( FLOOD, ">$vardir/flood.txt", 1 );
     print {FLOOD} @floodcontrol or croak "$croak{'print'} FLOOD";
     fclose(FLOOD);
     return;
  }
   
  sub SpamQuestion {
     srand;
     fopen( SPAMQUESTIONS, "<$langdir/$language/spam.questions" )
       or fatal_error( 'cannot_open', "$langdir/$language/spam.questions", 1 );
     while (<SPAMQUESTIONS>) {
         rand($INPUT_LINE_NUMBER) < 1 && ( $spam_question_rand = $_ );
     }
     fclose(SPAMQUESTIONS);
     chomp $spam_question_rand;
     ( $spam_question_id, $spam_question, undef, $spam_questions_case, $spam_image ) =
       split /\|/xsm, $spam_question_rand;
     $spam_image = $spam_image ? qq~<div style="margin-top: .5em;"><img src="$imagesdir/Spam_Img/$spam_image" alt="" /></div>~ : q{};
     return;
  }
   
  sub SpamQuestionCheck {
     my ( $verification_question, $verification_question_id ) = @_;
     fopen( SPAMQUESTIONS, "<$langdir/$language/spam.questions" )
       or fatal_error( 'cannot_open', "$langdir/$language/spam.questions", 1 );
     @spam_questions = <SPAMQUESTIONS>;
     fclose(SPAMQUESTIONS);
     foreach my $verification_question (@spam_questions) {
         chomp $verification_question;
         if ( $verification_question =~ /$verification_question_id/xsm ) {
             ( undef, undef, $verification_answer, $spam_questions_case, undef ) =
               split /\|/xsm, $verification_question;
         }
     }
     $verification_question =~ s/\A\s+//xsm;
     $verification_question =~ s/\s+\Z//xsm;
     if ( !$spam_questions_case ) {
         $verification_answer   = lc $verification_answer;
         $verification_question = lc $verification_question;
     }
     if ( $verification_question eq q{} ) {
         fatal_error('no_verification_question');
     }
     @verificationanswer = split /,/xsm, $verification_answer;
     foreach (@verificationanswer) {
         $_ =~ s/\A\s+//xsm;
         $_ =~ s/\s+\Z//xsm;
     }
     if ( !grep { $verification_question eq $_ } @verificationanswer ) {
         fatal_error('wrong_verification_question');
     }
     return;
} }
   
sub CountChars { sub CountChars {
   $convertstr =~ s/&#32;/ /g; # why? where? (deti)    $convertstr =~ s/&\x2332;/ /gsm;    # why? where? (deti)
     #length does not always function properly with UTF-8 - convert UTF-8 to internal Perl utf8
     if ( $yymycharset eq 'UTF-8' ) {
         require utf8;
         require Encode;
         Encode->import( decode_utf8, encode_utf8 );
         $convertstr = decode_utf8($convertstr);
     }
   
     $cliped = 0;
     my ( $string, $curstring, $stinglength, $teststring );
     foreach my $string ( split /\s+/xsm, $convertstr ) {
       CHECKAGAIN:
   
         # jump over HTML-tags
         if ( $curstring =~ /<[\/a-z][^>]*$/ixsm ) {
             if ( $string =~ /^([^>]*>)(.*)/xsm ) {
                 $curstring .= $1;
                 $convertcut += length $1;
                 if ($2) { $string = $2; goto CHECKAGAIN; }
             }
             else {
                 $curstring .= "$string ";
                 $convertcut += length($string) + 1;
             }
             next;
         }
   
   $cliped = 0;         # jump over YaBBC-tags if YaBBC is allowed 
   my ($string,$curstring,$stinglength,$teststring);         if ( $enable_ubbc && $curstring =~ /\[[\/a-z][^\]]*$/ixsm ) { 
   foreach $string (split(/\s+/, $convertstr)) {            if ( $string =~ /^([^\]]*\])(.*)/xsm ) {
       CHECKAGAIN:                 $curstring .= $1; 
       # jump over HTML-tags                 $convertcut += length $1; 
       if ($curstring =~ /<[\/a-z][^>]*$/i) {                 if ($2) { $string = $2; goto CHECKAGAIN; } 
           if ($string =~ /^([^>]*>)(.*)/) {             } 
               $curstring .= $1;             else { 
               $convertcut += length($1);                 $curstring .= "$string "; 
               if ($2) { $string = $2; goto CHECKAGAIN; }                 $convertcut += length($string) + 1; 
           } else {             } 
               $curstring .= "$string ";             next; 
               $convertcut += length($string) + 1;         } 
           }         $stinglength = length $string; 
           next;         $teststring  = $string; 
       }  
       # jump over YaBBC-tags if YaBBC is allowed         # correct length for HTML characters 
       if ($enable_ubbc && $curstring =~ /\[[\/a-z][^\]]*$/i) {         FromHTML($teststring); 
           if ($string =~ /^([^\]]*\])(.*)/) {         $convertcut += $stinglength - length $teststring; 
               $curstring .= $1;  
               $convertcut += length($1);         # correct length for special characters, YaBBC and HTML-Tags 
               if ($2) { $string = $2; goto CHECKAGAIN; }         $teststring = $string; 
           } else {         $teststring =~ s/\[ch\d{3,}?\]/ /igxsm; 
               $curstring .= "$string ";         $teststring =~ s/<.*?>|\[.*?\]//gxsm; 
               $convertcut += length($string) + 1;         $convertcut += $stinglength - length $teststring; 
           }  
           next;         $curstring .= "$string "; 
       }         $curstring =~ s/ <br $/<br /ism; 
       $stinglength = length($string);  
       $teststring = $string;         if ( $curstring =~ /(<[\/a-z][^>]*)$/ism ) { 
       # correct length for HTML characters             $convertcut += length $1; 
       &FromHTML($teststring);         } 
       $convertcut += $stinglength - length($teststring);         if ( $enable_ubbc && $curstring =~ /(\[[\/a-z][^\]]*)$/ism ) { 
             $convertcut += length $1;
       # correct length for speciall characters, YaBBC and HTML-Tags         } 
       $teststring = $string;  
       $teststring =~ s/\[ch\d{3,}?\]/ /ig;         if ( length($curstring) > $convertcut ) { 
       $teststring =~ s/<.*?>|\[.*?\]//g;             $cliped = 1; 
       $convertcut += $stinglength - length($teststring);             last; 
         }
       $curstring .= "$string ";     } 
       $curstring =~ s/ <br $/<br /i;     if ( $curstring =~ /( *<[\/a-z][^>]*)$/ism 
         || ( $enable_ubbc && $curstring =~ /( *\[[\/a-z][^\]]*)$/ism ) )
       if ($curstring =~ /(<[\/a-z][^>]*)$/is) {    {
           $convertcut += length($1);         $convertcut -= length $1; 
       }    }
       if ($enable_ubbc && $curstring =~ /(\[[\/a-z][^\]]*)$/is) {     $convertstr = substr $curstring, 0, $convertcut; 
           $convertcut += length($1);  
       }     # eliminate spaces, broken HTML-characters or special characters at the end 
     $convertstr =~ s/(\[(ch\d*)?|&[a-z]*| +)$//sm;
       if (length($curstring) > $convertcut) {    if ( $yymycharset eq 'UTF-8' ) {
           $cliped = 1;       $convertstr = encode_utf8($convertstr); 
           last;     } 
       }     return $convertstr; 
   }  
   if ($curstring =~ /( *<[\/a-z][^>]*)$/i || ($enable_ubbc && $curstring =~ /( *\[[\/a-z][^\]]*)$/i)) {  
       $convertcut -= length($1);  
   }  
   $convertstr = substr($curstring, 0, $convertcut);  
   # eliminate spaces, broken HTML-characters or special characters at the end  
   $convertstr =~ s/(\[(ch\d*)?|&[a-z]*| +)$//;  
} }
   
sub WrapChars { sub WrapChars {
   my ($tmpwrapstr,$length,$char,$curword,$tmpwrapcut);     my @x = @_; 
   my $wrapcut = $_[1];     my ( $tmpwrapstr, $length, $char, $curword, $tmpwrapcut ); 
   foreach $curword (split(/\s+/, $_[0])) {     my $wrapcut = $x[1]; 
       $char    = $curword;     foreach my $curword ( split /\s+/xsm, $x[0] ) { 
       $length  = 0;         $char    = $curword; 
       $curword = '';         $length  = 0; 
       while ($char ne '') {         $curword = q{}; 
           if   ( $char =~ s/^(&#?[a-z\d]+;)//i ) { $curword .= $1; }         while ( $char ne q{} ) { 
           else { $char =~ s/^(.)//;                $curword .= $1; }            if    ( $char =~ s/^(&\x23?[a-z\d]+;)//ism ) { $curword .= $1; }
           $length++;             elsif ( $char =~ s/^(.)//sm )             { $curword .= $1; } 
           if ($length >= $wrapcut) {             $length++; 
               $curword .= "<br />";             if ( $length >= $wrapcut ) { 
               $tmpwrapcut = $length = 0;                 $curword .= '<br />'; 
           }                 $tmpwrapcut = $length = 0; 
       }            }
       if ($tmpwrapstr && ($tmpwrapcut + $length) >= $wrapcut) {         } 
           $tmpwrapstr .= " $curword<br />";         if ( $tmpwrapstr && ( $tmpwrapcut + $length ) >= $wrapcut ) { 
           $tmpwrapcut  = 0;             $tmpwrapstr .= " $curword<br />"; 
       } elsif ($tmpwrapstr) {             $tmpwrapcut = 0; 
           $tmpwrapstr .= " $curword";         } 
           $tmpwrapcut += $length + 1;         elsif ($tmpwrapstr) { 
       } else {             $tmpwrapstr .= " $curword"; 
           $tmpwrapstr = $curword;             $tmpwrapcut += $length + 1; 
           $tmpwrapcut = $length;         } 
       }         else { 
   }             $tmpwrapstr = $curword; 
   $tmpwrapstr =~ s/(<br \/>)*$/<br \/>/;             $tmpwrapcut = $length; 
   $tmpwrapstr;         } 
     }
     $tmpwrapstr =~ s/(<br \/>)*$/<br \/>/sm;
     return $tmpwrapstr;
} }
   
# Out of: Escape.pm, v 3.28 2004/11/05 13:58:31 # Out of: Escape.pm, v 3.28 2004/11/05 13:58:31
# Original Modul at: http://search.cpan.org/~gaas/URI-1.35/URI/Escape.pm # Original Modul at: http://search.cpan.org/~gaas/URI-1.35/URI/Escape.pm
sub uri_escape { # usage: $safe = uri_escape( $string ) sub uri_escape {    # usage: $safe = uri_escape( $string )
   my $text = shift;    my $text = shift;
   return undef unless defined $text;  
   if (!%escapes) {     #    return undef unless defined $text; 
       # Build a char->hex map     $text || return; 
       for (0..255) { $escapes{chr($_)} = sprintf("%%%02X", $_) }     if ( !%escapes ) { 
   }  
   # Default unsafe characters. RFC 2732 ^(uric - reserved)         # Build a char->hex map 
   $text =~ s/([^A-Za-z0-9\-_.!~*'()])/ $escapes{$1} || $1 /ge;         for ( 0 .. 255 ) { $escapes{ chr $_ } = sprintf '%%%02X', $_ } 
   $text;     } 
   
     # Default unsafe characters. RFC 2732 ^(uric - reserved)
     $text =~ s/([^A-Za-z0-9\-_.!~*\x27()])/ $escapes{$1} || $1 /gesm;
   
     return $text;
} }
   
sub enc_eMail { sub enc_eMail {
   my ($title,$email,$subject,$body) = @_;    my ($title,$email,$subject,$body,$src) = @_;
   my $charset_value = 848 if $yycharset eq "windows-1251"; # Cyrillic decoding     my ($charset_value); 
     if ($yymycharset eq 'windows-1251') { $charset_value = 848;} # Cyrillic decoding
   
     my $email_length = length $email;
     my $code1 = generate_code($email_length);
     my $code2;
     for my $i ( 0 .. ( $email_length - 1 ) ) {
         $code2 .= chr( ord( substr $code1, $i, 1 )^ord( substr $email, $i, 1 ));
     }
     $code2 = uri_escape($code2);
   
     *enc_eMail_x = sub {
         my ( $x, $y, $z ) = @_;
         if ( !$y ) {
             $x = ord $x;
             if ( $charset_value && $x > 126 ) { $x += $charset_value; }
             $x = "&#$x";
         }
         elsif ($z) {
             $x =~ s/"/\\"/gxsm;
         }
   
         return $x;
     };
     my $subbody;
     if ($subject or $body) {
         $subject = uri_escape($subject);
         $body = uri_escape($body);
         $subbody = "?subject=$subject&body=$body";
         $subbody =~ s/(((<.+?>)|&\x23\d+;)|.)/ enc_eMail_x($1,$2,$3) /egsm;
     }
     $titlesp = $title;
     $titlesp =~ s/(((<.+?>)|&\x23\d+;)|.)/ enc_eMail_x($1,$2,$3) /egsm;
     if ($src || $yymycharset eq 'UTF-8') {$titlesp = $title;}
   
     return qq~<script type='text/javascript'>\nSpamInator('$titlesp',"$code1","$code2","&#109;&#97;&#105;&#108;&#92;&#117;&#48;&#48;&#55;&#52;&#111;&#92;&#117;&#48;&#48;&#51;&#97;",'$subbody');\n</script>~;
   
   my $email_length = length($email);  
   my $code1 = &generate_code($email_length);  
   my $code2;  
   for (my $i = 0; $i < $email_length; $i++) {  
       $code2 .= chr((ord(substr($code1,$i,1))^ord(substr($email,$i,1))));  
   }  
   $code2 = &uri_escape($code2);  
   
   my $subbody;  
   if ($subject or $body) {  
       $subject = &uri_escape($subject);  
       $body = &uri_escape($body);  
       $subbody = "?subject=$subject&body=$body";  
       $subbody =~ s/(((<.+?>)|&#\d+;)|.)/ &enc_eMail_x($1,$2,$3) /eg;  
   }  
   
   $title =~ s/(((<.+?>)|&#\d+;)|.)/ &enc_eMail_x($1,$2,$3) /eg;  
   
   return qq*<script type='text/javascript'>\n<!--\nSpamInator("$title","$code1","$code2","&#109;&#97;&#105;&#108;&#92;&#117;&#48;&#48;&#55;&#52;&#111;&#92;&#117;&#48;&#48;&#51;&#97;","$subbody");\n// -->\n</script><noscript>$maintxt{'noscript'}</noscript>*;  
   
   sub enc_eMail_x {  
       my ($x,$y,$z) = @_;  
       if (!$y) {  
           $x = ord($x);  
           $x += $charset_value if $charset_value && $x > 126;  
           $x = "&#$x";  
       } elsif ($z) {  
           $x =~ s/"/\\"/g;  
       }  
       $x;  
   }  
} }
   
sub generate_code { sub generate_code {
   my ($arrey_pos,$code);     my ($arrey_in) = @_; 
   my @arrey = ('a'..'q', 'C'..'O', '1'..'9', 'g'..'u', 'l'..'z', '9'..'1', 'H'..'W');     my ( $arrey_pos, $code ); 
     my @arrey = (
   for (my $i = 0; $i < $_[0]; $i++) {         'a' .. 'q', 'C' .. 'O', '1' .. '9', 'g' .. 'u', 
       $arrey_pos = int(rand($#arrey));         'l' .. 'z', '9' .. '1', 'H' .. 'W', 
       $code .= $arrey[$arrey_pos];     ); 
   }  
   $code;     foreach my $i ( 0 .. ( $arrey_in - 1 ) ) { 
         $arrey_pos = int rand $#arrey;
         $code .= $arrey[$arrey_pos];
     }
     return $code;
} }
   
sub FromChars { sub FromChars {
   $_[0] =~ s/&#(\d{3,});/ $1>127 ? "[ch$1]" : $& /egis;     ( $_[0] ) = @_; 
     ## This cannot be localized or unpacked ##
     $_[0] =~ s/&\x23(\d{3,});/ $1>127 ? "[ch$1]" : $& /egism;
   
     return $_[0];
} }
   
sub ToChars { sub ToChars {
   $_[0] =~ s/\[ch(\d{3,})\]/ $1>127 ? "\&#$1;" : '' /egis;     ( $_[0] ) = @_; 
     ## This cannot be localized or unpacked ##
     $_[0] =~ s/\[ch(\d{3,})\]/ $1>127 ? "\&\x23$1;" : q{} /egism;
     return $_[0];
} }
   
sub ToHTML { sub ToHTML {
   $_[0] =~ s/&/&amp;/g;     ( $_[0] ) = @_; 
   $_[0] =~ s/\}/\&#125;/g;     ## This cannot be localized or unpacked - damages smilies ## 
   $_[0] =~ s/\{/\&#123;/g;     $_[0] =~ s/&/&amp;/gsm; 
   $_[0] =~ s/\|/&#124;/g;     $_[0] =~ s/\}/\&\x23125;/gsm; 
   $_[0] =~ s/>/&gt;/g;     $_[0] =~ s/\{/\&\x23123;/gsm; 
   $_[0] =~ s/</&lt;/g;     $_[0] =~ s/\|/&\x23124;/gsm; 
   $_[0] =~ s/   /&nbsp; &nbsp;/g;     $_[0] =~ s/>/&gt;/gsm; 
   $_[0] =~ s/  /&nbsp; /g;     $_[0] =~ s/</&lt;/gsm; 
   $_[0] =~ s/"/&quot;/g;     $_[0] =~ s/   /&nbsp; &nbsp;/gsm; 
     $_[0] =~ s/  /&nbsp; /gsm;
     $_[0] =~ s/\x22/&quot;/gsm;
     return $_[0];
} }
   
sub FromHTML { sub FromHTML {
   $_[0] =~ s/&quot;/"/g;     ( $_[0] ) = @_; 
   $_[0] =~ s/&nbsp;/ /g;     ## This cannot be localized or unpacked ## 
   $_[0] =~ s/&lt;/</g;     $_[0] =~ s/&quot;/\x22/gsm; 
   $_[0] =~ s/&gt;/>/g;     $_[0] =~ s/&nbsp;/ /gsm; 
   $_[0] =~ s/&#124;/\|/g;     $_[0] =~ s/&lt;/</gsm; 
   $_[0] =~ s/&#123;/\{/g;     $_[0] =~ s/&gt;/>/gsm; 
   $_[0] =~ s/&#125;/\}/g;     $_[0] =~ s/&\x23124;/\|/gsm; 
   $_[0] =~ s/&amp;/&/g;     $_[0] =~ s/&\x23123;/\{/gsm; 
     $_[0] =~ s/&\x23125;/\}/gsm;
     $_[0] =~ s/&amp;/&/gsm;
     return $_[0];
} }
   
sub dopre { sub dopre {
   $_ = $_[0];     my ($inp) = @_; 
   $_ =~ s~<br \/>~\n~g;     $inp =~ s/<br \/>/\n/gxsm; 
   $_ =~ s~<br>~\n~g;     $inp =~ s/<br>/\n/gxsm; 
   return $_;     return $inp; 
} }
   
sub Split_Splice_Move { sub Split_Splice_Move {
   my $s_s_m = $_[0];     my ( $s_s_m, $s_s_n ) = @_; 
   my $ssm = 0;    my $ssm = 0;
   if (!$_[1]) { # Just for the subject of a message    if ( !$s_s_n ) {    # Just for the subject of a message
       $s_s_m =~ s/^(Re: )?\[m.*?\]/$maintxt{'758'}/;         $s_s_m =~ s/^(Re: )?\[m.*?\]/$maintxt{'758'}/sm; 
       return $s_s_m;        return $s_s_m;
   } elsif ($s_s_m =~ /\[m by=(.+?) destboard=(.+?) dest=(.+?)\]/) { # 'This Topic has been moved to' a different board     } 
       my ($mover, $destboard, $dest) = ($1, $2, $3); # Who moved the topic; destination board; destination id number     elsif ( $s_s_m =~ /\[m by=(.+?) destboard=(.+?) dest=(.+?)\]/sm ) 
       $mover = &decloak($mover);     {                   # 'This Topic has been moved to' a different board 
       &LoadUser($mover);         my ( $mover, $destboard, $dest ) = ( $1, $2, $3 ); 
       $board{$destboard} =~ /^(.+?)\|/;  
       return (qq~<b>$maintxt{'160'} <a href="$scripturl?num=$dest"><b>$maintxt{'160a'}</b></a> $maintxt{'160b'}</b> <a href="$scripturl?board=$destboard"><i><b>$1</b></i></a><b> $maintxt{'525'} <i>${$uid.$mover}{'realname'}</i></b>~,$dest);         # Who moved the topic; destination board; destination id number 
         $mover = decloak($mover);
   } elsif ($s_s_m =~ /\[m by=(.+?) dest=(.+?)\]/) { # 'The contents of this Topic have been moved to''this Topic'         LoadUser($mover); 
       my($mover, $dest) = ($1, $2); # Who moved the topic; destination id number         $board{$destboard} =~ /^(.+?)\|/xsm; 
       $mover = &decloak($mover);         return ( 
       &LoadUser($mover);  qq~<b>$maintxt{'160'} <a href="$scripturl?num=$dest"><b>$maintxt{'160a'}</b></a> $maintxt{'160b'}</b> <a href="$scripturl?board=$destboard"><i><b>$1</b></i></a><b> $maintxt{'525'} <i>${$uid.$mover}{'realname'}</i></b>~, 
       return (qq~<b>$maintxt{'160c'}</b> <a href="$scripturl?num=$dest"><i><b>$maintxt{'160d'}</b></i></a><b> $maintxt{'525'} <i>${$uid.$mover}{'realname'}</i></b>~,$dest);             $dest 
         );
   } elsif ($s_s_m =~ /^\[m\]/) { # Old style topic that was moved/spliced before this code     } 
       fopen(MOVEDFILE, "$datadir/$_[1].txt");     elsif ( $s_s_m =~ /\[m by=(.+?) dest=(.+?)\]/sm ) 
       (undef, undef, undef, undef, undef, undef, undef, undef, $s_s_m, undef) = split(/\|/, <MOVEDFILE>, 10);     {    # 'The contents of this Topic have been moved to''this Topic' 
       fclose(MOVEDFILE);         my ( $mover, $dest ) = 
       &ToChars($s_s_m);           ( $1, $2 );    # Who moved the topic; destination id number 
       $ssm = 1;         $mover = decloak($mover); 
   }         LoadUser($mover); 
         return (
   $ssm += $s_s_m =~ s/\[spliced\]/$maintxt{'160c'}/g; # The contents of this Topic have been moved to  qq~<b>$maintxt{'160c'}</b> <a href="$scripturl?num=$dest"><i><b>$maintxt{'160d'}</b></i></a><b> $maintxt{'525'} <i>${$uid.$mover}{'realname'}</i></b>~, 
   $ssm += $s_s_m =~ s/\[splicedhere\]|\[splithere\]/$maintxt{'160d'}/g; # this Topic             $dest 
   $ssm += $s_s_m =~ s/\[split\]/$maintxt{'160e'}/g; # Off-Topic replies have been moved to         ); 
   $ssm += $s_s_m =~ s/\[splithere_end\]/$maintxt{'160f'}/g; # .     } 
   $ssm += $s_s_m =~ s/\[moved\]/$maintxt{'160'}/g; # This Topic has been moved to     elsif ( $s_s_m =~ /^\[m\]/sm ) 
   $ssm += $s_s_m =~ s/\[movedhere\]/$maintxt{'161'}/g; # This Topic was moved here from     {    # Old style topic that was moved/spliced before this code 
   $ssm += $s_s_m =~ s/\[postsmovedhere1\]/$maintxt{'161a'}/g; # The last         fopen( MOVEDFILE, "$datadir/$_[1].txt" ); 
   $ssm += $s_s_m =~ s/\[postsmovedhere2\]/$maintxt{'161b'}/g; # Posts were moved here from         ( 
   $ssm += $s_s_m =~ s/\[move by\]/$maintxt{'525'}/g; # by             undef, undef, undef, undef,  undef, 
   if ($ssm) { # only if it was an internal s_s_m info             undef, undef, undef, $s_s_m, undef 
       $s_s_m =~ s~\[link=\s*(\S\w+\://\S+?)\s*\](.+?)\[/link\]~<a href="$1">$2</a>~g;         ) = split /\|/xsm, <MOVEDFILE>, 10; 
       $s_s_m =~ s~\[link=\s*(\S+?)\](.+?)\s*\[/link\]~<a href="http://$1">$2</a>~g;         fclose(MOVEDFILE); 
       $s_s_m =~ s~\[b\](.*?)\[/b\]~<b>$1</b>~g;         ToChars($s_s_m); 
       $s_s_m =~ s~\[i\](.*?)\[/i\]~<i>$1</i>~g;         $ssm = 1; 
   }    }
   return ($s_s_m,$ssm);  
     $ssm += $s_s_m =~ s/\[spliced\]/$maintxt{'160c'}/gxsm;
   
     # The contents of this Topic have been moved to
     $ssm += $s_s_m =~
       s/\[splicedhere\]|\[splithere\]/$maintxt{'160d'}/gxsm;    # this Topic
     $ssm += $s_s_m =~
       s/\[split\]/$maintxt{'160e'}/gxsm;  # Off-Topic replies have been moved to
     $ssm += $s_s_m =~ s/\[splithere_end\]/$maintxt{'160f'}/gxsm;    # .
     $ssm +=
       $s_s_m =~ s/\[moved\]/$maintxt{'160'}/gxsm; # This Topic has been moved to
     $ssm += $s_s_m =~
       s/\[movedhere\]/$maintxt{'161'}/gxsm;    # This Topic was moved here from
     $ssm += $s_s_m =~ s/\[postsmovedhere1\]/$maintxt{'161a'}/gxsm;    # The last
     $ssm += $s_s_m =~
       s/\[postsmovedhere2\]/$maintxt{'161b'}/gxsm;  # Posts were moved here from
     $ssm += $s_s_m =~ s/\[move by\]/$maintxt{'525'}/gxsm;    # by
   
     if ($ssm) {    # only if it was an internal s_s_m info
         $s_s_m =~
  s/\[link=\s*(\S\w+\:\/\/\S+?)\s*\](.+?)\[\/link\]/<a href="$1">$2<\/a>/gxsm;
         $s_s_m =~
  s/\[link=\s*(\S+?)\](.+?)\s*\[\/link\]/<a href="http:\/\/$1">$2<\/a>/gxsm;
         $s_s_m =~ s/\[b\](.*?)\[\/b\]/<b>$1<\/b>/gxsm;
         $s_s_m =~ s/\[i\](.*?)\[\/i\]/<i>$1<\/i>/gxsm;
     }
     return ( $s_s_m, $ssm );
} }
   
sub elimnests { sub elimnests {
   $_ = $_[0];     my ($inp) = @_; 
   $_ =~ s~\[/*shadow([^\]]*)\]~~ig;     $inp =~ s/\[\/*shadow([^\]]*)\]//igxsm;    #*/; 
   $_ =~ s~\[/*glow([^\]]*)\]~~ig;     $inp =~ s/\[\/*glow([^\]]*)\]//igxsm;      #*/; 
   return $_;     return $inp; 
} }
   
sub unwrap { sub unwrap {
   $codelang = $_[0];     my ( $codelang, $unwrapped ) = @_; 
   $unwrapped = $_[1];     $unwrapped =~ s/{yabbwrap}//gxsm; 
   $unwrapped =~ s~<yabbwrap>~~g;     $unwrapped = qq~\[code$codelang\]$unwrapped\[\/code\]~; 
   $unwrapped = qq~\[code$codelang\]$unwrapped\[\/code\]~;     return $unwrapped; 
   return $unwrapped;  
} }
   
sub wrap { sub wrap {
   if ($newswrap) { $linewrap = $newswrap; }    if ($newswrap) { $linewrap = $newswrap; }
   $message =~ s~ &nbsp; &nbsp; &nbsp;~\[tab\]~ig;     $message =~ s/ &nbsp; &nbsp; &nbsp;/\[tab\]/igsm; 
   $message =~ s~<br \/>~\n~g;     $message =~ s/<br \/>/\n/gsm; 
   $message =~ s~<br>~\n~g;     $message =~ s/<br>/\n/gxsm; 
   $message =~ s/((\[ch\d{3,}?\]){$linewrap})/$1\n/ig;     $message =~ s/((\[ch\d{3,}?\]){$linewrap})/$1\n/igsm; 
   
   &FromHTML($message);     FromHTML($message); 
   $message =~ s~[\n\r]~ <yabbbr> ~g;     $message =~ s/[\n\r]/ {yabbbr} /gsm; 
   my @words = split(/\s/, $message);     my @words = split /\s/xsm, $message; 
   $message = "";     $message = q{}; 
   foreach $cur (@words) {    foreach my $cur (@words) {
       if ($cur !~ m~www\.(\S+?)\.~ && $cur !~ m~[ht|f]tp://~ && $cur !~ m~\[\S*\]~ && $cur !~ m~\[\S*\s?\S*?\]~ && $cur !~ m~\[\/\S*\]~) { $cur =~ s~(\S{$linewrap})~$1\n~gi; }         if (   $cur !~ m{www\.(\S+?)\.}xsm 
       if ($cur !~ m~\[table(\S*)\](\S*)\[\/table\]~ && $cur !~ m~\[url(\S*)\](\S*)\[\/url\]~ && $cur !~ m~\[flash(\S*)\](\S*)\[\/flash\]~ && $cur !~ m~\[img(\S*)\](\S*)\[\/img\]~) {             && $cur !~ m/[ht|f]tp[s]{0,1}:\/\//xsm 
           $cur =~ s~(\[\S*?\])~ $1 ~g;             && $cur !~ m{\[\S*\]}xsm 
           @splitword = split(/\s/, $cur);             && $cur !~ m{\[\S*\s?\S*?\]}xsm 
           $cur = "";             && $cur !~ m{\[\/\S*\]}xsm ) 
           foreach $splitcur (@splitword) {        {
               if ($splitcur !~ m~www\.(\S+?)\.~ && $splitcur !~ m~[ht|f]tp://~ && $splitcur !~ m~\[\S*\]~) { $splitcur =~ s~(\S{$linewrap})~$1<yabbwrap>~gi; }             $cur =~ s/(\S{$linewrap})/$1\n/gism; 
               $cur .= $splitcur;         } 
           }         if (   $cur !~ m{\[table(\S*)\](\S*)\[\/table\]}xsm 
       }             && $cur !~ m{\[url(\S*)\](\S*)\[\/url\]}xsm 
       $message .= "$cur ";             && $cur !~ m{\[flash(\S*)\](\S*)\[\/flash\]}xsm 
   }             && $cur !~ m{\[img(\S*)\](\S*)\[\/img\]}xsm ) 
   $message =~ s~\[code((?:\s*).*?)\](.*?)\[\/code\]~&unwrap($1,$2)~eisg;         { 
   $message =~ s~ <yabbbr> ~\n~g;             $cur =~ s/(\[\S*?\])/ $1 /gxsm; 
   $message =~ s~<yabbwrap>~\n~g;             @splitword = split /\s/xsm, $cur; 
             $cur = q{};
   &ToHTML($message);             foreach my $splitcur (@splitword) { 
   $message =~ s~\[tab\]~ &nbsp; &nbsp; &nbsp;~ig;                 if (   $splitcur !~ m{www\.(\S+?)\.}xsm 
   $message =~ s~\n~<br />~g;                     && $splitcur !~ m/[ht|f]tp[s]{0,1}:\/\//xsm 
                     && $splitcur !~ m{\[\S*\]}xsm )
                 {
                     $splitcur =~ s/(\S{$linewrap})/$1{yabbwrap}/gism;
                 }
                 $cur .= $splitcur;
             }
         }
         $message .= "$cur ";
     }
     $message =~ s/\[code((?:\s*).*?)\](.*?)\[\/code\]/unwrap($1,$2)/eisgm;
     $message =~ s/\Q{yabbbr} \E/\n/gsm;
     $message =~ s/{yabbwrap}/\n/gsm;
   
     ToHTML($message);
     $message =~ s/\[tab\]/ &nbsp; &nbsp; &nbsp;/igsm;
     $message =~ s/\n/<br \/>/gsm;
     return;
} }
   
sub wrap2 { sub wrap2 {
   $message =~ s#<a href=(\S*?)(\s[^>]*)?>(\S*?)</a># my ($mes,$out,$i) = ($3,"",1); { while ($mes ne "") { if ($mes =~ s/^(<.+?>)//) { $out .= $1; } elsif ($mes =~ s/^(&.+?;|\[ch\d{3,}\]|.)//) { last if $i > $linewrap; $i++; $out .= $1; if ($mes eq "") { $i--; last; } } } } "<a href=$1$2>$out" . ($i > $linewrap ? "..." : "") . "</a>" #eig;     $message =~ 
  s/<a href=(\S*?)(\s[^>]*)?>(\S*?)<\/a>/ my ($mes,$out,$i) = ($3,q{},1); { while ($mes ne q{}) { if ($mes =~ s\/^(<.+?>)\/\/) { $out .= $1; } elsif ($mes =~ s\/^(&.+?;|\[ch\d{3,}\]|.)\/\/) { last if $i > $linewrap; $i++; $out .= $1; if ($mes eq q{}) { $i--; last; } } } } "<a href=$1$2>$out" . ($i > $linewrap ? q{...} : q{}) . '<\/a>' /eigsm;
     return;
} }
   
sub MembershipGet { sub MembershipGet {
   if (fopen(FILEMEMGET, "$memberdir/members.ttl")) {    if ( fopen( FILEMEMGET, "$memberdir/members.ttl" ) ) {
       $_ = <FILEMEMGET>;        $_ = <FILEMEMGET>;
       chomp;        chomp;
       fclose(FILEMEMGET);        fclose(FILEMEMGET);
       return split(/\|/, $_);         return split /\|/xsm, $_; 
   } else {     } 
       my @ttlatest = &MembershipCountTotal;     else { 
       return @ttlatest;         my @ttlatest = MembershipCountTotal(); 
   }         return @ttlatest; 
     }
} }
   
{ {
   my %yyOpenMode = (    my %yyOpenMode = (
       '+>>' => 5,        '+>>' => 5,
       '+>'  => 4,        '+>'  => 4,
       '+<'  => 3,        '+<'  => 3,
       '>>'  => 2,        '>>'  => 2,
       '>'   => 1,        '>'   => 1,
       '<'   => 0,        '<'   => 0,
       ''    => 0,        q{}   => 0,
   );    );
   
   # fopen: opens a file. Allows for file locking and better error-handling.    # fopen: opens a file. Allows for file locking and better error-handling.
   sub fopen ($$;$) {    sub fopen ($$;$) {
       my ($pack, $file, $line) = caller;         my ( $filehandle, $filename, $usetmp ) = @_; 
       $file_open++;         my ( $pack,       $file,     $line )   = caller; 
       my ($filehandle, $filename, $usetmp) = @_;         $file_open++; 
       ## make life easier - spot a file that's not closed!        ## make life easier - spot a file that is not closed!
       if ($debug) { $openfiles .= qq~$filehandle (~ . sprintf("%.4f", (time - $START_TIME)) . qq~)     $filename~; }         if ($debug) { 
       my ($flockCorrected, $cmdResult, $openMode, $openSig);             LoadLanguage('Debug'); 
             $openfiles .=
       $serveros = "$^O";                 qq~$filehandle (~ 
       if ($serveros =~ m/Win/ && substr($filename, 1, 1) eq ":") {               . sprintf( '%.4f', ( time - $START_TIME ) ) 
           $filename =~ s~\\~\\\\~g; # Translate windows-style \ slashes to windows-style \\ escaped slashes.               . qq~)     $filename~; 
           $filename =~ s~/~\\\\~g;  # Translate unix-style / slashes to windows-style \\ escaped slashes.         } 
       } else {         my ( $flockCorrected, $cmdResult, $openMode, $openSig ); 
           $filename =~ tr~\\~/~;    # Translate windows-style \ slashes to unix-style / slashes.  
       }         $serveros = $OSNAME;    #"$^O"; 
       $LOCK_EX     = 2;                 # You can probably keep this as it is set now.                                 #magic punctuation variable BAD # 
       $LOCK_UN     = 8;                 # You can probably keep this as it is set now.         if ( $serveros =~ m/Win/sm && substr( $filename, 1, 1 ) eq q{:} ) { 
       $LOCK_SH     = 1;                 # You can probably keep this as it is set now.             $filename =~ s/\\/\\\\/gxsm; 
       $usetempfile = 0;                 # Write to a temporary file when updating large files.  
         # Translate windows-style \ slashes to windows-style \\ escaped slashes.
       # Check whether we want write, append, or read.             $filename =~ s/\//\\\\/gxsm; 
       $filename =~ m~\A([<>+]*)(.+)~;  
       $openSig  = $1                    || '';            # Translate unix-style / slashes to windows-style \\ escaped slashes. 
       $filename = $2                    || $filename;         } 
       $openMode = $yyOpenMode{$openSig} || 0;         else { 
             $filename =~ tr~\\~/~;
       $filename =~ s~[^/\\0-9A-Za-z#%+\,\-\ \.\:@^_]~~g;    # Remove all inappropriate characters.  
             # Translate windows-style \ slashes to unix-style / slashes.
       if ($filename =~ m~/\.\./~) { &fatal_error("cannot_open","$filename. $maintxt{'609'}"); }        }
         $LOCK_EX     = 2; # You can probably keep this as it is set now.
       # If the file doesn't exist, but a backup does, rename the backup to the filename         $LOCK_UN     = 8; # You can probably keep this as it is set now. 
       if (!-e $filename && -e "$filename.bak") { rename("$filename.bak", "$filename"); }         $LOCK_SH     = 1; # You can probably keep this as it is set now. 
       if (-z $filename && -e "$filename.bak") { rename("$filename.bak", "$filename"); }         $usetempfile = 0; # Write to a temporary file when updating large files. 
   
       $testfile = $filename;         # Check whether we want write, append, or read. 
       if ($use_flock == 2 && $openMode) {        if ( $filename =~ m/\A([<>+]*)(.+)/sm ) {
           my $count;             $openSig  = $1 || q{}; 
           while ($count < 15) {             $filename = $2 || $filename; 
               if (-e $filehandle) { sleep 2; }        }
               else { last; }         $openMode = $yyOpenMode{$openSig} || 0; 
               ++$count;  
           }         $filename =~ s/[^\/\\0-9A-Za-z#%+\,\-\ \.\:@^_]//gxsm; 
           unlink($filehandle) if ($count == 15);  
           local *LFH;         # Remove all inappropriate characters. 
           CORE::open(LFH, ">$filehandle");  
           $yyLckFile{$filehandle} = *LFH;         if ( $filename =~ m{/\.\./}sm ) { 
       }             fatal_error( 'cannot_open', "$filename. $maintxt{'609'}" ); 
         }
       if ($use_flock && $openMode == 1 && $usetmp && $usetempfile && -e $filename) {  
           $yyTmpFile{$filehandle} = $filename;  # If the file doesn't exist, but a backup does, rename the backup to the filename 
           $filename .= '.tmp';         if ( !-e $filename && -e "$filename.bak" ) { 
       }             rename "$filename.bak", "$filename"; 
         }
       if ($openMode > 2) {        if ( -z $filename && -e "$filename.bak" ) {
           if ($openMode == 5) { $cmdResult = CORE::open($filehandle, "+>>$filename"); }             rename "$filename.bak", "$filename"; 
           elsif ($use_flock == 1) {         } 
               if ($openMode == 4) {  
                   if (-e $filename) {         $testfile = $filename; 
         if ( $use_flock == 2 && $openMode ) {
                       # We are opening for output and file locking is enabled...             my $count; 
                       # read-open() the file rather than write-open()ing it.             while ( $count < 15 ) { 
                       # This is to prevent open() from clobbering the file before                 if   ( -e $filehandle ) { sleep 2; } 
                       # checking if it is locked.                 else                    { last; } 
                       $flockCorrected = 1;                 ++$count; 
                       $cmdResult = CORE::open($filehandle, "+<$filename");             } 
                   } else {             if ( $count == 15 ) { unlink $filehandle; } 
                       $cmdResult = CORE::open($filehandle, "+>$filename");             *LFH = undef; 
                   }             CORE::open( LFH, ">$filehandle" ); 
               } else {             $yyLckFile{$filehandle} = *LFH; 
                   $cmdResult = CORE::open($filehandle, "+<$filename");         } 
               }  
           } elsif ($openMode == 4) {         if (   $use_flock 
               $cmdResult = CORE::open($filehandle, "+>$filename");             && $openMode == 1 
           } else {             && $usetmp 
               $cmdResult = CORE::open($filehandle, "+<$filename");             && $usetempfile 
           }             && -e $filename ) 
       } elsif ($openMode == 1 && $use_flock == 1) {        {
           if (-e $filename) {             $yyTmpFile{$filehandle} = $filename; 
             $filename .= '.tmp';
               # We are opening for output and file locking is enabled...         } 
               # read-open() the file rather than write-open()ing it.  
               # This is to prevent open() from clobbering the file before         if ( $openMode > 2 ) { 
               # checking if it is locked.             if ( $openMode == 5 ) { 
               $flockCorrected = 1;                 $cmdResult = CORE::open( $filehandle, "+>>$filename" ); 
               $cmdResult = CORE::open($filehandle, "+<$filename");             } 
           } else {            elsif ( $use_flock == 1 ) {
               $cmdResult = CORE::open($filehandle, ">$filename");                 if ( $openMode == 4 ) { 
           }                     if ( -e $filename ) { 
       } elsif ($openMode == 1) {  
           $cmdResult = CORE::open($filehandle, ">$filename");    # Open the file for writing                      # We are opening for output and file locking is enabled... 
       } elsif ($openMode == 2) {                      # read-open() the file rather than write-open()ing it. 
           $cmdResult = CORE::open($filehandle, ">>$filename");    # Open the file for append                      # This is to prevent open() from clobbering the file before 
       } elsif ($openMode == 0) {                      # checking if it is locked. 
           $cmdResult = CORE::open($filehandle, $filename);        # Open the file for input                         $flockCorrected = 1; 
       }                         $cmdResult = CORE::open( $filehandle, "+<$filename" ); 
       unless ($cmdResult)      { return 0; }                    }
       if     ($flockCorrected) {                    else {
                         $cmdResult = CORE::open( $filehandle, "+>$filename" );
           # The file was read-open()ed earlier, and we have now verified an exclusive lock.                     } 
           # We shall now clobber it.                 } 
           flock($filehandle, $LOCK_EX);                 else { 
           if ($faketruncation) {                     $cmdResult = CORE::open( $filehandle, "+<$filename" ); 
               CORE::open(OFH, ">$filename");                 } 
               unless ($cmdResult) { return 0; }            }
               print OFH '';             elsif ( $openMode == 4 ) { 
               CORE::close(OFH);                 $cmdResult = CORE::open( $filehandle, "+>$filename" ); 
           } else {             } 
               truncate(*$filehandle, 0) || &fatal_error("truncation_error","$filename");             else { 
           }                 $cmdResult = CORE::open( $filehandle, "+<$filename" ); 
           seek($filehandle, 0, 0);             } 
       } elsif ($use_flock == 1) {         } 
           if ($openMode) { flock($filehandle, $LOCK_EX); }         elsif ( $openMode == 1 && $use_flock == 1 ) { 
           else { flock($filehandle, $LOCK_SH); }             if ( -e $filename ) { 
       }  
       return 1;                 # We are opening for output and file locking is enabled... 
   }                 # read-open() the file rather than write-open()ing it. 
                 # This is to prevent open() from clobbering the file before
   # fclose: closes a file, using Windows 95/98/ME-style file locking if necessary.                 # checking if it is locked. 
   sub fclose ($) {                 $flockCorrected = 1; 
       my ($pack, $file, $line) = caller;                 $cmdResult = CORE::open( $filehandle, "+<$filename" ); 
       $file_close++;             } 
       my $filehandle = $_[0];             else { 
       if ($debug) { $openfiles .= qq~     $filehandle (~ . sprintf("%.4f", (time - $START_TIME)) . qq~)\n[$pack, $file, $line]\n\n~; }                 $cmdResult = CORE::open( $filehandle, ">$filename" ); 
       CORE::close($filehandle);             } 
       if ($use_flock == 2) {         } 
           if (exists $yyLckFile{$filehandle} && -e $filehandle) {        elsif ( $openMode == 1 ) {
               CORE::close($yyLckFile{$filehandle});             $cmdResult = CORE::open( $filehandle, ">$filename" ); 
               unlink($filehandle);  
               delete $yyLckFile{$filehandle};             # Open the file for writing 
           }        }
       }         elsif ( $openMode == 2 ) { 
       if ($yyTmpFile{$filehandle}) {             $cmdResult = CORE::open( $filehandle, ">>$filename" ); 
           my $bakfile = $yyTmpFile{$filehandle};  
           if ($use_flock == 1) {             # Open the file for append 
         }
               # Obtain an exclusive lock on the file.         elsif ( $openMode == 0 ) { 
               # ie: wait for other processes to finish...             $cmdResult = 
               local *FH;               CORE::open( $filehandle, $filename );    # Open the file for input 
               CORE::open(FH, $bakfile);         } 
               flock(FH, $LOCK_EX);         if ( !$cmdResult ) { return 0; } 
               CORE::close(FH);         if ($flockCorrected) { 
           }  
  # The file was read-open()ed earlier, and we have now verified an exclusive lock.
           # Switch the temporary file with the original.  # We shall now clobber it. 
           unlink("$bakfile.bak") if (-e "$bakfile.bak");             flock $filehandle, $LOCK_EX; 
           rename($bakfile, "$bakfile.bak");             if ($faketruncation) { 
           rename("$bakfile.tmp", $bakfile);                 CORE::open( OFH, ">$filename" ); 
           delete $yyTmpFile{$filehandle};                 if ( !$cmdResult ) { return 0; } 
           if (-e $bakfile) {                 print {OFH} q{} or croak "$croak{'print'} OFH"; 
               unlink("$bakfile.bak");    # Delete the original file to save space.                 CORE::close(OFH); 
           }            }
       }             else { 
       return 1;                 truncate( *{$filehandle}, 0 ) 
   }                   or fatal_error( 'truncation_error', "$filename" ); 
             }
             seek $filehandle, 0, 0;
         }
         elsif ( $use_flock == 1 ) {
             if   ($openMode) { flock $filehandle, $LOCK_EX; }
             else             { flock $filehandle, $LOCK_SH; }
         }
         return 1;
     }
   
  # fclose: closes a file, using Windows 95/98/ME-style file locking if necessary.
     sub fclose ($) {
         my ($filehandle) = @_;
         my ( $pack, $file, $line ) = caller;
         $file_close++;
         if ($debug) {
             LoadLanguage('Debug');
             $openfiles .=
                 qq~     $filehandle (~
               . sprintf( '%.4f', ( time - $START_TIME ) )
               . qq~)\n[$pack, $file, $line]\n\n~;
         }
         CORE::close($filehandle);
         if ( $use_flock == 2 ) {
             if ( exists $yyLckFile{$filehandle} && -e $filehandle ) {
                 CORE::close( $yyLckFile{$filehandle} );
                 unlink $filehandle;
                 delete $yyLckFile{$filehandle};
             }
         }
         if ( $yyTmpFile{$filehandle} ) {
             my $bakfile = $yyTmpFile{$filehandle};
             if ( $use_flock == 1 ) {
   
                 # Obtain an exclusive lock on the file.
                 # ie: wait for other processes to finish...
                 *FH = undef;
                 CORE::open( FH, $bakfile );
                 flock FH, $LOCK_EX;
                 CORE::close(FH);
             }
   
             # Switch the temporary file with the original.
             if ( -e "$bakfile.bak" ) { unlink "$bakfile.bak"; }
             rename $bakfile, "$bakfile.bak";
             rename "$bakfile.tmp", $bakfile;
             delete $yyTmpFile{$filehandle};
             if ( -e $bakfile ) {
                 unlink "$bakfile.bak";
   
                 # Delete the original file to save space.
             }
         }
         return 1;
     }
   
}    # / my %yyOpenMode }    # / my %yyOpenMode
   
sub KickGuest { sub KickGuest {
   require "$sourcedir/LogInOut.pl";     require Sources::LogInOut; 
   $sharedLogin_title = "$maintxt{'633'}";    $sharedLogin_title = "$maintxt{'633'}";
   $sharedLogin_text  = qq~<br />$maintxt{'634'}<br />$maintxt{'635'} <a href="$scripturl?action=register">$maintxt{'636'}</a> $maintxt{'637'}<br /><br />~;     $sharedLogin_text = 
   $yymain .= &sharedLogin;  qq~<br />$maintxt{'634'}<br />$maintxt{'635'} <a href="$scripturl?action=register">$maintxt{'636'}</a> $maintxt{'637'}<br /><br />~; 
   $yytitle = "$maintxt{'34'}";     $yymain .= sharedLogin(); 
   &template;     $yytitle = "$maintxt{'34'}"; 
     template();
     return;
} }
   
sub WriteLog { sub WriteLog {
   # comment out (#) the next line if you have problems with     if (   $action eq 'ajxmessage' 
   # 'Reverse DNS lookup timeout causes slow page loads'         || $action eq 'ajximmessage' 
   # (http://www.yabbforum.com/community/YaBB.pl?num=1199991357)         || $action eq 'ajxcal' ) 
   # Search Engine identification and display will be turned off     { 
   my $user_host = (gethostbyaddr(pack("C4", split(/\./, $user_ip)), 2))[0];         return; 
     }
   my ($name, $logtime, @new_log);  
   my $field = $username;     # comment out (#) the next line if you have problems with 
   if ($field eq "Guest") { if ($guestaccess) { $field = $user_ip; } else { return; } }     # 'Reverse DNS lookup timeout causes slow page loads' 
     # (http://www.yabbforum.com/community/YaBB.pl?num=1199991357)
   my $onlinetime = $date - ($OnlineLogTime * 60);     # Search Engine identification and display will be turned off 
   fopen(LOG, "+<$vardir/log.txt");  
   @logentries = <LOG>; # Global variable     my $user_host = 
   foreach (@logentries) {       ( gethostbyaddr pack( 'C4', split /\./xsm, $user_ip ), 2 )[0]; 
       ($name, $logtime, undef) = split(/\|/, $_, 3);  
       if ($name ne $user_ip && $name ne $field && $logtime >= $onlinetime) { push(@new_log, $_); }     my ( $name, $logtime, @new_log ); 
   }     my $onlinetime = $date - ( $OnlineLogTime * 60 ); 
   seek LOG, 0, 0;     my $field = $username; 
   truncate LOG, 0;     if ( $field eq 'Guest' ) { 
   print LOG ("$field|$date|$user_ip|$user_host#$ENV{'HTTP_USER_AGENT'}\n", @new_log);         if ($guestaccess) { $field = $user_ip; } 
   fclose(LOG);         else              { return; } 
     }
   if (!$action && $enableclicklog == 1) {  
       $onlinetime = $date - ($ClickLogTime * 60);     fopen( LOG, "<$vardir/log.txt" ); 
       fopen(LOG, "+<$vardir/clicklog.txt", 1);     @logentries = <LOG>;    # Global variable 
       @new_log = <LOG>;     fclose( LOG ); 
       seek LOG, 0, 0;     chomp @logentries; 
       truncate LOG, 0;     foreach (@logentries) { 
       print LOG "$field|$date|$ENV{'REQUEST_URI'}|" . ($ENV{'HTTP_REFERER'} =~ m~$boardurl~i ? '' : $ENV{'HTTP_REFERER'}) . "|$ENV{'HTTP_USER_AGENT'}\n";         ( $name, $logtime, undef ) = split /\|/xsm, $_, 3; 
       foreach (@new_log) { if ((split(/\|/, $_, 3))[1] >= $onlinetime) { print LOG $_; } }         if ( $name ne $user_ip && $name ne $field && $logtime >= $onlinetime ) { 
       fclose(LOG);             push @new_log, "$_\n"; 
   }        }
     }
     my $hostin = qq~$user_host#$ENV{'HTTP_USER_AGENT'}~;
  #    $hostin =~ s/\x0//gsm;
     $hostin =~ s/chr(32)//gxms;
     $hostin =~ s/\s+/ /gxms;
     $hostin =~ s/\x7C//gsm;
     $hostin =~ s/[^\x21-\x7E]+$//gsm;
     fopen( LOG, ">$vardir/log.txt" );
     print {LOG} (
  "$field|$date|$user_ip|$hostin|$username|$currentboard|" 
           . (
             ( !$action && $INFO{'num'} && $currentboard )
             ? 'display' 
             : (
                 (
                         !$action
                       && $ENV{'SCRIPT_FILENAME'} =~ /\/AdminIndex\.(pl|cgi)/sm
                 ) ? 'admincenter' : $action
             )
           )
           . "|$INFO{'username'}|$curnum\n",
         @new_log
     ) or croak qq~$croak{'print'} log.txt~;
     fclose(LOG);
   
     if ( !$action && $enableclicklog == 1 ) {
         $onlinetime = $date - ( $ClickLogTime * 60 );
         fopen( LOG, "<$vardir/clicklog.txt", 1 );
         @new_log = <LOG>;
         fclose( LOG );
         my $hostin = $ENV{'HTTP_USER_AGENT'};
  #        $hostin =~ s/\x0//gsm;
         $hostin =~ s/\x7C//gsm;
         $hostin =~ s/[^\x21-\x7E]+$//gsm;
         my $httprefer = $ENV{'HTTP_REFERER'};
  #        $httprefer =~ s/\x0//gsm;
         $httprefer =~ s/\x7C//gsm;
         $httprefer =~ s/[^\x21-\x7E]+$//gsm;
         my $newlog = "$field|$date|$ENV{'REQUEST_URI'}|" 
           . (
             $httprefer =~ m/$boardurl/ism
             ? q{}
             : $httprefer
           )
           . "|$hostin|$user_ip\n";
  #        $newlog =~ s/\x0//gsm;
         $newlog =~ s/chr(32)//gsms;
  #        $newlog =~ s/\s+//gms;
         $newlog =~ s/[^\x21-\x7E]+$//gsm;
         fopen( LOG, ">$vardir/clicklog.txt", 1 );
         print {LOG} $newlog . "\n" 
           or croak "$croak{'print'} LOG";
         foreach (@new_log) {
             if ( ( split /\|/xsm, $_, 3 )[1] >= $onlinetime ) {
                 print {LOG} $_ or croak "$croak{'print'} LOG";
             }
         }
         fclose(LOG);
     }
     return;
} }
   
sub RemoveUserOnline { sub RemoveUserOnline {
   my $user = shift;    my $user = shift;
   fopen(LOG, "+<$vardir/log.txt", 1);     fopen( LOG, "<$vardir/log.txt", 1 ); 
   @logentries = <LOG>; # Global variable    @logentries = <LOG>;    # Global variable
   seek LOG, 0, 0;     fclose( LOG ); 
   truncate LOG, 0;     fopen( LOG, ">$vardir/log.txt", 1 ); 
   if ($user) {    if ($user) {
       my $x = -1;        my $x = -1;
       for (my $i = 0; $i < @logentries; $i++) {        for my $i ( 0 .. $#logentries ) {
           if ((split(/\|/, $logentries[$i], 2))[0] ne $user) { print LOG $logentries[$i]; }             if ( ( split /\|/xsm, $logentries[$i], 2 )[0] ne $user ) { 
           elsif ($user eq $username) { $logentries[$i] =~ s/^$user\|/$user_ip\|/; print LOG $logentries[$i]; }                 print {LOG} $logentries[$i] or croak "$croak{'print'} LOG"; 
           else { $x = $i; }            }
       }             elsif ( $user eq $username ) { 
       splice(@logentries,$x,1) if $x > -1;                 $logentries[$i] =~ s/^$user\|/$user_ip\|/xsm; 
   } else {                 print {LOG} $logentries[$i] or croak "$croak{'print'} LOG"; 
       print LOG '';             } 
       @logentries = ();             else { $x = $i; } 
   }        }
   fclose(LOG);         if ( $x > -1 ) { splice @logentries, $x, 1; } 
}    }
     else {
sub freespace {         print {LOG} q{} or croak "$croak{'print'} LOG"; 
   my ($FreeBytes,$hostchecked);         @logentries = (); 
   if ($^O =~ /Win/) {     } 
       if ($enable_freespace_check) {     fclose(LOG); 
           my @x = qx{DIR /-C}; # Do an ordinary DOS dir command and grab the output     return; 
           my $lastline = pop(@x); # should look like: 17 Directory(s), 21305790464 Bytes free  
           return -1 if $lastline !~ m/byte/i; # error trapping if output fails. The word byte should be in the line  
           $lastline =~ /^\s+(\d+)\s+(.+?)\s+(\d+)\s+(.+?)\n$/;  
           $FreeBytes = $3 - 100000; # 100000 bytes reserve  
   
       } else {  
           return;  
       }  
   
       $yyfreespace = "Windows";  
   
   } else {  
       if ($enable_quota) {  
           my @quota = qx{quota -u $hostusername -v}; # Do an ordinary *nix quota command and grab the output  
           return -1 if !$quota[2]; # error trapping if output fails.  
           @quota = split(/ +/, $quota[$enable_quota], 5);  
           $quota[2] =~ s/\*//;  
           $FreeBytes = (($quota[3] - $quota[2]) * 1024) - 100000; # 100000 bytes reserve  
           $hostchecked = 1;  
   
       } elsif ($findfile_maxsize) {  
           ($FreeBytes,$hostchecked) = split(/<>/, $findfile_space);  
           if ($FreeBytes < 1 || $hostchecked < $date) {  
               # fork the process since the *nix find command can take a while  
               $child_pid = fork();  
               unless ($child_pid) { # child process runs here and exits then  
                   $findfile_space = 0;  
                   map { $findfile_space += $_ } split(/-/, qx(find $findfile_root -noleaf -type f -printf "%s-"));  
                   $findfile_space = (($findfile_maxsize * 1024 * 1024) - $findfile_space) . "<>" . ($date + ($findfile_time * 60)); # actual free host space <> time for next check  
   
                   require "$admindir/NewSettings.pl";  
                   &SaveSettingsTo('Settings.pl');  
                   exit(0);  
               }  
           }  
           $hostchecked = 1;  
   
       } elsif ($enable_freespace_check) {  
           my @x = qx{df -k .}; # Do an ordinary *nix df -k . command and grab the output  
           my $lastline = pop(@x); # should look like: /dev/path 151694892 5495660 134063644 4% /  
           return -1 if $lastline !~ m/\%/; # error trapping if output fails. The % sign should be in the line  
           $FreeBytes = ((split(/ +/, $lastline, 5))[3] * 1024) - 100000; # 100000 bytes reserve  
   
       } else {  
           return;  
       }  
   
       $yyfreespace = "Unix/Linux/BSD";  
   }  
   &automaintenance('on','low_disk') if $FreeBytes < 1;  
   
   if ($FreeBytes >= 1073741824) {  
       $yyfreespace = sprintf("%.2f", $FreeBytes / (1024 * 1024 * 1024)) . " GB ($yyfreespace)";  
   } elsif ($FreeBytes >= 1048576) {  
       $yyfreespace = sprintf("%.2f", $FreeBytes / (1024 * 1024)) . " MB ($yyfreespace)";  
   } else {  
       $yyfreespace = sprintf("%.2f", $FreeBytes / 1024) . " KB ($yyfreespace)";  
   }  
   $hostchecked;  
} }
   
sub encode_password { sub encode_password {
   my $eol = $_[0];     my ($eol) = @_; 
   chomp $eol;    chomp $eol;
   require Digest::MD5;    require Digest::MD5;
   import Digest::MD5 qw(md5_base64);    import Digest::MD5 qw(md5_base64);
   md5_base64($eol);    return md5_base64($eol);
} }
   
sub Censor { sub Censor {
   my $string = $_[0];     my ($string) = @_; 
   foreach $censor (@censored) {    foreach my $censor (@censored) {
       my ($tmpa, $tmpb, $tmpc) = @{$censor};        my ( $tmpa, $tmpb, $tmpc ) = @{$censor};
       if ($tmpc) {        if ($tmpc) {
           $string =~ s~(^|\W|_)\Q$tmpa\E(?=$|\W|_)~$1$tmpb~gi;             $string =~ 
       } else {               s/(^|\W|_)\Q$tmpa\E(?=$|\W|_)/$1$tmpb/gism; 
           $string =~ s~\Q$tmpa\E~$tmpb~gi;         } 
       }         else { 
   }             $string =~ s/\Q$tmpa\E/$tmpb/gism; 
   return $string;         } 
     }
     return $string;
} }
   
sub CheckCensor { sub CheckCensor {
   my $string = $_[0];     my ($string) = @_; 
   foreach $censor (@censored) {    foreach my $censor (@censored) {
       my ($tmpa, $tmpb, $tmpc) = @{$censor};        my ( $tmpa, $tmpb, $tmpc ) = @{$censor};
       if ($string =~ m/(\Q$tmpa\E)/i) {        if ( $string =~ m/(\Q$tmpa\E)/ixsm ) {
           $found_word .= "$1 ";            $found_word .= "$1 ";
       }        }
   }    }
   return $found_word;    return $found_word;
} }
   
sub referer_check { sub referer_check {
   return if !$action;    return if !$action;
   my $referencedomain = substr($boardurl, 7, (index($boardurl, "/", 7)) - 7);     my $referencedomain = substr $boardurl, 7, ( index $boardurl, q{/}, 7 ) - 7; 
   my $refererdomain = substr($ENV{HTTP_REFERER}, 7, (index($ENV{HTTP_REFERER}, "/", 7)) - 7);     my $refererdomain = substr $ENV{HTTP_REFERER}, 7, 
   if ($refererdomain !~ /$referencedomain/ && $ENV{QUERY_STRING} ne "" && length($refererdomain) > 0) {       ( index $ENV{HTTP_REFERER}, q{/}, 7 ) - 7; 
       my $goodaction = 0;     if (   $refererdomain !~ /$referencedomain/sm 
       fopen(ALLOWED, "$vardir/allowed.txt");         && $ENV{QUERY_STRING} ne q{} 
       my @allowed = <ALLOWED>;         && length($refererdomain) > 0 ) 
       fclose(ALLOWED);     { 
       foreach my $allow (@allowed) {         my $goodaction = 0; 
           chomp $allow;         fopen( ALLOWED, "$vardir/allowed.txt" ); 
           if ($action eq $allow) { $goodaction = 1; last; }         my @allowed = <ALLOWED>; 
       }         fclose(ALLOWED); 
       if (!$goodaction) { &fatal_error("referer_violation","$action<br />$reftxt{'7'} $referencedomain<br />$reftxt{'6'} $refererdomain"); }         foreach my $allow (@allowed) { 
   }             chomp $allow; 
             if ( $action eq $allow ) { $goodaction = 1; last; }
         }
         if ( !$goodaction ) {
             fatal_error( 'referer_violation',
  "$action<br />$reftxt{'7'} $referencedomain<br />$reftxt{'6'} $refererdomain" 
             );
         }
     }
     return;
} }
   
sub Dereferer { sub Dereferer {
   &fatal_error('no_access') unless $stealthurl;     if ( !$stealthurl ) { fatal_error('no_access'); } 
   print "Content-Type: text/html\n\n";     if ($yycharset) {$yymycharset = $yycharset;} 
   print qq~<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=$yycharset" />\n<title>-----</title>\n</head>\n<body onload="window.location.href='$INFO{'url'}';">\n<font face="Arial" size="2">$dereftxt{'1'}</font>\n</body></html>\n~;     print "Content-Type: text/html\n\n" or croak "$croak{'print'} content-type"; 
   exit;     print 
  qq~<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="$abbr_lang" lang="$abbr_lang">\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=$yymycharset" />\n<title>-----</title>\n</head>\n<body onload="window.location.href='$INFO{'url'}';">\n<span style="font-family:Arial; font-size:medium">$dereftxt{'1'}</span>\n</body></html>\n~
       or croak "$croak{'print'}";
     exit;
} }
   
sub LoadLanguage { sub LoadLanguage {
   my $what_to_load = $_[0];     my ($what_to_load) = @_; 
   my $use_lang     = $language ? $language : $lang;    my $use_lang = $language ? $language : $lang;
   if (-e "$langdir/$use_lang/$what_to_load.lng") {    if ( -e "$langdir/$use_lang/$what_to_load.lng" ) {
       require "$langdir/$use_lang/$what_to_load.lng";        require "$langdir/$use_lang/$what_to_load.lng";
   } elsif (-e "$langdir/$lang/$what_to_load.lng") {     } 
       require "$langdir/$lang/$what_to_load.lng";     elsif ( -e "$langdir/$lang/$what_to_load.lng" ) { 
   } elsif (-e "$langdir/English/$what_to_load.lng") {         require "$langdir/$lang/$what_to_load.lng"; 
       require "$langdir/English/$what_to_load.lng";     } 
   } else {    elsif ( -e "$langdir/English/$what_to_load.lng" ) {
       # Catches deep recursion problems         require "$langdir/English/$what_to_load.lng"; 
       # We can simply return to the error routine once we add the needed string     } 
       if($what_to_load eq 'Error') {    else {
           %error_txt = (  
           'cannot_open_language' => "Can't find required language file. Please inform the administrator about this problem.",        # Catches deep recursion problems 
           'error_description' => "An Error Has Occurred!",        # We can simply return to the error routine once we add the needed string 
           );         if ( $what_to_load eq 'Error' ) { 
           return;             %error_txt = ( 
       }                 'cannot_open_language' => 
  'Cannot find required language file. Please inform the administrator about this problem.',
       &fatal_error("cannot_open_language","$use_lang/$what_to_load.lng");                 'error_description' => 'An Error Has Occurred!', 
   }             ); 
             return;
         }
   
         fatal_error( 'cannot_open_language', "$use_lang/$what_to_load.lng" );
     }
     return;
} }
   
sub Recent_Load { sub Recent_Load {
   my $who_to_load = $_[0];     my ($who_to_load) = @_; 
   undef %recent;    undef %recent;
   if (-e "$memberdir/$who_to_load.rlog") {    if ( -e "$memberdir/$who_to_load.rlog" ) {
       fopen(RLOG, "$memberdir/$who_to_load.rlog");         fopen( RLOG, "$memberdir/$who_to_load.rlog" ); 
       my %r = map /(.*)\t(.*)/, <RLOG>;        my %r = map { /(.*)\t(.*)/xsm } <RLOG>;
       fclose(RLOG);        fclose(RLOG);
       map{ @{$recent{$_}} = split(/,/, $r{$_}); } keys %r;        map { @{ $recent{$_} } = split /,/xsm, $r{$_} } keys %r;
   } elsif (-e "$memberdir/$who_to_load.wlog") {     } 
       require "$memberdir/$who_to_load.wlog";     elsif ( -e "$memberdir/$who_to_load.wlog" ) { 
       fopen(RLOG, ">$memberdir/$who_to_load.rlog");         require "$memberdir/$who_to_load.wlog"; 
       print RLOG map "$_\t$recent{$_}\n", keys %recent;         fopen( RLOG, ">$memberdir/$who_to_load.rlog" ); 
       fclose(RLOG);         print {RLOG} map { "$_\t$recent{$_}\n" } keys %recent 
       unlink "$memberdir/$who_to_load.wlog";           or croak "$croak{'print'} RLOG"; 
       &Recent_Load($who_to_load);         fclose(RLOG); 
   }         unlink "$memberdir/$who_to_load.wlog"; 
         Recent_Load($who_to_load);
     }
     return;
} }
   
sub Recent_Write { sub Recent_Write {
   my ($todo, $recentthread, $recentuser,$recenttime) = @_;    my ( $todo, $recentthread, $recentuser, $recenttime ) = @_;
   &Recent_Load($recentuser);     Recent_Load($recentuser); 
   if ($todo eq "incr") {    if ( $todo eq 'incr' ) {
       ${$recent{$recentthread}}[0]++;         ${ $recent{$recentthread} }[0]++; 
       ${$recent{$recentthread}}[1] = $recenttime;        ${ $recent{$recentthread} }[1] = $recenttime;
   } elsif ($todo eq "decr") {     } 
       ${$recent{$recentthread}}[0]--;     elsif ( $todo eq 'decr' ) { 
       if (${$recent{$recentthread}}[0] < 1) { delete $recent{$recentthread}; }         ${ $recent{$recentthread} }[0]--; 
       else { ${$recent{$recentthread}}[1] = $recenttime; }         if ( ${ $recent{$recentthread} }[0] < 1 ) { 
   }             delete $recent{$recentthread}; 
   &Recent_Save($recentuser);         } 
         else { ${ $recent{$recentthread} }[1] = $recenttime; }
     }
     Recent_Save($recentuser);
     return;
} }
   
sub Recent_Save { sub Recent_Save {
   my $who_to_save = $_[0];     my ($who_to_save) = @_; 
   if (!%recent) {    if ( !%recent ) {
       unlink("$memberdir/$who_to_save.rlog");         unlink "$memberdir/$who_to_save.rlog"; 
       return;        return;
   }    }
   fopen(RLOG, ">$memberdir/$who_to_save.rlog");     fopen( RLOG, ">$memberdir/$who_to_save.rlog" ); 
   print RLOG map "$_\t" . join(',', @{$recent{$_}}) . "\n", keys %recent;     print {RLOG} map { "$_\t" . join( q{,}, @{ $recent{$_} } ) . "\n" } 
   fclose(RLOG);       keys %recent 
       or croak "$croak{'print'} RLOG";
     fclose(RLOG);
     return;
} }
   
sub save_moved_file { sub save_moved_file {
   # This sub saves the hash for the moved files: key == old id, value == new id  
   fopen(MOVEDFILE, ">$datadir/movedthreads.cgi") || &fatal_error("cannot_open",">$datadir/movedthreads.cgi", 1);    # This sub saves the hash for the moved files: key == old id, value == new id 
   print MOVEDFILE "%moved_file = (" . join(',', map { qq~"$_","$moved_file{$_}"~ } grep { ($_ > 0 && $moved_file{$_} > 0 && $_ != $moved_file{$_}) } keys %moved_file) . ");\n1;";     fopen( MOVEDFILE, ">$vardir/Movedthreads.pm" ) 
   fclose(MOVEDFILE);       or fatal_error( 'cannot_open', "$vardir/Movedthreads.pm", 1 ); 
     print {MOVEDFILE} '%moved_file = (' 
       . join( q{,},
         map { qq~"$_","$moved_file{$_}"~ }
           grep { ( $_ > 0 && $moved_file{$_} > 0 && $_ != $moved_file{$_} ) }
           keys %moved_file )
       . ");\n1;" 
       or croak "$croak{'print'} MOVEDFILE";
     fclose(MOVEDFILE);
     return;
} }
   
sub Write_ForumMaster { sub Write_ForumMaster {
   fopen(FORUMMASTER, ">$boardsdir/forum.master", 1);     fopen( FORUMMASTER, ">$boardsdir/forum.master", 1 ); 
   print FORUMMASTER qq~\$mloaded = 1;\n~;     print {FORUMMASTER} qq~\$mloaded = 1;\n~ 
   @catorder = &undupe(@categoryorder);       or croak "$croak{'print'} FORUMMASTER"; 
   print FORUMMASTER qq~\@categoryorder = qw(@catorder);\n~;     @catorder = undupe(@categoryorder); 
   my ($key, $value);     print {FORUMMASTER} qq~\@categoryorder = qw(@catorder);\n~ 
   while (($key, $value) = each(%cat)) {       or croak "$croak{'print'} FORUMMASTER"; 
       # Escape membergroups with a $ in them     my ( $key, $value ); 
       $value =~ s~\$~\\\$~g;     while ( ( $key, $value ) = each %cat ) { 
       # Strip membergroups with a ~ from them         %seen = (); 
       $value =~ s/\~//g;         @catval = split /\,/xsm, $value; 
       print FORUMMASTER qq~\$cat{'$key'} = qq\~$value\~;\n~;         @unique = grep { !$seen{$_} ++ } @catval; 
   }         $val2 = join ',', @unique; 
   while (($key, $value) = each(%catinfo)) {  
       my ($catname, $therest) = split(/\|/, $value, 2);         print {FORUMMASTER} qq~\$cat{'$key'} = qq\~$val2\~;\n~ 
       #$catname =~ s/\&(?!amp;)/\&amp;$1/g;           or croak "$croak{'print'} FORUMMASTER"; 
       # We can rely on the admin scripts to properly encode when needed.     } 
       $value = "$catname|$therest";     while ( ( $key, $value ) = each %catinfo ) { 
         my ( $catname, $therest ) = split /\|/xsm, $value, 2;
       # Escape membergroups with a $ in them  
       $value =~ s~\$~\\\$~g;         #$catname =~ s/\&(?!amp;)/\&amp;$1/g; 
       # Strip membergroups with a ~ from them         # We can rely on the admin scripts to properly encode when needed. 
       $value =~ s/\~//g;         $value = "$catname|$therest"; 
       print FORUMMASTER qq~\$catinfo{'$key'} = qq\~$value\~;\n~;  
   }         # Escape membergroups with a $ in them 
   while (($key, $value) = each(%board)) {         $value =~ s/\$/\\\$/gxsm; 
       my ($boardname, $therest) = split(/\|/, $value, 2);  
       #$boardname =~ s/\&(?!amp;)/\&amp;$1/g;         # Strip membergroups with a ~ from them 
       # We can rely on the admin scripts to properly encode when needed.         $value =~ s/\~//gxsm; 
       $value = "$boardname|$therest";         print {FORUMMASTER} qq~\$catinfo{'$key'} = qq\~$value\~;\n~ 
           or croak "$croak{'print'} FORUMMASTER";
       # Escape membergroups with a $ in them     } 
       $value =~ s~\$~\\\$~g;     while ( ( $key, $value ) = each %board ) { 
       # Strip membergroups with a ~ from them         my ( $boardname, $therest ) = split /\|/xsm, $value, 2; 
       $value =~ s/\~//g;  
       print FORUMMASTER qq~\$board{'$key'} = qq\~$value\~;\n~;         #$boardname =~ s/\&(?!amp;)/\&amp;$1/g; 
   }         # We can rely on the admin scripts to properly encode when needed. 
   print FORUMMASTER qq~\n1;~;         $value = "$boardname|$therest"; 
   fclose(FORUMMASTER);  
         # Escape membergroups with a $ in them
         $value =~ s/\$/\\\$/gxsm;
   
         # Strip membergroups with a ~ from them
         $value =~ s/\~//gxsm;
         print {FORUMMASTER} qq~\$board{'$key'} = qq\~$value\~;\n~
           or croak "$croak{'print'} FORUMMASTER";
     }
     while ( ( $key, $value ) = each %subboard ) {
         if ( $value ne q{} ) {
             print {FORUMMASTER} qq~\$subboard{'$key'} = qq\~$value\~;\n~
               or croak "$croak{'print'} FORUMMASTER";
         }
     }
     print {FORUMMASTER} qq~\n1;~ or croak "$croak{'print'} FORUMMASTER";
     fclose(FORUMMASTER);
     return;
} }
   
sub dirsize { sub dirsize {
   my $dirsize;     my ($drsz) = @_; 
   require File::Find;     my $dirsize; 
   import File::Find;    require File::Find;
   &find(sub { $dirsize += -s }, $_[0]);     import File::Find; 
   $dirsize;     find( sub { $dirsize += -s }, $drsz ); 
     return $dirsize;
} }
   
sub MemberPageindex { sub MemberPageindex {
   my ($msindx, $trindx, $mbindx, $pmindx);     my ( $msindx, $trindx, $mbindx, $pmindx ) = 
   ($msindx, $trindx, $mbindx, $pmindx) = split(/\|/, ${$uid.$username}{'pageindex'});       split /\|/xsm, ${ $uid . $username }{'pageindex'}; 
   if ($INFO{'action'} eq "memberpagedrop") {    if ( $INFO{'action'} eq 'memberpagedrop' ) {
       ${$uid.$username}{'pageindex'} = qq~$msindx|$trindx|0|$pmindx~;        ${ $uid . $username }{'pageindex'} = qq~$msindx|$trindx|0|$pmindx~;
   }    }
   if ($INFO{'action'} eq "memberpagetext") {    if ( $INFO{'action'} eq 'memberpagetext' ) {
       ${$uid.$username}{'pageindex'} = qq~$msindx|$trindx|1|$pmindx~;        ${ $uid . $username }{'pageindex'} = qq~$msindx|$trindx|1|$pmindx~;
   }    }
   &UserAccount($username, "update");     UserAccount( $username, 'update' ); 
   my $SearchStr = $FORM{'member'} || $INFO{'member'};    my $SearchStr = $FORM{'member'} || $INFO{'member'};
   if ($SearchStr ne '') { $findmember = qq~;member=$SearchStr~; }    if ( $SearchStr ne q{} ) { $findmember = qq~;member=$SearchStr~; }
   if(!$INFO{'from'}) {    if ( !$INFO{'from'} ) {
       $yySetLocation = qq~$scripturl?action=ml;sort=$INFO{'sort'};letter=$INFO{'letter'};start=$INFO{'start'}$findmember~;         $yySetLocation = 
   } elsif($INFO{'from'} eq "imlist") {  qq~$scripturl?action=ml;sort=$INFO{'sort'};letter=$INFO{'letter'};start=$INFO{'start'}$findmember~; 
       $yySetLocation = qq~$scripturl?action=imlist;sort=$INFO{'sort'};letter=$INFO{'letter'};start=$INFO{'start'};field=$INFO{'field'}~;     } 
   } elsif($INFO{'from'} eq 'admin') {    elsif ( $INFO{'from'} eq 'imlist' ) {
       $yySetLocation = qq~$adminurl?action=ml;sort=$INFO{'sort'};letter=$INFO{'letter'};start=$INFO{'start'}~;         $yySetLocation = 
   }  qq~$scripturl?action=imlist;sort=$INFO{'sort'};letter=$INFO{'letter'};start=$INFO{'start'};field=$INFO{'field'}~; 
     }
     elsif ( $INFO{'from'} eq 'admin' ) {
         $yySetLocation =
  qq~$adminurl?action=ml;sort=$INFO{'sort'};letter=$INFO{'letter'};start=$INFO{'start'}~;
     }
   
   &redirectexit;     redirectexit(); 
     return;
} }
   
#changed sub for improve perfomance, code from Zoo #changed sub for improved performance, code from Zoo
sub check_existence { sub check_existence {
   my ($dir, $filename) = @_;    my ( $dir, $filename ) = @_;
     my ( $origname, $filext );
   
   $filename =~ /(\S+?)(\.\S+$)/;     if ( $filename =~ /(\S+?)(\.\S+$)/sm ) { 
   my $origname = $1;        $origname = $1;
   my $filext = $2;        $filext   = $2;
   my $numdelim = "_";     } 
   my $filenumb = 0;     my $numdelim = '_'; 
   while (-e "$dir/$filename") {     my $filenumb = 0; 
           $filenumb = sprintf("%03d", ++$filenumb);     while ( -e "$dir/$filename" ) { 
           $filename = qq~$origname$numdelim$filenumb$filext~;         $filenumb = sprintf '%03d', ++$filenumb; 
   }         $filename = qq~$origname$numdelim$filenumb$filext~; 
   return ($filename);     } 
     return ($filename);
} }
   
sub ManageMemberlist { sub ManageMemberlist {
   my $todo    = $_[0];     my ( $todo, $user, $userreg ) = @_; 
   my $user    = $_[1];     if (   $todo eq 'load' 
   my $userreg = $_[2];         || $todo eq 'update' 
   if ($todo eq "load" || $todo eq "update" || $todo eq "delete" || $todo eq "add") {         || $todo eq 'delete' 
       fopen(MEMBLIST, "$memberdir/memberlist.txt");         || $todo eq 'add' ) 
       %memberlist = map /(.*)\t(.*)/, <MEMBLIST>;     { 
       fclose(MEMBLIST);         fopen( MEMBLIST, "$memberdir/memberlist.txt" ); 
   }         %memberlist = map { /(.*)\t(.*)/m } <MEMBLIST>; 
   if ($todo eq "add") {         fclose(MEMBLIST); 
       $memberlist{$user} = "$userreg";     } 
     if ( $todo eq 'add' ) {
   } elsif ($todo eq "update") {         $memberlist{$user} = "$userreg"; 
       $memberlist{$user} = $userreg ? $userreg : $memberlist{$user};  
     }
   } elsif ($todo eq "delete") {    elsif ( $todo eq 'update' ) {
       if ($user =~ /,/) {    # been sent a list to kill, not a single         $memberlist{$user} = $userreg ? $userreg : $memberlist{$user}; 
           my @oldusers = split(',', $user);  
           foreach my $user (@oldusers) {     } 
               delete($memberlist{$user});     elsif ( $todo eq 'delete' ) { 
           }         if ( $user =~ /,/sm ) {    # been sent a list to kill, not a single 
       }             my @oldusers = split /,/xsm, $user; 
       else    {delete($memberlist{$user});}             foreach my $user (@oldusers) { 
   }                 delete $memberlist{$user}; 
   if ($todo eq "save" || $todo eq "update" || $todo eq "delete" || $todo eq "add") {             } 
       fopen(MEMBLIST, ">$memberdir/memberlist.txt");         } 
       print MEMBLIST map "$_\t$memberlist{$_}\n", sort { $memberlist{$a} <=> $memberlist{$b} } keys %memberlist;         else { delete $memberlist{$user}; } 
       fclose(MEMBLIST);     } 
       undef %memberlist;     if (   $todo eq 'save' 
   }         || $todo eq 'update' 
         || $todo eq 'delete' 
         || $todo eq 'add' )
     {
         fopen( MEMBLIST, ">$memberdir/memberlist.txt" );
         print {MEMBLIST} map { "$_\t$memberlist{$_}\n" }
           sort { $memberlist{$a} <=> $memberlist{$b} } keys %memberlist
           or croak "$croak{'print'} MEMBLIST";
         fclose(MEMBLIST);
         undef %memberlist;
     }
     return;
} }
   
## deal with basic member data in memberinfo.txt ## deal with basic member data in memberinfo.txt
sub ManageMemberinfo { sub ManageMemberinfo {
   my $todo       = $_[0];     my ( $todo, $user, $userdisp, $usermail, $usergrp, $usercnt, $useraddgrp ) = 
   my $user       = $_[1];       @_; 
   my $userdisp   = $_[2];     ## pull hash of member name + other data 
   my $usermail   = $_[3];     if (   $todo eq 'load' 
   my $usergrp    = $_[4];         || $todo eq 'update' 
   my $usercnt    = $_[5];         || $todo eq 'delete' 
   my $useraddgrp = $_[6];         || $todo eq 'add' ) 
   ## pull hash of member name + other data     { 
   if ($todo eq "load" || $todo eq "update" || $todo eq "delete" || $todo eq "add") {         fopen( MEMBINFO, "$memberdir/memberinfo.txt" ); 
       fopen(MEMBINFO, "$memberdir/memberinfo.txt");         @membinfo = <MEMBINFO>; 
       %memberinf = map /(.*)\t(.*)/, <MEMBINFO>;         chomp @membinfo; 
       fclose(MEMBINFO);         %memberinf = map { /(.*)\t(.*)/xsm } @membinfo; 
   }         fclose(MEMBINFO); 
   if ($todo eq "add") {     } 
       $memberinf{$user} = "$userdisp|$usermail|$usergrp|$usercnt|$useraddgrp";     if ( $todo eq 'add' ) { 
   } elsif ($todo eq "update") {         $memberinf{$user} = "$userdisp|$usermail|$usergrp|$usercnt|$useraddgrp"; 
       ($memrealname, $mememail, $memposition, $memposts, $memaddgrp) = split(/\|/, $memberinf{$user});     } 
       if ($userdisp) { $memrealname = $userdisp; }     elsif ( $todo eq 'update' ) { 
       if ($usermail) { $mememail = $usermail; }         ( $memrealname, $mememail, $memposition, $memposts, $memaddgrp ) = 
       if ($usergrp) { $memposition = $usergrp; }           split /\|/xsm, $memberinf{$user}; 
       if ($usercnt) { $memposts = $usercnt; }        if ($userreg)  { $regdate     = $userreg; }
       if ($useraddgrp) {         if ($userdisp) { $memrealname = $userdisp; } 
           if ($useraddgrp =~ /###blank###/) { $useraddgrp = ''; }        if ($usermail) { $mememail    = $usermail; }
           $memaddgrp = $useraddgrp;         if ($usergrp)  { $memposition = $usergrp; } 
       }        if ($usercnt)  { $memposts    = $usercnt; }
       $memberinf{$user} = "$memrealname|$mememail|$memposition|$memposts|$memaddgrp";         if ($useraddgrp) { 
   } elsif ($todo eq "delete") {             if ( $useraddgrp =~ /\x23\x23\x23blank\x23\x23\x23/sm ) { $useraddgrp = q{}; } 
       if ($user =~ /,/) {    # been sent a list to kill, not a single             $memaddgrp = $useraddgrp; 
           my @oldusers = split(',', $user);         } 
           foreach my $user (@oldusers) {         $memberinf{$user} = 
               delete($memberinf{$user});           "$memrealname|$mememail|$memposition|$memposts|$memaddgrp"; 
           }    }
       }     elsif ( $todo eq 'delete' ) { 
       delete($memberinf{$user});         if ( $user =~ /,/xsm ) {    # been sent a list to kill, not a single 
   }             my @oldusers = split /,/xsm, $user; 
   if ($todo eq "save" || $todo eq "update" || $todo eq "delete" || $todo eq "add") {            foreach my $user (@oldusers) {
       fopen(MEMBINFO, ">$memberdir/memberinfo.txt");                 delete $memberinf{$user}; 
       print MEMBINFO map "$_\t$memberinf{$_}\n", keys %memberinf;             } 
       fclose(MEMBINFO);         } 
       undef %memberinf;         delete $memberinf{$user}; 
   }    }
     if (   $todo eq 'save' 
         || $todo eq 'update' 
         || $todo eq 'delete' 
         || $todo eq 'add' )
     {
         fopen( MEMBINFO, ">$memberdir/memberinfo.txt" );
         print {MEMBINFO} map { "$_\t$memberinf{$_}\n" } keys %memberinf
           or croak "$croak{'print'} MEMBINFO";
         fclose(MEMBINFO);
         undef %memberinf;
     }
     return;
} }
   
sub Collapse_Load { sub Collapse_Load {
   my (%userhide, $catperms, $catallowcol, $access);     my ( %userhide, $catperms, $catallowcol, $access ); 
   my $i = 0;    my $i = 0;
   map{ $userhide{$_} = 1; } split(/,/, ${$uid.$username}{'cathide'});     map { $userhide{$_} = 1; } split /,/xsm, ${ $uid . $username }{'cathide'}; 
   foreach my $key (@categoryorder) {    foreach my $key (@categoryorder) {
       (undef, $catperms, $catallowcol) = split(/\|/, $catinfo{$key});         ( undef, $catperms, $catallowcol ) = split /\|/xsm, $catinfo{$key}; 
       $access = &CatAccess($catperms);         $access = CatAccess($catperms); 
       if ($catallowcol == 1 && $access) { $i++; }        if ( $catallowcol == 1 && $access ) { $i++; }
       $catcol{$key} = 1;        $catcol{$key} = 1;
       if ($catallowcol == 1 && $userhide{$key}) { $catcol{$key} = 0; }        if ( $catallowcol == 1 && $userhide{$key} ) { $catcol{$key} = 0; }
   }    }
   $colbutton = ($i == keys %userhide) ? 0 : 1;    $colbutton = ( $i == keys %userhide ) ? 0 : 1;
   $colloaded = 1;    $colloaded = 1;
     return;
} }
   
sub MailList { sub MailList {
   &is_admin_or_gmod;     my ($m_line) = @_; 
   my $delmailline = '';     is_admin_or_gmod(); 
   if (!$INFO{'delmail'}) {     my $delmailline = q{}; 
       $mailline = $_[0];     if ( !$INFO{'delmail'} ) { 
       $mailline =~ s~\r~~g;         $mailline = $m_line; 
       $mailline =~ s~\n~<br />~g;         $mailline =~ s/\r//gxsm; 
   } else {         $mailline =~ s/\n/<br \/>/gsm; 
       $delmailline = $INFO{'delmail'};     } 
   }     else { 
   if (-e ("$vardir/maillist.dat")) {         $delmailline = $INFO{'delmail'}; 
       fopen(FILE, "$vardir/maillist.dat");     } 
       @maillist = <FILE>;     if ( -e ("$vardir/maillist.dat") ) { 
       fclose(FILE);         fopen( FILE, "$vardir/maillist.dat" ); 
       fopen(FILE, ">$vardir/maillist.dat");         @maillist = <FILE>; 
       if (!$INFO{'delmail'}) {         fclose(FILE); 
           print FILE "$mailline\n";         fopen( FILE, ">$vardir/maillist.dat" ); 
       }         if ( !$INFO{'delmail'} ) { 
       foreach $curmail (@maillist) {             print {FILE} "$mailline\n" or croak "$croak{'print'} FILE"; 
           chomp $curmail;         } 
           $otime = (split /\|/, $curmail)[0];         foreach my $curmail (@maillist) { 
           if ($otime ne $delmailline) {             chomp $curmail; 
               print FILE "$curmail\n";             $otime = ( split /\|/xsm, $curmail )[0]; 
           }             if ( $otime ne $delmailline ) { 
       }                 print {FILE} "$curmail\n" or croak "$croak{'print'} FILE"; 
       fclose(FILE);             } 
   } else {         } 
       fopen(FILE, ">$vardir/maillist.dat");         fclose(FILE); 
       print FILE "$mailline\n";     } 
       fclose(FILE);     else { 
   }         fopen( FILE, ">$vardir/maillist.dat" ); 
   if ($INFO{'delmail'}) {         print {FILE} "$mailline\n" or croak "$croak{'print'} FILE"; 
       $yySetLocation = qq~$adminurl?action=mailing~;         fclose(FILE); 
       &redirectexit;     } 
   }     if ( $INFO{'delmail'} ) { 
         $yySetLocation = qq~$adminurl?action=mailing~;
         redirectexit();
     }
     return;
} }
   
sub cloak { sub cloak {
   my ($input) =$_[0];     my ($input) = @_; 
   my ($user,$ascii,$key,$hex,$hexkey);     my ( $user, $ascii, $key, $hex, $hexkey ); 
   $key = substr($date,length($date)-2,2);     $key = substr $date, length($date) - 2, 2; 
   $hexkey = uc(unpack("H2", pack("V", $key)));     $hexkey = uc( unpack 'H2', pack 'V', $key ); 
   for($n=0; $n < length $input ; $n++)    {    for my $n ( 0 .. ( length($input) - 1 ) ) {
       $ascii = substr($input, $n, 1);         $ascii = substr $input, $n, 1; 
       $ascii = ord($ascii) ^ $key; # xor it instead of adding to prevent wide characters         $ascii = ord($ascii) ^ $key; 
       $hex = uc(unpack("H2", pack("V", $ascii)));  
       $user .= $hex;         # xor it instead of adding to prevent wide characters 
   }         $hex = uc( unpack 'H2', pack 'V', $ascii ); 
   $user .= $hexkey;         $user .= $hex; 
   $user .= '0';     } 
   return $user;     $user .= $hexkey; 
     $user .= '0';
     return $user;
} }
   
sub decloak { sub decloak {
   my ($input) =$_[0];     my ($input) = @_; 
   my ($user,$ascii,$key,$dec,$hexkey);     my ( $user, $ascii, $key, $dec, $hexkey ); 
   if (length($input) % 2 == 0) {return &old_decloak($input);} # Old style, return it     if ( $input !~ /\A[0-9A-F]+\Z/xsm ) { 
   elsif ($input !~ /\A[0-9A-F]+\Z/) {return $input; }         # probably a non cloaked ID as it contains non hex code         return $input; 
   else {$input =~ s~0$~~;}     }    # probably a non cloaked ID as it contains non hex code 
   $hexkey = substr($input,length($input)-2,2);     else { $input =~ s/0$//xsm; } 
   $key = hex($hexkey);     $hexkey = substr $input, length($input) - 2, 2; 
   for($n=0; $n < length($input)-2; $n += 2)    {     $key = hex $hexkey; 
       $dec = substr($input, $n, 2);     foreach my $n ( 0 .. ( length($input) - 3 ) ) { 
       $ascii = hex($dec) ^ $key; # xor it to reverse it         if ( $n % 2 == 0 ) { 
       $ascii = chr($ascii);             $dec = substr $input, $n, 2; 
       $user .= $ascii;             $ascii = hex($dec) ^ $key; 
   }  
   return $user;             # xor it to reverse it 
}             $ascii = chr $ascii; 
             $user .= $ascii;
# THIS IS BROKEN -- it fails on larger ASCII values (for example chr(255) )         } 
# It is only here to support YaBBForum's old format.     } 
sub old_decloak {     return $user; 
   my ($input) =$_[0];  
   my ($user,$ascii,$key,$dec,$hexkey,$x);  
   if ($input !~ /\A[0-9A-F]+\Z/) { return $input; }    ## probably a non cloaked ID as it contains non hex code  
   $hexkey = substr($input,length($input)-2,2);  
   $key = hex($hexkey);  
   $x=0;  
   for($n=0; $n < length($input)-2; $n++) {  
       $dec = substr($input, $n, 2);  
       $ascii = hex($dec);  
       $ascii = chr($ascii-$key+$x);  
       $user .= $ascii;  
       $n++;  
       $x++;  
       if ($x > 32){$x = 0;}  
   }  
   return $user;  
} }
   
# run through the log.txt and return the online/offline/away string near by the username # run through the log.txt and return the online/offline/away string near by the username
my %users_online; my %users_online;
   
sub userOnLineStatus { sub userOnLineStatus {
   my $userToCheck = $_[0];     my ($userToCheck) = @_; 
   
   return '' if $userToCheck eq 'Guest';     if ( $userToCheck eq 'Guest' ) { return; } 
   if (exists $users_online{$userToCheck}) {    if ( exists $users_online{$userToCheck} ) {
       return $users_online{$userToCheck} if $users_online{$userToCheck};         if ( $users_online{$userToCheck} ) { 
   } else {             return $users_online{$userToCheck}; 
       map { $users_online{(split(/\|/, $_, 2))[0]} = 0 } @logentries;         } 
   }    }
     else {
   &LoadUser($userToCheck);         map { $users_online{ ( split /\|/xsm, $_, 2 )[0] } = 0 } @logentries; 
     }
   if (exists $users_online{$userToCheck} && (!${$uid.$userToCheck}{'stealth'} || $iamadmin || $iamgmod)) {  
       ${$uid.$userToCheck}{'offlinestatus'} = 'online';     LoadUser($userToCheck); 
       $users_online{$userToCheck} = qq~<span class="useronline">$maintxt{'60'}</span>~ . (${$uid.$userToCheck}{'stealth'} ? "*" : "");  
   } else {     if ( exists $users_online{$userToCheck} 
       $users_online{$userToCheck} = qq~<span class="useroffline">$maintxt{'61'}</span>~;         && ( !${ $uid . $userToCheck }{'stealth'} || $iamadmin || $iamgmod ) ) 
   }     { 
   # enable 'away' indicator $enable_MCaway: 0=Off; 1=Staff to Staff; 2=Staff to all; 3=Members         ${ $uid . $userToCheck }{'offlinestatus'} = 'online'; 
   if (!$iamguest && $enable_MCstatusStealth &&         $users_online{$userToCheck} = 
       (($enable_MCaway == 1 && $staff) || $enable_MCaway > 1) &&           qq~<span class="useronline">$maintxt{'60'}</span>~ 
       ${$uid.$userToCheck}{'offlinestatus'} eq 'away') {           . ( ${ $uid . $userToCheck }{'stealth'} ? q{*} : q{} ); 
       $users_online{$userToCheck} = qq~<span class="useraway">$maintxt{'away'}</span>~;     } 
   }     else { 
   $users_online{$userToCheck};         $users_online{$userToCheck} = 
           qq~<span class="useroffline">$maintxt{'61'}</span>~;
     }
   
  # enable 'away' indicator $enable_MCaway: 0=Off; 1=Staff to Staff; 2=Staff to all; 3=Members
     if (  !$iamguest
         && $enable_MCstatusStealth
         && ( ( $enable_MCaway == 1 && $staff ) || $enable_MCaway > 1 )
         && ${ $uid . $userToCheck }{'offlinestatus'} eq 'away' )
     {
         $users_online{$userToCheck} =
           qq~<span class="useraway">$maintxt{'away'}</span>~;
     }
     return $users_online{$userToCheck};
} }
   
## moved from Register.pl so we can use for guest browsing ## moved from Register.pm so we can use for guest browsing
sub guestLangSel { sub guestLangSel {
   opendir DIR, $langdir;    opendir DIR, $langdir;
   $morelang = 0;    $morelang = 0;
   my @langDir = readdir DIR;    my @langDir = readdir DIR;
   closedir DIR;    closedir DIR;
   foreach my $langitems ( sort { lc($a) cmp lc $b } @langDir ) {    foreach my $langitems ( sort { lc($a) cmp lc $b } @langDir ) {
       chomp $langitems;        chomp $langitems;
       if (   ( $langitems ne q{.} )        if (   ( $langitems ne q{.} )
           && ( $langitems ne q{..} )            && ( $langitems ne q{..} )
           && ( $langitems ne q{.htaccess} )            && ( $langitems ne q{.htaccess} )
           && ( $langitems ne q{index.html} )             && ( $langitems ne q{index.html} ) ) 
          )  
       {        {
           $lngsel = q{};            $lngsel = q{};
           if ( $langitems eq $language ) {            if ( $langitems eq $language ) {
               $lngsel = q~ selected="selected"~;                $lngsel = q~ selected="selected"~;
           }            }
           my $displang = $langitems;            my $displang = $langitems;
           $displang =~ s/(.+?)\_(.+?)$/$1 ($2)/gism;            $displang =~ s/(.+?)\_(.+?)$/$1 ($2)/gism;
           $langopt .=            $langopt .=
             qq~<option value="$langitems"$lngsel>$displang</option>~;              qq~<option value="$langitems"$lngsel>$displang</option>~;
           $morelang++;            $morelang++;
       }        }
   }    }
   return $langopt;    return $langopt;
} }
   
##  control guest language selection. ##  control guest language selection.
   
sub setGuestLang { sub setGuestLang {
   ## if either 'no guest access' or 'no guest lan sel', throw the user back to the logn screen    ## if either 'no guest access' or 'no guest lan sel', throw the user back to the login screen
   if (!$guestaccess || !$enable_guestlanguage) {    if ( !$guestaccess || !$enable_guestlanguage ) {
       $yySetLocation = qq~$scripturl?action=login~;        $yySetLocation = qq~$scripturl?action=login~;
       &redirectexit;         redirectexit(); 
   }    }
   # otherwise, grab the selected language from the form and redirect to load it.  
   $guestLang = $FORM{'guestlang'};   # otherwise, grab the selected language from the form and redirect to load it. 
   $language = $guestLang;     $guestLang     = $FORM{'guestlang'}; 
   $yySetLocation = qq~$scripturl~;     $language      = $guestLang; 
   &redirectexit;     $yySetLocation = qq~$scripturl~; 
     redirectexit();
     return;
} }
   
##  check for locked post bypass status - user must be at least mod and bypass lock must be set right. ##  check for locked post bypass status - user must be at least mod and bypass lock must be set right.
sub checkUserLockBypass { sub checkUserLockBypass {
   my $canbypass;     if ( 
   ## work down the levels         $staff 
   if ($bypass_lock_perm eq "fa" && $iamadmin) { $canbypass = 1; }         && ( 
   elsif ($bypass_lock_perm eq "gmod" && ($iamadmin || $iamgmod)) { $canbypass = 1; }                ( $bypass_lock_perm eq 'fa' && $iamadmin ) 
   elsif ($bypass_lock_perm eq "mod" && ($iamadmin || $iamgmod || $iammod)) { $canbypass = 1; }             || ( $bypass_lock_perm eq 'gmod' && ( $iamadmin || $iamgmod ) ) 
   $canbypass;             || ( $bypass_lock_perm eq 'fmod' 
                 && ( $iamadmin || $iamgmod || $iamfmod ) )
             || $bypass_lock_perm eq 'mod' 
         )
       )
     {
         return 1;
     }
} }
   
sub alertbox { sub alertbox {
   $yymain .= qq~     my ($alert) = @_; 
<script language="JavaScript" type="text/javascript">     $yymain .= qq~ 
   <!--  <script type="text/javascript"> 
       alert("$_[0]");         alert("$alert"); 
   // -->  
</script>~; </script>~;
     return;
} }
   
## load buddy list for user, new version from sub isUserBuddy ## load buddy list for user, new version from sub isUserBuddy
sub loadMyBuddy { sub loadMyBuddy {
   %mybuddie = ();    %mybuddie = ();
   if (${$uid.$username}{'buddylist'}) {    if ( ${ $uid . $username }{'buddylist'} ) {
       my @buddies = split(/\|/, ${$uid.$username}{'buddylist'});         my @buddies = split /\|/xsm, ${ $uid . $username }{'buddylist'}; 
       chomp(@buddies);         chomp @buddies; 
       foreach my $buddy (@buddies) {        foreach my $buddy (@buddies) {
           $buddy =~ s/^ //;             $buddy =~ s/^ //sm; 
           $mybuddie{$buddy} = 1;            $mybuddie{$buddy} = 1;
       }        }
   }    }
     return;
} }
   
## add user to buddy list ## add user to buddy list
## this is only for the ## this is only for the
sub addBuddy { sub addBuddy {
   my $newBuddy;    my $newBuddy;
   if ($INFO{'name'}) {    if ( $INFO{'name'} ) {
       if ($do_scramble_id) { $newBuddy = &decloak($INFO{'name'}); }        if   ($do_scramble_id) { $newBuddy = decloak( $INFO{'name'} ); }
       else { $newBuddy = $INFO{'name'}; }        else                   { $newBuddy = $INFO{'name'}; }
       chomp($newBuddy);         chomp $newBuddy; 
       if ($newBuddy eq $username) { &fatal_error("self_buddy"); }        if ( $newBuddy eq $username ) { fatal_error('self_buddy'); }
       &ToHTML($newBuddy);         ToHTML($newBuddy); 
       if (!${$uid.$username}{'buddylist'}) {        if ( !${ $uid . $username }{'buddylist'} ) {
           ${$uid.$username}{'buddylist'} = "$newBuddy";            ${ $uid . $username }{'buddylist'} = "$newBuddy";
       } else {         } 
           my @currentBuddies = split(/\|/, ${$uid.$username}{'buddylist'});         else { 
           push(@currentBuddies, $newBuddy);             my @currentBuddies = 
           sort(@currentBuddies);               split /\|/xsm, ${ $uid . $username }{'buddylist'}; 
           @newBuddies = &undupe(@currentBuddies);             push @currentBuddies, $newBuddy; 
           $newBuddyList = join('|', @newBuddies);             @currentBuddies = sort @currentBuddies; 
           ${$uid.$username}{'buddylist'} = $newBuddyList;             @newBuddies     = undupe(@currentBuddies); 
       }             $newBuddyList   = join q{|}, @newBuddies; 
       &UserAccount($username, "update");             ${ $uid . $username }{'buddylist'} = $newBuddyList; 
   }        }
   $yySetLocation = qq~$scripturl?num=$INFO{'num'}/$INFO{'vpost'}#$INFO{'vpost'}~;         UserAccount( $username, 'update' ); 
   if ($INFO{'vpost'} eq '') {     } 
       $yySetLocation = qq~$scripturl?action=viewprofile;username=$INFO{'name'}~;     $yySetLocation = 
   }       qq~$scripturl?num=$INFO{'num'}/$INFO{'vpost'}#$INFO{'vpost'}~; 
   &redirectexit;     if ( $INFO{'vpost'} eq q{} ) { 
         $yySetLocation =
           qq~$scripturl?action=viewprofile;username=$INFO{'name'}~;
     }
     redirectexit();
     return;
} }
   
## check to see if user can view a broadcast message based on group ## check to see if user can view a broadcast message based on group
sub BroadMessageView { sub BroadMessageView {
   if ($iamadmin) { return 1; }     my ($imp) = @_; 
   if ($_[0]) {     if ($iamadmin) { return 1; } 
       foreach my $checkgroup (split(/\,/, $_[0])) {    if ($imp) {
           if ($checkgroup eq 'all') { return 1; }         foreach my $checkgroup ( split /\,/xsm, $imp ) { 
           if ($checkgroup eq ('gmods' || 'mods') && $iamgmod) { return 1; }            if ( $checkgroup eq 'all' ) { return 1; }
           if ($checkgroup eq 'mods' && $iammod) { return 1; }             if ( 
           if ($checkgroup eq ${$uid.$username}{'position'}) { return 1; }                 ( 
           foreach (split(/,/, ${$uid.$username}{'addgroups'})) {                        $checkgroup eq 'gmods' 
               if ($checkgroup eq $_) { return 1; }                     || $checkgroup eq 'fmods' 
           }                     || $checkgroup eq 'mods' 
       }                 ) 
   }                 && $iamgmod 
   return 0;               ) 
             {
                 return 1;
             }
             if ( ( $checkgroup eq 'fmods' || $checkgroup eq 'mods' )
                 && $iamfmod )
             {
                 return 1;
             }
             if ( $checkgroup eq 'mods' && $iammod ) { return 1; }
             if ( $checkgroup eq ${ $uid . $username }{'position'} ) {
                 return 1;
             }
             foreach ( split /,/xsm, ${ $uid . $username }{'addgroups'} ) {
                 if ( $checkgroup eq $_ ) { return 1; }
             }
         }
     }
     return 0;
} }
   
sub CheckUserPM_Level { sub CheckUserPM_Level {
   my $checkuser = $_[0];     my ($checkuser) = @_; 
   return if $PM_level <= 1 || $UserPM_Level{$checkuser};    return if $PM_level <= 1 || $UserPM_Level{$checkuser};
   $UserPM_Level{$checkuser} = 1;    $UserPM_Level{$checkuser} = 1;
   if (!${$uid.$checkuser}{'password'}) { &LoadUser($checkuser); }    if ( !${ $uid . $checkuser }{'password'} ) { LoadUser($checkuser); }
   if (${$uid.$checkuser}{'position'} eq 'Administrator' || ${$uid.$checkuser}{'position'} eq 'Global Moderator') {    if ( ${ $uid . $checkuser }{'position'} eq 'Mid Moderator' ) {
       $UserPM_Level{$checkuser} = 3;         $UserPM_Level{$checkuser} = 4; 
   } else {     } 
       usercheck: foreach my $catid (@categoryorder) {     elsif (${ $uid . $checkuser }{'position'} eq 'Administrator' 
           foreach my $checkboard (split(/,/, $cat{$catid})) {         || ${ $uid . $checkuser }{'position'} eq 'Global Moderator' ) 
               foreach my $curuser (split(/, ?/, ${$uid.$checkboard}{'mods'})) {    {
                   if ($checkuser eq $curuser) { $UserPM_Level{$checkuser} = 2; last usercheck; }         $UserPM_Level{$checkuser} = 3; 
               }    }
               foreach my $curgroup (split(/, /, ${$uid.$checkboard}{'modgroups'})) {    else {
                   if (${$uid.$checkuser}{'position'} eq $curgroup) { $UserPM_Level{$checkuser} = 2; last usercheck; }       USERCHECK: foreach my $catid (@categoryorder) { 
                   foreach (split(/,/, ${$uid.$checkuser}{'addgroups'})) {            foreach my $checkboard ( split /,/xsm, $cat{$catid} ) {
                       if ($_ eq $curgroup) { $UserPM_Level{$checkuser} = 2; last usercheck; }                 foreach 
                   }                   my $curuser ( split /, ?/sm, ${ $uid . $checkboard }{'mods'} ) 
               }                 { 
           }                     if ( $checkuser eq $curuser ) { 
       }                         $UserPM_Level{$checkuser} = 2; 
   }                         last USERCHECK; 
                     }
                 }
                 foreach my $curgroup ( split /, /sm,
                     ${ $uid . $checkboard }{'modgroups'} )
                 {
                     if ( ${ $uid . $checkuser }{'position'} eq $curgroup ) {
                         $UserPM_Level{$checkuser} = 2;
                         last USERCHECK;
                     }
                     foreach ( split /,/xsm,
                         ${ $uid . $checkuser }{'addgroups'} )
                     {
                         if ( $_ eq $curgroup ) {
                             $UserPM_Level{$checkuser} = 2;
                             last USERCHECK;
                         }
                     }
                 }
             }
         }
     }
     return;
  }
   
  sub get_forum_master {
     if ( $mloaded != 1 ) {
         require "$boardsdir/forum.master";
     }
     return;
  }
   
  sub get_micon {
     if ( -e ("$templatesdir/$usestyle/Micon.def") ) {
         $Micon_def = qq~$templatesdir/$usestyle/Micon.def~;
     }
     else { $Micon_def = qq~$templatesdir/default/Micon.def~; }
     require "$Micon_def";
     return;
  }
   
  sub get_template {
     my ($templt) = @_;
     my @templ_list = ( $useboard, $usemessage, $usedisplay, $usemycenter );
     my @ld_list    = qw(BoardIndex MessageIndex Display MyCenter);
     my $ld_cn      = 0;
     for my $x ( 0 .. $#ld_list ) {
         if ( $templt eq $ld_list[$x] ) {
             require qq~$templatesdir/$templ_list[$x]/$ld_list[$x].template~;
             $ld_cn = 1;
         }
     }
     if ( $ld_cn == 0 ) {
         if ( -e ("$templatesdir/$usestyle/$templt.template") ) {
             require "$templatesdir/$usestyle/$templt.template";
         }
         else {
             require "$templatesdir/default/$templt.template";
         }
     }
     return;
  }
   
  sub get_gmod {
     if ( $iamgmod && -e "$vardir/gmodsettings.txt" ) {
         require "$vardir/gmodsettings.txt";
     }
     return;
  }
   
  sub enable_yabbc {
     if ( $yyYaBBCloaded != 1 ) {
         require Sources::YaBBC;
     }
     return;
  }
  ## moved from YaBBC.pm and Printpage.pl DAR 2/7/2012 ##
  sub format_url {
     my ( $txtfirst, $txturl ) = @_;
     my $lasttxt = q{};
     if ( $txturl =~
  m{(.*?)(\.|\.\)|\)\.|\!|\!\)|\)\!|\,|\)\,|\)|\;|\&quot\;|\&quot\;\.|\.\&quot\;|\&quot\;\,|\,\&quot\;|\&quot\;\;|\<\/)\Z}sm
       )
     {
         $txturl  = $1;
         $lasttxt = $2;
     }
     my $realurl = $txturl;
     $txturl =~ s/(\[highlight\]|\[\/highlight\]|\[edit\]|\[\/edit\])//igsm;
     $txturl =~ s/\[/&\x2391;/gsm;
     $txturl =~ s/\]/&\x2393;/gsm;
     $txturl =~ s/\<.+?\>//igsm;
     my $formaturl = qq~$txtfirst\[url\=$txturl\]$realurl\[\/url\]$lasttxt~;
     return $formaturl;
  }
   
  sub format_url2 {
     my ( $txturl, $txtlink ) = @_;
     $txturl =~ s/(\[highlight\]|\[\/highlight\]|\[edit\]|\[\/edit\])//igsm;
     $txturl =~ s/\<.+?\>//igsm;
     my $formaturl = qq~[url=$txturl]$txtlink\[/url]~;
     return $formaturl;
  }
   
  sub format_url3 {
     my ($txturl) = @_;
     my $txtlink = $txturl;
     $txturl =~ s/(\[highlight\]|\[\/highlight\]|\[edit\]|\[\/edit\])//igsm;
     $txturl =~ s/\[/&\x2391;/gsm;
     $txturl =~ s/\]/&\x2393;/gsm;
     $txturl =~ s/\<.+?\>//igsm;
     my $formaturl = qq~\[url\=$txturl\]$txtlink\[\/url\]~;
     return $formaturl;
  }
   
  sub sizefont {
     ## limit minimum and maximum font pitch as CSS does not restrict it at all. ##
     my ( $tsize, $ttext ) = @_;
     if    ( !$fontsizemax )         { $fontsizemax = 72; }
     if    ( !$fontsizemin )         { $fontsizemin = 6; }
     if    ( $tsize < $fontsizemin ) { $tsize       = $fontsizemin; }
     elsif ( $tsize > $fontsizemax ) { $tsize       = $fontsizemax; }
     return qq~<span style="font-size: ${tsize}pt;">$ttext</span><!--size-->~;
  }
   
  sub regex_1 {
     my ($message) = @_;
     $message =~ s/[\r\n\ ]//gsm;
     $message =~ s/\&nbsp;//gxsm;
     $message =~ s/\[table\].*?\[tr\].*?\[td\]//gxsm;
     $message =~ s/\[\/td\].*?\[\/tr\].*?\[\/table\]//gxsm;
     $message =~ s/\[.*?\]//gxsm;
   
     return $message;
  }
   
  sub regex_2 {
     my ($message) = @_;
     $message =~ s/\cM//gsm;
     $message =~ s/\[([^\]\[]{0,30})\n([^\]\[]{0,30})\]/\[$1$2\]/gsm;
     $message =~ s/\[\/([^\]\[]{0,30})\n([^\]\[]{0,30})\]/\[\/$1$2\]/gsm;
     return $message;
  }
   
  sub regex_3 {
     my ($message) = @_;
     $message =~ s/\t/ \&nbsp; \&nbsp; \&nbsp;/gsm;
     $message =~ s/\n/<br \/>/gsm;
     $message =~ s/([\000-\x09\x0b\x0c\x0e-\x1f\x7f])/\x0d/gxsm;
     return $message;
  }
   
  sub regex_4 {
     my ($message) = @_;
     $message =~ s/\[b\](.*?)\[\/b\]/*$1*/igxsm;
     $message =~ s/\[i\](.*?)\[\/i\]/\/$1\//igxsm;
     $message =~ s/\[u\](.*?)\[\/u\]/_$1_/igxsm;
     $message =~ s/\[.*?\]//gxsm;
     $message =~ s/<br.*?>/\n/igxsm;
     return $message;
  }
   
  sub password_check {
     LoadLanguage('Register');
   
     if ( $action eq 'myprofile' ) {
         get_template('MyProfile');
     }
     else { $class = 'windowbg2'; }
     $check_js = qq~    <script type="text/javascript">
                 // Password_strength_meter start
                 var verdects = new Array("$pwstrengthmeter_txt{'1'}","$pwstrengthmeter_txt{'2'}","$pwstrengthmeter_txt{'3'}","$pwstrengthmeter_txt{'4'}","$pwstrengthmeter_txt{'5'}","$pwstrengthmeter_txt{'6'}","$pwstrengthmeter_txt{'7'}","$pwstrengthmeter_txt{'8'}");
                 var colors = new Array("#8F8F8F","#BF0000","#FF0000","#00A0FF","#33EE00","#339900");
                 var scores = new Array($pwstrengthmeter_scores);
                 var common = new Array($pwstrengthmeter_common);
                 var minchar = $pwstrengthmeter_minchar;
   
                 function runPassword(D) {
                     var nPerc = checkPassword(D);
                     if (nPerc > -199 && nPerc < 0) {
                         strColor = colors[0];
                         strText = verdects[1];
                         strWidth = "5%";
                     } else if (nPerc == -200) {
                         strColor = colors[1];
                         strText = verdects[0];
                         strWidth = "0%";
                     } else if (scores[0] == -1 && scores[1] == -1 && scores[2] == -1 && scores[3] == -1) {
                         strColor = colors[4];
                         strText = verdects[7];
                         strWidth = "100%";
                     } else if (nPerc <= scores[0]) {
                         strColor = colors[1];
                         strText = verdects[2];
                         strWidth = "10%";
                     } else if (nPerc > scores[0] && nPerc <= scores[1]) {
                         strColor = colors[2];
                         strText = verdects[3];
                         strWidth = "25%";
                     } else if (nPerc > scores[1] && nPerc <= scores[2]) {
                         strColor = colors[3];
                         strText = verdects[4];
                         strWidth = "50%";
                     } else if (nPerc > scores[2] && nPerc <= scores[3]) {
                         strColor = colors[4];
                         strText = verdects[5];
                         strWidth = "75%";
                     } else {
                         strColor = colors[5];
                         strText = verdects[6];
                         strWidth = "100%";
                     }
                     document.getElementById("passwrd1_bar").style.width = strWidth;
                     document.getElementById("passwrd1_bar").style.backgroundColor = strColor;
                     document.getElementById("passwrd1_text").style.color = strColor;
                     document.getElementById("passwrd1_text").childNodes[0].nodeValue = strText;
                 }
   
                 function checkPassword(C) {
                     if (C.length === 0 || C.length < minchar) return -100;
   
                     for (var D = 0; D < common.length; D++) {
                         if (C.toLowerCase() == common[D]) return -200;
                     }
   
                     var F = 0;
                     if (C.length >= minchar && C.length <= (minchar+2)) {
                         F = (F + 6);
                     } else if (C.length >= (minchar + 3) && C.length <= (minchar + 4)) {
                         F = (F + 12);
                     } else if (C.length >= (minchar + 5)) {
                         F = (F + 18);
                     }
   
                     if (C.match(/[a-z]/)) {
                         F = (F + 1);
                     }
                     if (C.match(/[A-Z]/)) {
                         F = (F + 5);
                     }
                     if (C.match(/d+/)) {
                         F = (F + 5);
                     }
                     if (C.match(/(.*[0-9].*[0-9].*[0-9])/)) {
                         F = (F + 7);
                     }
                     if (C.match(/.[!,\@,#,\$,\%,^,&,*,?,_,\~]/)) {
                         F = (F + 5);
                     }
                     if (C.match(/(.*[!,\@,#,\$,\%,^,&,*,?,_,\~].*[!,\@,#,\$,\%,^,&,*,?,_,\~])/)) {
                         F = (F + 7);
                     }
                     if (C.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)){
                         F = (F + 2);
                     }
                     if (C.match(/([a-zA-Z])/) && C.match(/([0-9])/)) {
                         F = (F + 3);
                     }
                     if (C.match(/([a-zA-Z0-9].*[!,\@,#,\$,\%,^,&,*,?,_,\~])|([!,\@,#,\$,\%,^,&,*,?,_,\~].*[a-zA-Z0-9])/)) {
                         F = (F + 3);
                     }
                     return F;
                 }
                 // Password_strength_meter end
                         </script>~;
     $check = $show_check;
     $check .= $show_check_bot;
     $check =~ s/{yabb check_js}/$check_js/sm;
     $check =~ s/{yabb tmpregpasswrd1}/$tmpregpasswrd1/sm;
     $check =~ s/{yabb tmpregpasswrd2}/$tmpregpasswrd2/sm;
   
     return $check;
  }
   
  sub BoardPassw {
  #    my ($boardname,$viewnum,$currentboard) = @_;
     #template in MessageIndex.template
     $yymain .= $boardpassw;
   
     $yytitle = qq~$maintxt{'900pw'}: $boardname~;
     template();
     exit;
  }
   
  sub BoardPassw_g {
     #template in MessageIndex.template
     $yymain .= $boardpassw_g;
   
     $yytitle = qq~$maintxt{'900pw'}: $boardname~;
     template();
     exit;
  }
  sub BoardPasswCheck {
   
     my $returnnum   = $FORM{'pswviewnum'};
     my $returnboard = $FORM{'pswcurboard'};
     my $spass       = ${ $uid . $returnboard }{'brdpassw'};
     my $cryptpass   = encode_password("$FORM{'boardpw'}");
     if ( $FORM{'boardpw'} eq q{} ) { fatal_error('', "$maintxt{'900pe'}"); }
     if ( $spass ne $cryptpass ) { fatal_error('wrong_pass'); }
     $ck{'len'} = 'Sunday, 17-Jan-2030 00:00:00 GMT';
     my $cookiename = "$cookiepassword$returnboard$username";
     push @otherCookies,
       write_cookie(
         -name    => "$cookiename",
         -value   => "$cryptpass",
         -path    => q{/},
         -expires => "$ck{'len'}" 
       );
     WriteLog();
     undef $FORM{'boardpw'};
   
     if ( $returnnum ne q{} ) {
         $yySetLocation = qq~$scripturl?num=$returnnum~;
     }
     else {
         $yySetLocation = qq~$scripturl?board=$returnboard~;
     }
     redirectexit();
     return;
  }
   
  sub UploadFile {
     my ( $file_upload, $file_directory, $file_extensions, $file_size, $directory_limit ) = @_;
     $file_directory = qq~$htmldir/$file_directory~;
   
     LoadLanguage('FA');
     require Sources::SpamCheck;
   
     if ($CGI_query) { $file = $CGI_query->upload("$file_upload"); }
     if ($file) {
         $fixfile = $file;
         $fixfile =~ s/.+\\([^\\]+)$|.+\/([^\/]+)$/$1/xsm;
         if ( $fixfile =~ /[^0-9A-Za-z\+\-\.:_]/xsm )
        {    # replace all inappropriate characters
             # Transliteration
             my $x = 0;
             foreach ( @uploadtranlist ) {
                 $fixfile =~ s/$_/$ISO_8859_1[$x]/gxsm;
                 $x++;
             }
   
             # END Transliteration. Thanks to "Velocity" for this contribution.
             # replace . with _ in the filename except for the extension
             $fixfile =~ s/[^0-9A-Za-z\+\-\.:_]/_/gxsm;
         }
   
         my $fixname = $fixfile;
         if ( $fixname =~ s/(.+)(\..+?)$/$1/xsm ) {
             $fixext = $2;
         }
   
         $spamdetected = spamcheck($fixname);
         if ( !$staff ) {
             if ( $spamdetected == 1 ) {
                 ${ $uid . $username }{'spamcount'}++;
                 ${ $uid . $username }{'spamtime'} = $date;
                 UserAccount( $username, 'update' );
                 $spam_hits_left_count = $post_speed_count -
                   ${ $uid . $username }{'spamcount'};
                 unlink "$file_directory/$fixfile";
                 fatal_error('tsc_alert');
             }
         }
         if ( $use_guardian && $string_on ) {
             @bannedstrings = split /\|/xsm, $banned_strings;
             foreach (@bannedstrings) {
                 chomp $_;
                 if ( $fixname =~ m/$_/ism ) {
                     fatal_error( 'attach_name_blocked', "($_)" );
                 }
             }
         }
   
         $fixext  =~ s/\.(pl|pm|cgi|php)/._$1/ixsm;
         $fixname =~ s/\.(?!tar$)/_/gxsm;
         $fixfile = qq~$fixname$fixext~;
         if ( $fixfile eq 'index.html' || $fixfile eq '.htaccess' ) { fatal_error('attach_file_blocked') };
   
         $fixfile = check_existence( $file_directory, $fixfile );
   
         my $match = 0;
         foreach my $ext ( split / /, $file_extensions ) {
             if ( grep { /$ext$/ixsm } $fixfile ) {
                 $match = 1;
                 last;
             }
         }
   
         if (!$match) {
             unlink "$file_directory/$fixfile";
             fatal_error( q{}, "$fixfile $fatxt{'20'} $file_extensions" );
         }
   
         my ( $size, $buffer, $filesize, $file_buffer );
         while ( $size = read $file, $buffer, 512 ) {
             $filesize += $size;
             $file_buffer .= $buffer;
         }
         if ( $file_size && $filesize > ( 1024 * $file_size ) ) {
             unlink "$file_directory/$fixfile";
             fatal_error( q{},
                     "$fatxt{'21'} $fixfile (" 
                   . int( $filesize / 1024 )
                   . " KB) $fatxt{'21b'} " 
                   . $file_size );
         }
         if ($directory_limit) {
             my $dirsize = dirsize($file_directory);
             if ( $file_size > ( ( 1024 * $directory_limit ) - $dirsize ) ) {
                 unlink "$file_directory/$fixfile";
                 fatal_error(
                     q{},
                     "$fatxt{'22'} $fixfile (" 
                       . (
                         int( $file_size / 1024 ) -
                           $directory_limit +
                           int( $dirsize / 1024 )
                        )
                        . " KB) $fatxt{'22b'}" 
                 );
             }
         }
   
         # create a new file on the server using the formatted ( new instance ) filename
         if ( fopen( NEWFILE, ">$file_directory/$fixfile" ) ) {
             binmode NEWFILE;
   
             # needed for operating systems (OS) Windows, ignored by Linux
             print {NEWFILE} $file_buffer
               or croak "$croak{'print'} NEWFILE"; # write new file on HD
             fclose(NEWFILE);
         }
         else
         { # return the server's error message if the new file could not be created
                 unlink "$file_directory/$fixfile";
                 fatal_error( 'file_not_open', "$file_directory" );
         }
   
         # check if file has actually been uploaded, by checking the file has a size
         $filesizekb{$fixfile} = -s "$file_directory/$fixfile";
         if ( !$filesizekb{$fixfile} ) {
             unlink "$file_directory/$fixfile";
             fatal_error( 'file_not_uploaded', $fixfile );
         }
         $filesizekb{$fixfile} = int( $filesizekb{$fixfile} / 1024 );
   
         if ( $fixfile =~ /\.(jpg|gif|png|jpeg)$/ism ) {
             my $okatt = 1;
             if ( $fixfile =~ /gif$/ism ) {
                 my $header;
                 fopen( ATTFILE, "$file_directory/$fixfile" );
                 read ATTFILE, $header, 10;
                 my $giftest;
                 ( $giftest, undef, undef, undef, undef, undef ) =
                   unpack 'a3a3C4', $header;
                 fclose(ATTFILE);
                 if ( $giftest ne 'GIF' ) { $okatt = 0; }
             }
             fopen( ATTFILE, "$file_directory/$fixfile" );
             while ( read ATTFILE, $buffer, 1024 ) {
                 if ( $buffer =~ /<(html|script|body)/igxsm ) {
                     $okatt = 0;
                     last;
                 }
             }
             fclose(ATTFILE);
             if ( !$okatt )
             {    # delete the file as it contains illegal code
                 unlink "$file_directory/$fixfile";
                 fatal_error( 'file_not_uploaded', "$fixfile $fatxt{'20a'}" );
              }
         }
   
     }
     return ($fixfile);
  }
   
  sub isempty {
     my ($x, $y) = @_;
     if ( defined $x && $x ne q{} ) {
         $y = $x;
     }
     return $y;
} }
   
1; 1;