package TWiki;
# Main Module of TWiki Collaboration Platform, http://TWiki.org/
# ($config->{TWiki}->{wikiversion} has version info)
#
# Copyright (C) 1999-2004 Peter Thoeny, peter@thoeny.com
#
# Based on parts of Ward Cunninghams original Wiki and JosWiki.
# Copyright (C) 1998 Markus Peter - SPiN GmbH (warpi@spin.de)
# Some changes by Dave Harris (drh@bhresearch.co.uk) incorporated
#
# For licensing info read license.txt file in the TWiki root.
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details, published at 
# http://www.gnu.org/copyleft/gpl.html
#
# Notes:
# - Latest version at http://twiki.org/
# - Installation instructions in $config->{TWiki}->{dataDir}/TWiki/TWikiDocumentation.txt
# - Customize variables in $config->{fileConfig}.pm when installing TWiki.
# - Optionally create a new plugin or customize DefaultPlugin.pm for
#   custom rendering rules.
# - Upgrading TWiki is easy as long as you only customize DefaultPlugin.pm.
# - Check web server error logs for errors, i.e. % tail /var/log/httpd/error_log
#
# 20000501 Kevin Kinnell : changed beta0404 to have many new search
#                          capabilities.  This file had a new hash added
#                          for month name-to-number look-ups, a slight
#                          change in the parameter list for the search
#                          script call in &handleSearchWeb, and a new
#                          sub -- &revDate2EpSecs -- for calculating the
#                          epoch seconds from a rev date (the only way
#                          to sort dates.)

=begin twiki

---+ TWiki Package
This package stores all TWiki subroutines that haven't been modularized
into any of the others.

=cut



use strict;

use Time::Local;	# Added for revDate2EpSecs
use Cwd qw( cwd ); 	# Added for getTWikiLibDir



    # Do a dynamic 'use locale' for this module

# ===========================
# TWiki config variables from $config->{fileConfig}.pm:


# Internationalisation (I18N) config from $config->{fileConfig}.pm:


# TWiki::Store config:


# TWiki::Search config:


# ===========================
# Global variables

# Refactoring Note: these are split up by "site" globals and "request"
# globals so that the latter may latter be placed inside a Perl object
# instead of being globals as now.

# ---------------------------
# Site-Wide Global Variables

# Misc. Globals


# Internationalisation (I18N) setup:


# ---------------------------
# Per-Request "Global" Variables

    
#
# Remark this part to have no var global
## ===========================
## Exports
##
## The Render module needs to access a lot of configuration flags from
## $config->{fileConfig}.pm, so we export them here.  We also export the %{$config->{TWiki}->{regex}} hash
## and a few other useful constants.
#
#use vars qw(@EXPORT_OK %EXPORT_TAGS @ISA);
#
#BEGIN {
#    require Exporter;
#    @ISA = qw(Exporter);
#    
#    %EXPORT_TAGS = (
#	renderflags => [qw($config->{TWiki}->{siteLang} $config->{TWiki}->{securityFilter} $config->{TWiki}->{twikiWebname} $config->{TWiki}->{mainWebname}
#	    $config->{TWiki}->{mainTopicname} $config->{TWiki}->{scriptSuffix} $config->{TWiki}->{doPluralToSingular}
#	    $config->{TWiki}->{dispScriptUrlPath} $config->{TWiki}->{dispViewPath}
#	)]
#    );
#    
#    @EXPORT_OK = qw(%{$config->{TWiki}->{regex}} $config->{TWiki}->{TranslationToken});
#    Exporter::export_ok_tags('renderflags');
#}

# ===========================
# TWiki version:

# ===========================
# Key Global variables, required for writeDebug
# (new variables must be declared in "use vars qw(..)" above)



# ===========================
# use TWiki and other modules
use TWiki::Prefs;     # preferences
use TWiki::Search;    # search engine
use TWiki::Access;    # access control
use TWiki::Meta;      # Meta class - topic meta data
use TWiki::Store;     # file I/O and rcs related functions
use TWiki::Attach;    # file attachment functions
use TWiki::Form;      # forms for topics
use TWiki::Func;      # official TWiki functions for plugins
use TWiki::Plugins;   # plugins handler  #AS
use TWiki::Net;       # SMTP, get URL
use TWiki::User;
use TWiki::Render;
use TWiki::UI;
use TWiki::UI::Changes;
use TWiki::UI::Edit;
use TWiki::UI::Manage;
use TWiki::UI::Oops;
use TWiki::UI::Preview;
use TWiki::UI::RDiff;
use TWiki::UI::Save;
use TWiki::UI::Search;
use TWiki::UI::Statistics;
use TWiki::UI::Upload;
use TWiki::UI::Viewfile;
use TWiki::UI::View;
use TWiki::User::HtPasswdUser;
use TWiki::User::NoPasswdUser;
use TWiki::Prefs::Parser;





# ===========================
# Other Global variables

# Token character that must not occur in any normal text - converted
# to a flag character if it ever does occur (very unlikely)

# The following are also initialized in initialize, here for cases where
# initialize not called.


# Header patterns based on '+++'. The '###' are reserved for numbered headers

sub new { 
	my $dummy = shift;
	my $config = shift;
	unshift @_,$dummy ;

   my ( $proto ) =@_ ;
   my $class = ref($proto) || $proto ;
   my $self;

	$self->{config}=$config;
   bless ( $self );

	$self->init_config();

   return $self ;
}





sub init_config { 

   my $self = shift;
	my $config = $self->{config} ;


require 5.005;		# For regex objects and internationalisation
{
    $config->{fileConfig} =~ /(.*)/ ;
    require "$1.pm";
    $config->{TWikicfg} = TWikicfg->new( $config );
    $config->{TWikicfg}->TWikicfg ();
    if( $config->{TWiki}->{useLocale} ) {
        require locale;
      import locale ();
    }
}


   $config->{TWiki}->{Render}=TWiki::Render->new($config) ;
   $config->{TWiki}->{Plugins}=TWiki::Plugins->new($config) ;
   $config->{TWiki}->{UI}=TWiki::UI->new($config) ;
   $config->{TWiki}->{Meta}=TWiki::Meta->new($config )  ;
   $config->{TWiki}->{Form}=TWiki::Form->new($config) ;
   $config->{TWiki}->{User}=TWiki::User->new($config) ;
   $config->{TWiki}->{Net}=TWiki::Net->new($config) ;
   $config->{TWiki}->{Store}=TWiki::Store->new($config) ;
   $config->{TWiki}->{Prefs}=TWiki::Prefs->new($config) ;
   $config->{TWiki}->{Attach}=TWiki::Attach->new($config) ;
   $config->{TWiki}->{Func}=TWiki::Func->new($config) ;
   $config->{TWiki}->{Access}=TWiki::Access->new($config) ;
   $config->{TWiki}->{Search}=TWiki::Search->new($config) ;


   $config->{TWiki}->{UI}->{Upload}=TWiki::UI::Upload->new($config) ;
   $config->{TWiki}->{UI}->{Save}=TWiki::UI::Save->new($config) ;
   $config->{TWiki}->{Prefs}->{Parser}=TWiki::Prefs::Parser->new($config )  ;
   $config->{TWiki}->{UI}->{Edit}=TWiki::UI::Edit->new($config) ;
   $config->{TWiki}->{UI}->{Viewfile}=TWiki::UI::Viewfile->new($config) ;
   $config->{TWiki}->{UI}->{Statistics}=TWiki::UI::Statistics->new($config) ;
   $config->{TWiki}->{UI}->{Preview}=TWiki::UI::Preview->new($config) ;
   $config->{TWiki}->{UI}->{RDiff}=TWiki::UI::RDiff->new($config) ;
   $config->{TWiki}->{User}->{NoPasswdUser}=TWiki::User::NoPasswdUser->new($config )  ;
   $config->{TWiki}->{User}->{HtPasswdUser}=TWiki::User::HtPasswdUser->new($config )  ;
   $config->{TWiki}->{UI}->{Search}=TWiki::UI::Search->new($config) ;
   $config->{TWiki}->{UI}->{View}=TWiki::UI::View->new($config) ;
   $config->{TWiki}->{UI}->{Changes}=TWiki::UI::Changes->new($config) ;
   $config->{TWiki}->{UI}->{Oops}=TWiki::UI::Oops->new($config) ;
   $config->{TWiki}->{UI}->{Manage}=TWiki::UI::Manage->new($config) ;

$config->{TWiki}->{wikiversion}      = '01 Sep 2004 $Rev: 1742 $';
@{$config->{TWiki}->{isoMonth}} = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
@{$config->{TWiki}->{weekDay}} = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
{ 
    my $count = 0;
    %{$config->{TWiki}->{mon2num}} = map { $_ => $count++ } @{$config->{TWiki}->{isoMonth}}; 
}
$config->{TWiki}->{Net}->init_config ();
$config->{TWiki}->{Prefs}->init_config ();
$config->{TWiki}->{Search}->init_config ();
$config->{TWiki}->{Plugins}->init_config ();
$config->{TWiki}->{TranslationToken}= "\0";	# Null not allowed in charsets used with TWiki
$config->{TWiki}->{cgiQuery} = 0;
@{$config->{TWiki}->{publicWebList}} = ();
$config->{TWiki}->{viewScript} = "view";
$config->{TWiki}->{regex}{linkProtocolPattern} = "(file|ftp|gopher|http|https|irc|news|nntp|telnet)";
$config->{TWiki}->{regex}{headerPatternDa} = '^---+(\++|\#+)\s*(.+)\s*$';       # '---++ Header', '---## Header'
$config->{TWiki}->{regex}{headerPatternSp} = '^\t(\++|\#+)\s*(.+)\s*$';         # '   ++ Header', '   + Header'
$config->{TWiki}->{regex}{headerPatternHt} = '^<h([1-6])>\s*(.+?)\s*</h[1-6]>'; # '<h6>Header</h6>
$config->{TWiki}->{regex}{headerPatternNoTOC} = '(\!\!+|%NOTOC%)';  # '---++!! Header' or '---++ Header %NOTOC% ^top'
$config->{TWiki}->{debugUserTime}   = 0;
$config->{TWiki}->{debugSystemTime} = 0;
$config->{TWiki}->{formatVersion} = "1.0";
$config->{TWiki}->{basicInitDone} = 0;		# basicInitialize not yet done
$config->{TWiki}->{pageMode} = 'html';		# Default is to render as HTML

}# END of init_config

#
# Configuration file is read in another part
## ===========================
## Read the configuration file at compile time in order to set locale
#BEGIN {
#    do "$config->{fileConfig}.pm";
#
#    # Do a dynamic 'use locale' for this module
#    if( $config->{TWiki}->{useLocale} ) {
#        require locale;
#	import locale ();
#    }
#}

sub writeDebug;
sub writeWarning;

=pod

---++ $config->{TWiki}->writeWarning ( $text )

Prints date, time, and contents $text to $config->{TWiki}->{warningFilename}, typically
'warnings.txt'.  Use for warnings and errors that may require admin
intervention.  Not using Store::writeLog; log file is more of an audit/usage
file.  Use this for defensive programming warnings (e.g. assertions).

=cut

sub writeWarning { 
   my $self = shift;
	my $config = $self->{config} ;


    my( $text ) = @_;
    if( $config->{TWiki}->{warningFilename} ) {
        my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime( time() );
	my( $tmon) = $config->{TWiki}->{isoMonth}[$mon];
        $year = sprintf( "%.4u", $year + 1900 );
        my $time = sprintf( "%.2u ${tmon} %.2u - %.2u:%.2u",
			   $mday, $year, $hour, $min );

        if( open( FILE, ">>$config->{TWiki}->{warningFilename}" ) ) {
            print FILE "$time $text\n";
            close( FILE );
        } else {
            print STDERR "Couldn't write \"$text\" to $config->{TWiki}->{warningFilename}: $!\n";
        }
    }
}

=pod

---++ $config->{TWiki}->writeDebug ( $text )

Prints date, time, and contents of $text to $config->{TWiki}->{debugFilename}, typically
'debug.txt'.  Use for debugging messages.

=cut

sub writeDebug { 
   my $self = shift;
	my $config = $self->{config} ;


    my( $text ) = @_;
    
    my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime( time() );
    my( $tmon) = $config->{TWiki}->{isoMonth}[$mon];
    $year = sprintf( "%.4u", $year + 1900 );
    my $time = sprintf( "%.2u ${tmon} %.2u - %.2u:%.2u", $mday, $year, $hour, $min );

    if( open( FILE, ">>$config->{TWiki}->{debugFilename}" ) ) {
         print FILE "$time $text\n";
         close( FILE );
    } else {
         print STDERR "Couldn't write \"$text\" to $config->{TWiki}->{debugFilename}: $!\n";
    }
}

=pod

---++ $config->{TWiki}->writeDebugTimes ( $text )

Dumps user and system time spent, with deltas from last call, followed
by contents of $text, to debug log using writeDebug above.  Use for
performance monitoring/debugging.

=cut

sub writeDebugTimes
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $text ) = @_;

    if( ! $config->{TWiki}->{debugUserTime} ) {
        $config->{TWiki}->writeDebug ( "===      sec (delta:)     sec (delta:)     sec   function:" );
    }
    my( $puser, $psystem, $cuser, $csystem ) = times();
    my $duser = $puser - $config->{TWiki}->{debugUserTime};
    my $dsystem = $psystem - $config->{TWiki}->{debugSystemTime};
    my $times = sprintf( "usr %1.2f (%1.2f), sys %1.2f (%1.2f), sum %1.2f",
                  $puser, $duser, $psystem, $dsystem, $puser+$psystem );
    $config->{TWiki}->{debugUserTime}   = $puser;
    $config->{TWiki}->{debugSystemTime} = $psystem;

    $config->{TWiki}->writeDebug ( "==> $times,  $text" );
}

=pod

---++ $config->{TWiki}->initialize ( $pathInfo, $remoteUser, $topic, $url, $query )
Return value: ( $config->{TWiki}->{topicName}, $config->{TWiki}->{webName}, $config->{TWiki}->{scriptUrlPath}, $config->{TWiki}->{userName}, $config->{TWiki}->{dataDir} )

Per-web initialization of all aspects of TWiki.  Initializes the
Store, User, Access, and Prefs modules.  Contains two plugin
initialization hooks: 'initialize1' to allow plugins to interact
for authentication, and 'initialize2' once the authenticated username
is available.

Also parses $theTopic to determine whether it's a URI, a "Web.Topic"
pair, a "Web." WebHome shorthand, or just a topic name.  Note that
if $pathInfo is set, this overrides $theTopic.

=cut

sub initialize
{ 
   my $self = shift;
	my $config = $self->{config} ;


 
	 $config->{TWiki}->init_config () ;

    my ( $thePathInfo, $theRemoteUser, $theTopic, $theUrl, $theQuery ) = @_;
    
    if( not $config->{TWiki}->{basicInitDone} ) {
	$config->{TWiki}->basicInitialize () ;
    }

    ##$config->{TWiki}->writeDebug ( "\n---------------------------------" );

    $config->{TWiki}->{cgiQuery} = $theQuery;
    
    # Initialise vars here rather than at start of module,
    # so compatible with modPerl
    @{$config->{TWiki}->{publicWebList}} = ();
    $config->{TWiki}->{Store}->initialize ();

    $config->{TWiki}->{User}->initialize ();

    # Make %ENV safer for CGI
    if( $config->{TWiki}->{safeEnvPath} ) {
        $ENV{'PATH'} = $config->{TWiki}->{safeEnvPath};
    }
    delete @ENV{ qw( IFS CDPATH ENV BASH_ENV ) };

    # initialize lib directory early because of later 'cd's
    $config->{TWiki}->getTWikiLibDir () ;

    # initialize access control
    $config->{TWiki}->{Access}->initializeAccess ();
    $config->{TWiki}->{readTopicPermissionFailed} = ""; # Will be set to name(s) of topic(s) that can't be read

    # initialize $config->{TWiki}->{webName} and $config->{TWiki}->{topicName} from URL
    $config->{TWiki}->{topicName} = "";
    $config->{TWiki}->{webName}   = "";
    if( $theTopic ) {
        if(( $theTopic =~ /^$config->{TWiki}->{regex}{linkProtocolPattern}\:\/\//o ) && ( $config->{TWiki}->{cgiQuery} ) ) {
            # redirect to URI
            print $config->{TWiki}->{cgiQuery}->redirect( $theTopic );
            return; # should never return here
        } elsif( $theTopic =~ /(.*)[\.\/](.*)/ ) {
            # is "bin/script?topic=Webname.SomeTopic"
            $config->{TWiki}->{webName}   = $1 || "";
            $config->{TWiki}->{topicName} = $2 || "";
            # jump to WebHome if ""bin/script?topic=Webname."
            $config->{TWiki}->{topicName} = $config->{TWiki}->{mainTopicname} if( $config->{TWiki}->{webName} && ( ! $config->{TWiki}->{topicName} ) );
        } else {
            # assume "bin/script/Webname?topic=SomeTopic"
            $config->{TWiki}->{topicName} = $theTopic;
        }
    }

    # Clean up PATH_INFO problems, e.g.  Support.CobaltRaqInstall.  A valid
    # PATH_INFO is '/Main/WebHome', i.e. the text after the script name;
    # invalid PATH_INFO is often a full path starting with '/cgi-bin/...'.
    my $cgiScriptName = $ENV{'SCRIPT_NAME'} || "";
    $thePathInfo =~ s!$cgiScriptName/!/!i;
    ## $config->{TWiki}->writeDebug ( "===== thePathInfo after cleanup = $thePathInfo" );

    # Get the web and topic names from PATH_INFO
    if( $thePathInfo =~ /\/(.*)[\.\/](.*)/ ) {
        # is "bin/script/Webname/SomeTopic" or "bin/script/Webname/"
        $config->{TWiki}->{webName}   = $1 || "" if( ! $config->{TWiki}->{webName} );
        $config->{TWiki}->{topicName} = $2 || "" if( ! $config->{TWiki}->{topicName} );
    } elsif( $thePathInfo =~ /\/(.*)/ ) {
        # is "bin/script/Webname" or "bin/script/"
        $config->{TWiki}->{webName}   = $1 || "" if( ! $config->{TWiki}->{webName} );
    }
    ( $config->{TWiki}->{topicName} =~ /\.\./ ) && ( $config->{TWiki}->{topicName} = $config->{TWiki}->{mainTopicname} );

    # Refuse to work with character sets that allow TWiki syntax
    # to be recognised within multi-byte characters.  Only allow 'oops'
    # page to be displayed (redirect causes this code to be re-executed).
    if ( $config->{TWiki}->invalidSiteCharset ()  and $theUrl !~ m!$config->{TWiki}->{scriptUrlPath}/oops! ) {  
	$config->{TWiki}->writeWarning (  "Cannot use this multi-byte encoding ('$config->{TWiki}->{siteCharset}') as site character encoding" );
	$config->{TWiki}->writeWarning (  "Please set a different character encoding in the \$config->{TWiki}->{siteLocale} setting in $config->{fileConfig}.pm." );
        my $url = $config->{TWiki}->getOopsUrl ( $config->{TWiki}->{webName}, $config->{TWiki}->{topicName}, "oopsbadcharset" );
	print $config->{TWiki}->{cgiQuery}->redirect( $url );
        return;
    }

    # Convert UTF-8 web and topic name from URL into site charset 
    # if necessary - no effect if URL is not in UTF-8
    ( $config->{TWiki}->{webName}, $config->{TWiki}->{topicName} ) = $config->{TWiki}->convertUtf8URLtoSiteCharset ( $config->{TWiki}->{webName}, $config->{TWiki}->{topicName} );

    # Filter out dangerous or unwanted characters
    $config->{TWiki}->{topicName} =~ s/$config->{TWiki}->{securityFilter}//go;
    $config->{TWiki}->{topicName} =~ /(.*)/;
    $config->{TWiki}->{topicName} = $1 || $config->{TWiki}->{mainTopicname};  # untaint variable
    $config->{TWiki}->{webName}   =~ s/$config->{TWiki}->{securityFilter}//go;
    $config->{TWiki}->{webName}   =~ /(.*)/;
    $config->{TWiki}->{webName}   = $1 || $config->{TWiki}->{mainWebname};  # untaint variable
    $config->{TWiki}->{includingTopicName} = $config->{TWiki}->{topicName};
    $config->{TWiki}->{includingWebName} = $config->{TWiki}->{webName};

    # initialize $config->{TWiki}->{urlHost} and $config->{TWiki}->{scriptUrlPath} 
    if( ( $theUrl ) && ( $theUrl =~ m!^([^:]*://[^/]*)(.*)/.*$! ) && ( $2 ) ) {
        if( $config->{TWiki}->{doGetScriptUrlFromCgi} ) {
            $config->{TWiki}->{scriptUrlPath} = $2;
        }
        $config->{TWiki}->{urlHost} = $1;
        if( $config->{TWiki}->{doRemovePortNumber} ) {
            $config->{TWiki}->{urlHost} =~ s/\:[0-9]+$//;
        }
    } else {
        $config->{TWiki}->{urlHost} = $config->{TWiki}->{defaultUrlHost};
    }
    # PTh 15 Jul 2001: Removed init of $config->{TWiki}->{scriptUrlPath} based on $theUrl because
    # $theUrl has incorrect URI after failed authentication

    # initialize preferences, first part for site and web level
    $config->{TWiki}->{Prefs}->initializePrefs ( $config->{TWiki}->{webName} );

    # initialize user name and user to WikiName list
    $config->{TWiki}->userToWikiListInit () ;
    if( !$config->{TWiki}->{disableAllPlugins} ) {
            # Early plugin initialization, allow plugins like SessionPlugin
	    # to set the user.  This must be done before preferences are set,
	    # as we need to get user preferences
            $config->{TWiki}->{userName} = $config->{TWiki}->{Plugins}->initialize1 ( $config->{TWiki}->{topicName}, $config->{TWiki}->{webName}, $theRemoteUser, $theUrl, $thePathInfo );
    }
    $config->{TWiki}->{wikiName}     = $config->{TWiki}->userToWikiName ( $config->{TWiki}->{userName}, 1 );      # i.e. "JonDoe"
    $config->{TWiki}->{wikiUserName} = $config->{TWiki}->userToWikiName ( $config->{TWiki}->{userName} );         # i.e. "Main.JonDoe"

    # initialize preferences, second part for user level
    $config->{TWiki}->{Prefs}->initializeUserPrefs ( $config->{TWiki}->{wikiUserName} );

    # some remaining init
    $config->{TWiki}->{viewScript} = "view";
    if( ( $ENV{'SCRIPT_NAME'} ) && ( $ENV{'SCRIPT_NAME'} =~ /^.*\/viewauth$/ ) ) {
        # Needed for TOC
        $config->{TWiki}->{viewScript} = "viewauth";
    }
    
    $config->{TWiki}->{Render}->initialize ();

#AS
    if( !$config->{TWiki}->{disableAllPlugins} ) {
        # Normal plugin initialization - userName is known and preferences available
        $config->{TWiki}->{Plugins}->initialize2 ( $config->{TWiki}->{topicName}, $config->{TWiki}->{webName}, $config->{TWiki}->{userName} );
    }
#/AS

    return ( $config->{TWiki}->{topicName}, $config->{TWiki}->{webName}, $config->{TWiki}->{scriptUrlPath}, $config->{TWiki}->{userName}, $config->{TWiki}->{dataDir} );
}

=pod

---++ $config->{TWiki}->basicInitialize () 

Sets up POSIX locale and precompiled regexes - for use from scripts
that handle multiple webs (e.g. mailnotify) and need regexes or
isWebName/isWikiName to work before the per-web $config->{TWiki}->initialize ()  is called.
Also called from $config->{TWiki}->initialize ()  if not necessary beforehand.

=cut

sub basicInitialize { 
   my $self = shift;
	my $config = $self->{config} ;


 
	 $config->{TWiki}->init_config () ;

    # Set up locale for internationalisation and pre-compile regexes
    $config->{TWiki}->setupLocale () ;
    $config->{TWiki}->setupRegexes () ;
    
    $config->{TWiki}->{basicInitDone} = 1;
}

=pod

---++ $config->{TWiki}->setupLocale () 

Run-time locale setup - If $config->{TWiki}->{useLocale} is set, this function parses $config->{TWiki}->{siteLocale}
from $config->{fileConfig}.pm and passes it to the POSIX::setLocale function to change TWiki's
operating environment.

mod_perl compatibility note: If TWiki is running under Apache, won't this play
with the Apache process's locale settings too?  What effects would this have?

Note that 'use locale' must be done in BEGIN block for regexes and sorting to
work properly, although regexes can still work without this in
'non-locale regexes' mode (see setupRegexes routine).

=cut

sub setupLocale { 
   my $self = shift;
	my $config = $self->{config} ;


 
    $config->{TWiki}->{siteCharset} = 'ISO-8859-1';	# Default values if locale mis-configured
    $config->{TWiki}->{siteLang} = 'en';
    $config->{TWiki}->{siteFullLang} = 'en-us';

    if ( $config->{TWiki}->{useLocale} ) {
	if ( not defined $config->{TWiki}->{siteLocale} or $config->{TWiki}->{siteLocale} !~ /[a-z]/i ) {
	    $config->{TWiki}->writeWarning (  "Locale $config->{TWiki}->{siteLocale} unset or has no alphabetic characters" );
	    return;
	}
	# Extract the character set from locale and use in HTML templates
	# and HTTP headers
	$config->{TWiki}->{siteLocale} =~ m/\.([a-z0-9_-]+)$/i;
	$config->{TWiki}->{siteCharset} = $1 if defined $1;
	$config->{TWiki}->{siteCharset} =~ s/^utf8$/utf-8/i;	# For convenience, avoid overrides
	$config->{TWiki}->{siteCharset} =~ s/^eucjp$/euc-jp/i;

	# Override charset - used when locale charset not supported by Perl
	# conversion modules
	$config->{TWiki}->{siteCharset} = $config->{TWiki}->{siteCharsetOverride} || $config->{TWiki}->{siteCharset};
	$config->{TWiki}->{siteCharset} = lc $config->{TWiki}->{siteCharset};

	# Extract the default site language - ignores '@euro' part of
	# 'fr_BE@euro' type locales.
	$config->{TWiki}->{siteLocale} =~ m/^([a-z]+)_([a-z]+)/i;
	$config->{TWiki}->{siteLang} = (lc $1) if defined $1;	# Not including country part
	$config->{TWiki}->{siteFullLang} = (lc "$1-$2" ) 		# Including country part
		if defined $1 and defined $2;

	# Set environment variables for grep 
	$ENV{'LC_CTYPE'}= $config->{TWiki}->{siteLocale};

	# Load POSIX for I18N support 
	require POSIX;
	import POSIX qw( locale_h LC_CTYPE );

	# Set new locale
	my $locale = setlocale(&LC_CTYPE, $config->{TWiki}->{siteLocale});
	##$config->{TWiki}->writeDebug (  "New locale is $locale" );
    }
}

=pod

---++ $config->{TWiki}->setupRegexes () 

Set up pre-compiled regexes for use in rendering.  All regexes with
unchanging variables in match should use the '/o' option, even if not in a
loop, to help mod_perl, where the same code can be executed many times
without recompilation.

=cut

sub setupRegexes { 
   my $self = shift;
	my $config = $self->{config} ;



    # Build up character class components for use in regexes.
    # Depends on locale mode and Perl version, and finally on
    # whether locale-based regexes are turned off.
    if ( not $config->{TWiki}->{useLocale} or $] < 5.006 or not $config->{TWiki}->{localeRegexes} ) {
	# No locales needed/working, or Perl 5.005_03 or lower, so just use
	# any additional national characters defined in $config->{fileConfig}.pm
	$config->{TWiki}->{regex}{upperAlpha} = "A-Z$config->{TWiki}->{upperNational}";
	$config->{TWiki}->{regex}{lowerAlpha} = "a-z$config->{TWiki}->{lowerNational}";
	$config->{TWiki}->{regex}{numeric} = '\d';
	$config->{TWiki}->{regex}{mixedAlpha} = "$config->{TWiki}->{regex}{upperAlpha}$config->{TWiki}->{regex}{lowerAlpha}";
    } else {
	# Perl 5.6 or higher with working locales
	$config->{TWiki}->{regex}{upperAlpha} = "[:upper:]";
	$config->{TWiki}->{regex}{lowerAlpha} = "[:lower:]";
	$config->{TWiki}->{regex}{numeric} = "[:digit:]";
	$config->{TWiki}->{regex}{mixedAlpha} = "[:alpha:]";
    }
    $config->{TWiki}->{regex}{mixedAlphaNum} = "$config->{TWiki}->{regex}{mixedAlpha}$config->{TWiki}->{regex}{numeric}";
    $config->{TWiki}->{regex}{lowerAlphaNum} = "$config->{TWiki}->{regex}{lowerAlpha}$config->{TWiki}->{regex}{numeric}";

    # Compile regexes for efficiency and ease of use
    # Note: qr// locks in regex modes (i.e. '-xism' here) - see Friedl
    # book at http://regex.info/. 

    # TWiki concept regexes
    $config->{TWiki}->{regex}{wikiWordRegex} = qr/[$config->{TWiki}->{regex}{upperAlpha}]+[$config->{TWiki}->{regex}{lowerAlpha}]+[$config->{TWiki}->{regex}{upperAlpha}]+[$config->{TWiki}->{regex}{mixedAlphaNum}]*/;
    $config->{TWiki}->{regex}{webNameRegex} = qr/[$config->{TWiki}->{regex}{upperAlpha}]+[$config->{TWiki}->{regex}{mixedAlphaNum}]*/;
    $config->{TWiki}->{regex}{defaultWebNameRegex} = qr/_[$config->{TWiki}->{regex}{mixedAlphaNum}_]+/;
    $config->{TWiki}->{regex}{anchorRegex} = qr/\#[$config->{TWiki}->{regex}{mixedAlphaNum}_]+/;
    $config->{TWiki}->{regex}{abbrevRegex} = qr/[$config->{TWiki}->{regex}{upperAlpha}]{3,}s?\b/;

    # Simplistic email regex, e.g. for WebNotify processing - no i18n
    # characters allowed
    $config->{TWiki}->{regex}{emailAddrRegex} = qr/([A-Za-z0-9\.\+\-\_]+\@[A-Za-z0-9\.\-]+)/;

    # Filename regex, for attachments
    $config->{TWiki}->{regex}{filenameRegex} = qr/[$config->{TWiki}->{regex}{mixedAlphaNum}\.]+/;

    # Single-character alpha-based regexes
    $config->{TWiki}->{regex}{singleUpperAlphaRegex} = qr/[$config->{TWiki}->{regex}{upperAlpha}]/;
    $config->{TWiki}->{regex}{singleLowerAlphaRegex} = qr/[$config->{TWiki}->{regex}{lowerAlpha}]/;
    $config->{TWiki}->{regex}{singleUpperAlphaNumRegex} = qr/[$config->{TWiki}->{regex}{upperAlpha}$config->{TWiki}->{regex}{numeric}]/;
    $config->{TWiki}->{regex}{singleMixedAlphaNumRegex} = qr/[$config->{TWiki}->{regex}{upperAlpha}$config->{TWiki}->{regex}{lowerAlpha}$config->{TWiki}->{regex}{numeric}]/;

    $config->{TWiki}->{regex}{singleMixedNonAlphaRegex} = qr/[^$config->{TWiki}->{regex}{upperAlpha}$config->{TWiki}->{regex}{lowerAlpha}]/;
    $config->{TWiki}->{regex}{singleMixedNonAlphaNumRegex} = qr/[^$config->{TWiki}->{regex}{upperAlpha}$config->{TWiki}->{regex}{lowerAlpha}$config->{TWiki}->{regex}{numeric}]/;

    # Multi-character alpha-based regexes
    $config->{TWiki}->{regex}{mixedAlphaNumRegex} = qr/[$config->{TWiki}->{regex}{mixedAlphaNum}]*/;

    # Character encoding regexes

    # 7-bit ASCII only
    $config->{TWiki}->{regex}{validAsciiStringRegex} = qr/^[\x00-\x7F]+$/;
    
    # Regex to match only a valid UTF-8 character, taking care to avoid
    # security holes due to overlong encodings by excluding the relevant
    # gaps in UTF-8 encoding space - see 'perldoc perlunicode', Unicode
    # Encodings section.  Tested against Markus Kuhn's UTF-8 test file
    # at http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt.
    $config->{TWiki}->{regex}{validUtf8CharRegex} = qr{
				# Single byte - ASCII
				[\x00-\x7F] 
				|

				# 2 bytes
				[\xC2-\xDF][\x80-\xBF] 
				|

				# 3 bytes

				    # Avoid illegal codepoints - negative lookahead
				    (?!\xEF\xBF[\xBE\xBF])	

				    # Match valid codepoints
				    (?:
					([\xE0][\xA0-\xBF])|
					([\xE1-\xEC\xEE-\xEF][\x80-\xBF])|
					([\xED][\x80-\x9F])
				    )
				    [\x80-\xBF]
				|

				# 4 bytes 
				    (?:
					([\xF0][\x90-\xBF])|
					([\xF1-\xF3][\x80-\xBF])|
					([\xF4][\x80-\x8F])
				    )
				    [\x80-\xBF][\x80-\xBF]
			    }x;

    $config->{TWiki}->{regex}{validUtf8StringRegex} = qr/^ (?: $config->{TWiki}->{regex}{validUtf8CharRegex} )+ $/x;

}

=pod

---++ $config->{TWiki}->invalidSiteCharset () 
Return value: boolean $isCharsetInvalid

Check for unusable multi-byte encodings as site character set
- anything that enables a single ASCII character such as '[' to be
matched within a multi-byte character cannot be used for TWiki.

=cut

sub invalidSiteCharset { 
   my $self = shift;
	my $config = $self->{config} ;


    # FIXME: match other problematic multi-byte character sets 
    return ( $config->{TWiki}->{siteCharset} =~ /^(?:iso-2022-?|hz-?|.*big5|.*shift_?jis|ms.kanji)/i );
}


=pod

---++ $config->{TWiki}->convertUtf8URLtoSiteCharset ( $config->{TWiki}->{webName}, $config->{TWiki}->{topicName} )
Return value: ( string $convertedWebName, string $convertedTopicName)
Auto-detect UTF-8 vs. site charset in URL, and convert UTF-8 into site charset.

TODO: remove dependence on webname and topicname, i.e. generic encoding
subroutine.

=cut

sub convertUtf8URLtoSiteCharset { 
   my $self = shift;
	my $config = $self->{config} ;


    my ( $webNameLoc, $topicNameLoc ) = @_;

    ##$config->{TWiki}->writeDebug (  "URL web.topic is $config->{TWiki}->{webName}.$config->{TWiki}->{topicName}" );
    my $fullTopicName = "$webNameLoc.$topicNameLoc";
    my $charEncoding;

    # Detect character encoding of the full topic name from URL
    if ( $fullTopicName =~ $config->{TWiki}->{regex}{validAsciiStringRegex} ) {
	$config->{TWiki}->{urlCharEncoding} = 'ASCII';
    } elsif ( $fullTopicName =~ $config->{TWiki}->{regex}{validUtf8StringRegex} ) {
	$config->{TWiki}->{urlCharEncoding} = 'UTF-8';

	# Convert into ISO-8859-1 if it is the site charset
	if ( $config->{TWiki}->{siteCharset} =~ /^iso-?8859-?1$/i ) {
	    # ISO-8859-1 maps onto first 256 codepoints of Unicode
	    # (conversion from 'perldoc perluniintro')
	    $fullTopicName =~ s/ ([\xC2\xC3]) ([\x80-\xBF]) / 
				 chr( ord($1) << 6 & 0xC0 | ord($2) & 0x3F )
				 /egx;
	} elsif ( $config->{TWiki}->{siteCharset} eq "utf-8" ) {
	    # Convert into internal Unicode characters if on Perl 5.8 or higher.
	    if( $] >= 5.008 ) {
		require Encode;			# Perl 5.8 or higher only
		$fullTopicName = Encode::decode("utf8", $fullTopicName);	# 'decode' into UTF-8
	    } else {
		$config->{TWiki}->writeWarning (  "UTF-8 not supported on Perl $] - use Perl 5.8 or higher." );
	    }
	    $config->{TWiki}->writeWarning (  "UTF-8 not yet supported as site charset - TWiki is likely to have problems" );
	} else {
	    # Convert from UTF-8 into some other site charset
	    $config->{TWiki}->writeDebug (  "Converting from UTF-8 to $config->{TWiki}->{siteCharset}" );

	    # Use conversion modules depending on Perl version
	    if( $] >= 5.008 ) {
		require Encode;			# Perl 5.8 or higher only
                import Encode qw(:fallbacks);
		# Map $config->{TWiki}->{siteCharset} into real encoding name
		$charEncoding = Encode::resolve_alias( $config->{TWiki}->{siteCharset} );
		if( not $charEncoding ) {
		    $config->{TWiki}->writeWarning (  "Conversion to \$config->{TWiki}->{siteCharset} '$config->{TWiki}->{siteCharset}' not supported, or name not recognised - check 'perldoc Encode::Supported'" );
		} else {
		    ##$config->{TWiki}->writeDebug (  "Converting with Encode, valid 'to' encoding is '$charEncoding'" );
		    # Convert text using Encode:
		    # - first, convert from UTF8 bytes into internal (UTF-8) characters
		    $fullTopicName = Encode::decode("utf8", $fullTopicName);	
		    # - then convert into site charset from internal UTF-8,
		    # inserting \x{NNNN} for characters that can't be converted
                    $fullTopicName = Encode::encode( $charEncoding, $fullTopicName, &FB_PERLQQ );
		    ##$config->{TWiki}->writeDebug (  "Encode result is $fullTopicName" );
		}

	    } else {
		require Unicode::MapUTF8;	# Pre-5.8 Perl versions
		$charEncoding = $config->{TWiki}->{siteCharset};
		if( not Unicode::MapUTF8::utf8_supported_charset($charEncoding) ) {
		    $config->{TWiki}->writeWarning (  "Conversion to \$config->{TWiki}->{siteCharset} '$config->{TWiki}->{siteCharset}' not supported, or name not recognised - check 'perldoc Unicode::MapUTF8'" );
		} else {
		    # Convert text
		    ##$config->{TWiki}->writeDebug (  "Converting with Unicode::MapUTF8, valid encoding is '$charEncoding'" );
		    $fullTopicName = Unicode::MapUTF8::from_utf8({ 
			    			-string => $fullTopicName, 
		    			 	-charset => $charEncoding });
		    # FIXME: Check for failed conversion?
		}
	    }
	}
	($webNameLoc, $topicNameLoc) = split /\./, $fullTopicName;

    } else {
	# Non-ASCII and non-UTF-8 - assume in site character set, 
	# no conversion required
	$config->{TWiki}->{urlCharEncoding} = 'Native';
	$charEncoding = $config->{TWiki}->{siteCharset};
    }
    ##$config->{TWiki}->writeDebug (  "Final web and topic are $config->{TWiki}->{webName} $config->{TWiki}->{topicName} ($config->{TWiki}->{urlCharEncoding} URL -> $config->{TWiki}->{siteCharset})" );

    return ($webNameLoc, $topicNameLoc);
}

=pod

---++ $config->{TWiki}->writeHeader ( $query )

Simple header setup for most scripts.  Calls writeHeaderFull, assuming
'basic' type and 'text/html' content-type.

=cut

sub writeHeader
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $query ) = @_;

    # FIXME: Pass real content-length to make persistent connections work
    # in HTTP/1.1 (performance improvement for browsers and servers). 
    # Requires significant but easy changes in various places.

    # Just write a basic content-type header for text/html
    $config->{TWiki}->writeHeaderFull ( $query, 'basic', 'text/html', 0);
}


=pod

---++ $config->{TWiki}->writeHeaderFull ( $query, $pageType, $contentType, $contentLength )

Builds and outputs HTTP headers.  $pageType should (currently) be either
"edit" or "basic".  $query is the object from the CGI module, not the actual
query string.

"edit" will cause headers to be generated that force caching for 24 hours, to
prevent Codev.BackFromPreviewLosesText bug, which caused data loss with IE5 and
IE6.

"basic" will cause only the Content-Type header to be set (from the
parameter), plus any headers set by plugins.  Hopefully, further types will
be used to improve cacheability for other pages in future.

Implements the post-Dec2001 release plugin API, which requires the
writeHeaderHandler in plugin to return a string of HTTP headers, CR/LF
delimited.  Filters out headers that the core code needs to generate for
whatever reason, and any illegal headers.

=cut

sub writeHeaderFull
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $query, $pageType, $contentType, $contentLength ) = @_;

    # Handle Edit pages - future versions will extend to caching
    # of other types of page, with expiry time driven by page type.
    my( $pluginHeaders, $coreHeaders );


    $contentType .= "; charset=$config->{TWiki}->{siteCharset}";

    if ($pageType eq 'edit') {
	# Get time now in HTTP header format
	my $lastModifiedString = $config->{TWiki}->formatTime (time, '\$http', "gmtime");

	# Expiry time is set high to avoid any data loss.  Each instance of 
	# Edit page has a unique URL with time-string suffix (fix for 
	# RefreshEditPage), so this long expiry time simply means that the 
	# browser Back button always works.  The next Edit on this page 
	# will use another URL and therefore won't use any cached 
	# version of this Edit page.
	my $expireHours = 24;
	my $expireSeconds = $expireHours * 60 * 60;

	# Set content length, to enable HTTP/1.1 persistent connections 
	# (aka HTTP keepalive), and cache control headers, to ensure edit page 
	# is cached until required expiry time.
	$coreHeaders = $query->header( 
			    -content_type => $contentType,
			    -content_length => $contentLength,
			    -last_modified => $lastModifiedString,
			    -expires => "+${expireHours}h",
			    -cache_control => "max-age=$expireSeconds",
			 );
    } elsif ($pageType eq 'basic') {
	$coreHeaders = $query->header(
	    		    -content_type => $contentType,
			 );
    } else {
	$config->{TWiki}->writeWarning ( "===== invalid page type in TWiki.pm, $config->{TWiki}->writeHeaderFull () : $pageType" );
    }

    # Delete extra CR/LF to allow suffixing more headers
    $coreHeaders =~ s/\r\n\r\n$/\r\n/s;
    ##$config->{TWiki}->writeDebug ( "===== After trim, Headers are:\n$coreHeaders" );

    # Wiki Plugin Hook - get additional headers from plugin
    $pluginHeaders = $config->{TWiki}->{Plugins}->writeHeaderHandler ( $query ) || '';

    # Delete any trailing blank line
    $pluginHeaders =~ s/\r\n\r\n$/\r\n/s;

    # Add headers supplied by plugin, omitting any already in core headers
    my $finalHeaders = $coreHeaders;
    if( $pluginHeaders ) {
	# Build hash of all core header names, lower-cased
	my ($headerLine, $headerName, %coreHeaderSeen);
	for $headerLine (split /\r\n/, $coreHeaders) {
	    $headerLine =~ m/^([^ ]+): /i;		# Get header name
	    $headerName = lc($1);
	    ##$config->{TWiki}->writeDebug ("==== core header name $headerName");
	    $coreHeaderSeen{$headerName}++;
	}
	# Append plugin headers if legal and not seen in core headers
	for $headerLine (split /\r\n/, $pluginHeaders) {
	    $headerLine =~ m/^([^ ]+): /i;		# Get header name
	    $headerName = lc($1);
	    if ( $headerName =~ m/[\-a-z]+/io ) {	# Skip bad headers
		##$config->{TWiki}->writeDebug ("==== plugin header name $headerName");
		##$config->{TWiki}->writeDebug ("Saw $headerName already ") if $coreHeaderSeen{$headerName};
		$finalHeaders .= $headerLine . "\r\n"
		    unless $coreHeaderSeen{$headerName};
	    }

	}
    }
    $finalHeaders .= "\r\n" if ( $finalHeaders);

    ##$config->{TWiki}->writeDebug ( "===== Final Headers are:\n$finalHeaders" );
    print $finalHeaders;

}

=pod

---++ $config->{TWiki}->setPageMode ( $mode )

Set page rendering mode:
   * 'rss' - encode 8-bit characters as XML entities
   * 'html' - (default) no encoding of 8-bit characters
   
=cut

sub setPageMode
{ 
   my $self = shift;
	my $config = $self->{config} ;


    $config->{TWiki}->{pageMode} = shift;
}

=pod

---++ $config->{TWiki}->getPageMode () 
Return value: string $mode

Returns current page mode, 'html' unless set via setPageMode
FIXME: This function is currently unused.  Remove on some non
documentation-only commit, unless use is planned in future.

=cut

sub getPageMode
{ 
   my $self = shift;
	my $config = $self->{config} ;


    return $config->{TWiki}->{pageMode};
}

=pod

---++ $config->{TWiki}->getCgiQuery () 
Retrun value: string $query

Returns the CGI query portion (i.e. the bit after the '?') of the
current request.

=cut

sub getCgiQuery
{ 
   my $self = shift;
	my $config = $self->{config} ;


    return $config->{TWiki}->{cgiQuery};
}

=pod

---++ $config->{TWiki}->redirect ( $query, $url )

Redirects the request to $url, via the CGI module object $query unless
overridden by a plugin.  Note that this is currently only called by
Func::redirectCgiQuery() at the request of a plugin!  All of the redirects
done internally by TWiki are not overridable.

=cut

sub redirect
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $query, $url ) = @_;
    if( ! $config->{TWiki}->{Plugins}->redirectCgiQueryHandler ( $query, $url ) ) {
        print $query->redirect( $url );
    }
}


=pod

---++ $config->{TWiki}->getEmailNotifyList ( $config->{TWiki}->{webName}, $config->{TWiki}->{topicName} )
Return value: @emailNotifyList

Get email list from WebNotify page - this now handles entries of the form:
   * Main.UserName 
   * UserName 
   * Main.GroupName
   * GroupName
The 'UserName' format (i.e. no Main webname) is supported in any web, but
is not recommended since this may make future data conversions more
complicated, especially if used outside the Main web.  %<nop>MAINWEB% is OK
instead of 'Main'.  The user's email address(es) are fetched from their
user topic (home page) as long as they are listed in the '* Email:
fred@example.com' format.  Nested groups are supported.

=cut

sub getEmailNotifyList
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $web, $topicname ) = @_;

    $topicname = $config->{TWiki}->{notifyTopicname} unless $topicname;
    return() unless $config->{TWiki}->{Store}->topicExists ( $web, $topicname );

    # Allow %MAINWEB% as well as 'Main' in front of users/groups -
    # non-capturing regex.
    my $mainWebPattern = qr/(?:$config->{TWiki}->{mainWebname}|%MAINWEB%)/;

    my @list = ();
    my %seen;			# Incremented when email address is seen
    foreach ( split ( /\n/, $config->{TWiki}->{Store}->readWebTopic ( $web, $topicname ) ) ) {
        if ( /^\s+\*\s(?:$mainWebPattern\.)?($config->{TWiki}->{regex}{wikiWordRegex})\s+\-\s+($config->{TWiki}->{regex}{emailAddrRegex})/o ) {
	    # Got full form:   * Main.WikiName - email@domain
	    # (the 'Main.' part is optional, non-capturing)
	    if ( $1 ne 'TWikiGuest' ) {
		# Add email address to list if non-guest and non-duplicate
		push (@list, $2) unless $seen{$1}++;
            }
        } elsif ( /^\s+\*\s(?:$mainWebPattern\.)?($config->{TWiki}->{regex}{wikiWordRegex})\s*$/o ) { 
	    # Got short form:   * Main.WikiName
	    # (the 'Main.' part is optional, non-capturing)
            my $userWikiName = $1;
            foreach ( $config->{TWiki}->getEmailOfUser ($userWikiName) ) {
		# Add email address to list if it's not a duplicate
                push (@list, $_) unless $seen{$_}++;
            }
        }
    }
    ##$config->{TWiki}->writeDebug (  "list of emails: @list" );
    return( @list);
}

=pod

---++ $config->{TWiki}->getEmailOfUser ( $config->{TWiki}->{wikiName} )
Return value: ( $userEmail ) or @groupEmailList

Get e-mail address for a given WikiName from the user's home page, or
list of e-mail addresses for a group.  Nested groups are supported.
$config->{TWiki}->{wikiName} must contain _only_ the WikiName; do *not* pass names of the
form "Main.JohnSmith".

=cut

sub getEmailOfUser
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $wikiNameLoc ) = @_;		# WikiName without web prefix

    my @list = ();
    # Ignore guest entry and non-existent pages
    if ( $wikiNameLoc ne "TWikiGuest" && 
		$config->{TWiki}->{Store}->topicExists ( $config->{TWiki}->{mainWebname}, $wikiNameLoc ) ) {
        if ( $wikiNameLoc =~ /Group$/ ) {
            # Page is for a group, get all users in group
	    ##$config->{TWiki}->writeDebug (  "using group: $config->{TWiki}->{mainWebname} . $wikiNameLoc" );
	    my @userList = $config->{TWiki}->{Access}->getUsersOfGroup ( $wikiNameLoc ); 
	    foreach my $user ( @userList ) {
		$user =~ s/^.*\.//;	# Get rid of 'Main.' part.
		foreach my $email ( $config->{TWiki}->getEmailOfUser ($user) ) {
		    push @list, $email;
		}
	    }
        } else {
	    # Page is for a user
	    ##$config->{TWiki}->writeDebug (  "reading home page: $config->{TWiki}->{mainWebname} . $wikiNameLoc" );
            foreach ( split ( /\n/, $config->{TWiki}->{Store}->readWebTopic ( 
					    $config->{TWiki}->{mainWebname}, $wikiNameLoc ) ) ) {
                if (/^\s\*\sEmail:\s+([\w\-\.\+]+\@[\w\-\.\+]+)/) {   
		    # Add email address to list
                    push @list, $1;
                }
            }
        }
    }
    return (@list);
}

=pod

---++ $config->{TWiki}->initializeRemoteUser ( $remoteUser )
Return value: $remoteUser

Acts as a filter for $remoteUser.  If set, $remoteUser is filtered for
insecure characters and untainted.

If $config->{TWiki}->{doRememberRemoteUser} and $remoteUser are both set, it also caches
$remoteUser as belonging to the IP address of the current request.

If $config->{TWiki}->{doRememberRemoteUser} is set and $remoteUser is not, then it sets
$remoteUser to the last authenticated user to make a request with the
current request's IP address, or $config->{TWiki}->{defaultUserName} if no cached name
is available.

If neither are set, then it sets $remoteUser to $config->{TWiki}->{defaultUserName}.

=cut

sub initializeRemoteUser
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theRemoteUser ) = @_;

    my $remoteUser = $theRemoteUser || $config->{TWiki}->{defaultUserName};
    $remoteUser =~ s/$config->{TWiki}->{securityFilter}//go;
    $remoteUser =~ /(.*)/;
    $remoteUser = $1;  # untaint variable

    my $remoteAddr = $ENV{'REMOTE_ADDR'} || "";

    if( $ENV{'REDIRECT_STATUS'} && $ENV{'REDIRECT_STATUS'} eq '401' ) {
        # bail out if authentication failed
        $remoteAddr = "";
    }

    if( ( ! $config->{TWiki}->{doRememberRemoteUser} ) || ( ! $remoteAddr ) ) {
        # do not remember IP address
        return $remoteUser;
    }

    my $text = $config->{TWiki}->{Store}->readFile ( $config->{TWiki}->{remoteUserFilename} );
    # Assume no I18N characters in userids, as for email addresses
    # FIXME: Needs fixing for IPv6?
    my %AddrToName = map { split( /\|/, $_ ) }
                     grep { /^[0-9\.]+\|[A-Za-z0-9]+\|$/ }
                     split( /\n/, $text );

    my $rememberedUser = "";
    if( exists( $AddrToName{ $remoteAddr } ) ) {
        $rememberedUser = $AddrToName{ $remoteAddr };
    }

    if( $theRemoteUser ) {
        if( $theRemoteUser ne $rememberedUser ) {
            $AddrToName{ $remoteAddr } = $theRemoteUser;
            # create file as "$remoteAddr|$theRemoteUser|" lines
            $text = "# This is a generated file, do not modify.\n";
            foreach my $usrAddr ( sort keys %AddrToName ) {
                my $usrName = $AddrToName{ $usrAddr };
                # keep $config->{TWiki}->{userName} unique
                if(  ( $usrName ne $theRemoteUser )
                  || ( $usrAddr eq $remoteAddr ) ) {
                    $text .= "$usrAddr|$usrName|\n";
                }
            }
            $config->{TWiki}->{Store}->saveFile ( $config->{TWiki}->{remoteUserFilename}, $text );
        }
    } else {
        # get user name from AddrToName table
        $remoteUser = $rememberedUser || $config->{TWiki}->{defaultUserName};
    }

    return $remoteUser;
}

=pod

---++ $config->{TWiki}->userToWikiListInit () 

Build hashes to translate in both directions between username (e.g. jsmith) 
and WikiName (e.g. JaneSmith).  Only used for sites where authentication is
managed by external Apache configuration, instead of via TWiki's .htpasswd
mechanism.

=cut

sub userToWikiListInit
{ 
   my $self = shift;
	my $config = $self->{config} ;


    %{$config->{TWiki}->{userToWikiList}} = ();
    %{$config->{TWiki}->{wikiToUserList}} = ();
    my @list = ();
    if( $config->{TWiki}->{doMapUserToWikiName} ) {
        @list = split( /\n/, $config->{TWiki}->{Store}->readFile ( $config->{TWiki}->{userListFilename} ) );
    } else {
        # fix for Codev.SecurityAlertGainAdminRightWithTWikiUsersMapping
        # for .htpasswd authenticated sites ignore user list, but map only guest to TWikiGuest
        @list = ( "\t* TWikiGuest - guest - " ); # CODE_SMELL on localization
    }

    # Get all entries with two '-' characters on same line, i.e.
    # 'WikiName - userid - date created'
    @list = grep { /^\s*\* $config->{TWiki}->{regex}{wikiWordRegex}\s*-\s*[^\-]*-/o } @list;
    my $wUser;
    my $lUser;
    foreach( @list ) {
	# Get the WikiName and userid, and build hashes in both directions
        if(  ( /^\s*\* ($config->{TWiki}->{regex}{wikiWordRegex})\s*\-\s*([^\s]*).*/o ) && $2 ) {
            $wUser = $1;	# WikiName
            $lUser = $2;	# userid
            $lUser =~ s/$config->{TWiki}->{securityFilter}//go;	# FIXME: Should filter in for security...
            $config->{TWiki}->{userToWikiList}{ $lUser } = $wUser;
            $config->{TWiki}->{wikiToUserList}{ $wUser } = $lUser;
        }
    }
}

=pod

---++ $config->{TWiki}->userToWikiName ( $loginUser, $dontAddWeb )
Return value: $config->{TWiki}->{wikiName}

Translates intranet username (e.g. jsmith) to WikiName (e.g. JaneSmith)
userToWikiListInit must be called before this function is used.

Unless $dontAddWeb is set, "Main." is prepended to the returned WikiName.

if you give an invalid username, we just return that (no appending Main. blindy)

SMELL: the userToWikiList cache should really contain the WebName so its possible 
		to have userTopics in more than just the MainWeb (what if you move a user topic?)

=cut

sub userToWikiName
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $loginUser, $dontAddWeb ) = @_;
    
    if( !$loginUser ) {
        return "";
    }

    $loginUser =~ s/$config->{TWiki}->{securityFilter}//go;
    my $wUser = $config->{TWiki}->{userToWikiList}{ $loginUser } || $loginUser;
    if( $dontAddWeb ) {
        return $wUser;
    }
    return "$config->{TWiki}->{mainWebname}.$wUser";
}

=pod

---++ $config->{TWiki}->wikiToUserName ( $config->{TWiki}->{wikiName} )
Return value: $loginUser

Translates WikiName (e.g. JaneSmith) to an intranet username (e.g. jsmith)
userToWikiListInit must be called before this function is used.

=cut

sub wikiToUserName
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $wikiUserLoc ) = @_;
    $wikiUserLoc =~ s/^.*\.//g;
    my $userNameLoc =  $config->{TWiki}->{wikiToUserList}{"$wikiUserLoc"} || $wikiUserLoc;
    ##$config->{TWiki}->writeDebug ( "$config->{TWiki}->wikiToUserName : $wikiUser->$config->{TWiki}->{userName}" );
    return $userNameLoc;
}

=pod

---++ $config->{TWiki}->isGuest () 

Returns whether the current user is TWikiGuest or equivalent.

=cut

sub isGuest
{ 
   my $self = shift;
	my $config = $self->{config} ;


   return ( $config->{TWiki}->{userName} eq $config->{TWiki}->{defaultUserName} );
}

# =========================
=pod

---++ sub $config->{TWiki}->getWikiUserTopic () 

Not yet documented.

=cut

sub getWikiUserTopic
{ 
   my $self = shift;
	my $config = $self->{config} ;


    # Topic without Web name
    return $config->{TWiki}->{wikiName};
}

# =========================
# Check for a valid WikiWord or WikiName
=pod

---++ sub $config->{TWiki}->isWikiName (  $name  )

Not yet documented.
CODE_SMELL - this should be called isWikiWord

=cut

sub isWikiName
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $name ) = @_;

    $name ||= "";	# Default value if undef
    return ( $name =~ m/^$config->{TWiki}->{regex}{wikiWordRegex}$/o )
}

# =========================
# Check for a valid ABBREV (acronym)
=pod

---++ sub $config->{TWiki}->isAbbrev (  $name  )

Not yet documented.

=cut

sub isAbbrev
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $name ) = @_;

    $name ||= "";	# Default value if undef
    return ( $name =~ m/^$config->{TWiki}->{regex}{abbrevRegex}$/o )
}

# =========================
# Check for a valid web name
=pod

---++ sub $config->{TWiki}->isWebName (  $name  )

Not yet documented.

=cut

sub isWebName
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $name ) = @_;

    $name ||= "";	# Default value if undef
    return ( $name =~ m/^$config->{TWiki}->{regex}{webNameRegex}$/o )
}

# =========================
=pod

---++ sub $config->{TWiki}->readOnlyMirrorWeb (  $theWeb  )

Not yet documented.

=cut

sub readOnlyMirrorWeb
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theWeb ) = @_;

    my @mirrorInfo = ( "", "", "", "" );
    if( $config->{TWiki}->{siteWebTopicName} ) {
        my $mirrorSiteName = $config->{TWiki}->{Prefs}->getPreferencesValue ( "MIRRORSITENAME", $theWeb );
        if( $mirrorSiteName && $mirrorSiteName ne $config->{TWiki}->{siteWebTopicName} ) {
            my $mirrorViewURL  = $config->{TWiki}->{Prefs}->getPreferencesValue ( "MIRRORVIEWURL", $theWeb );
            my $mirrorLink = $config->{TWiki}->{Store}->readTemplate ( "mirrorlink" );
            $mirrorLink =~ s/%MIRRORSITENAME%/$mirrorSiteName/g;
            $mirrorLink =~ s/%MIRRORVIEWURL%/$mirrorViewURL/g;
            $mirrorLink =~ s/\s*$//g;
            my $mirrorNote = $config->{TWiki}->{Store}->readTemplate ( "mirrornote" );
            $mirrorNote =~ s/%MIRRORSITENAME%/$mirrorSiteName/g;
            $mirrorNote =~ s/%MIRRORVIEWURL%/$mirrorViewURL/g;
            $mirrorNote = $config->{TWiki}->{Render}->getRenderedVersion ( $mirrorNote, $theWeb );
            $mirrorNote =~ s/\s*$//g;
            @mirrorInfo = ( $mirrorSiteName, $mirrorViewURL, $mirrorLink, $mirrorNote );
        }
    }
    return @mirrorInfo;
}


# =========================
=pod

---++ sub $config->{TWiki}->getDataDir () 

Not yet documented.

=cut

sub getDataDir
{ 
   my $self = shift;
	my $config = $self->{config} ;


    return $config->{TWiki}->{dataDir};
}

# =========================
=pod

---++ sub $config->{TWiki}->getPubDir () 

Not yet documented.

=cut

sub getPubDir
{ 
   my $self = shift;
	my $config = $self->{config} ;


    return $config->{TWiki}->{pubDir};
}

# =========================
=pod

---++ sub $config->{TWiki}->getPubUrlPath () 

Not yet documented.

=cut

sub getPubUrlPath
{ 
   my $self = shift;
	my $config = $self->{config} ;


    return $config->{TWiki}->{pubUrlPath};
}

=pod

---++ $config->{TWiki}->getTWikiLibDir () 

If necessary, finds the full path of the directory containing TWiki.pm,
and sets the variable $config->{TWiki}->{twikiLibDir} so that this process is only performed
once per invocation.  (mod_perl safe: lib dir doesn't change.)

=cut

sub getTWikiLibDir
{ 
   my $self = shift;
	my $config = $self->{config} ;


    return $config->{TWiki}->{libDir};
    if( $config->{TWiki}->{twikiLibDir} ) {
        return $config->{TWiki}->{twikiLibDir};
    }

    # FIXME: Should just use $INC{"TWiki.pm"} to get path used to load this
    # module.
    my $dir = "";
    foreach $dir ( @INC ) {
        if( -e "$dir/TWiki.pm" ) {
            $config->{TWiki}->{twikiLibDir} = $dir;
            last;
        }
    }

    # fix relative path
    if( $config->{TWiki}->{twikiLibDir} =~ /^\./ ) {
        my $curr = cwd();
        $config->{TWiki}->{twikiLibDir} = "$curr/$config->{TWiki}->{twikiLibDir}/";
        # normalize "/../" and "/./"
        while ( $config->{TWiki}->{twikiLibDir} =~ s|([\\/])[^\\/]+[\\/]\.\.[\\/]|$1| ) {};
        $config->{TWiki}->{twikiLibDir} =~ s|([\\/])\.[\\/]|$1|g;
    }
    $config->{TWiki}->{twikiLibDir} =~ s|([\\/])[\\/]*|$1|g; # reduce "//" to "/"
    $config->{TWiki}->{twikiLibDir} =~ s|[\\/]$||;           # cut trailing "/"

    return $config->{TWiki}->{twikiLibDir};
}

# =========================
=pod

---++ sub $config->{TWiki}->revDate2EpSecs () 

Not yet documented.

=cut

sub revDate2EpSecs
# Convert RCS revision date/time to seconds since epoch, for easier sorting 
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $date ) = @_;
    # NOTE: This routine *will break* if input is not one of below formats!
    
    # FIXME - why aren't ifs around pattern match rather than $5 etc
    # try "31 Dec 2001 - 23:59"  (TWiki date)
    if ($date =~ /([0-9]+)\s+([A-Za-z]+)\s+([0-9]+)[\s\-]+([0-9]+)\:([0-9]+)/) {
        my $year = $3;
        $year -= 1900 if( $year > 1900 );
        return timegm( 0, $5, $4, $1, $config->{TWiki}->{mon2num}{$2}, $year );
    }

    # try "2001/12/31 23:59:59" or "2001.12.31.23.59.59" (RCS date)
    if ($date =~ /([0-9]+)[\.\/\-]([0-9]+)[\.\/\-]([0-9]+)[\.\s\-]+([0-9]+)[\.\:]([0-9]+)[\.\:]([0-9]+)/) {
        my $year = $1;
        $year -= 1900 if( $year > 1900 );
        return timegm( $6, $5, $4, $3, $2-1, $year );
    }

    # try "2001/12/31 23:59" or "2001.12.31.23.59" (RCS short date)
    if ($date =~ /([0-9]+)[\.\/\-]([0-9]+)[\.\/\-]([0-9]+)[\.\s\-]+([0-9]+)[\.\:]([0-9]+)/) {
        my $year = $1;
        $year -= 1900 if( $year > 1900 );
        return timegm( 0, $5, $4, $3, $2-1, $year );
    }

    # try "2001-12-31T23:59:59Z" or "2001-12-31T23:59:59+01:00" (ISO date)
    # FIXME: Calc local to zulu time "2001-12-31T23:59:59+01:00"
    if ($date =~ /([0-9]+)\-([0-9]+)\-([0-9]+)T([0-9]+)\:([0-9]+)\:([0-9]+)/ ) {
        my $year = $1;
        $year -= 1900 if( $year > 1900 );
        return timegm( $6, $5, $4, $3, $2-1, $year );
    }

    # try "2001-12-31T23:59Z" or "2001-12-31T23:59+01:00" (ISO short date)
    # FIXME: Calc local to zulu time "2001-12-31T23:59+01:00"
    if ($date =~ /([0-9]+)\-([0-9]+)\-([0-9]+)T([0-9]+)\:([0-9]+)/ ) {
        my $year = $1;
        $year -= 1900 if( $year > 1900 );
        return timegm( 0, $5, $4, $3, $2-1, $year );
    }

    # give up, return start of epoch (01 Jan 1970 GMT)
    return 0;
}

# =========================
=pod

---++ sub $config->{TWiki}->getSessionValue () 

Not yet documented.

=cut

sub getSessionValue
{ 
   my $self = shift;
	my $config = $self->{config} ;


#   my( $key ) = @_;
    return $config->{TWiki}->{Plugins}->getSessionValueHandler ( @_ );
}

# =========================
=pod

---++ sub $config->{TWiki}->setSessionValue () 

Not yet documented.

=cut

sub setSessionValue
{ 
   my $self = shift;
	my $config = $self->{config} ;


#   my( $key, $value ) = @_;
    return $config->{TWiki}->{Plugins}->setSessionValueHandler ( @_ );
}

# =========================
=pod

---++ sub $config->{TWiki}->getSkin () 

Not yet documented.

=cut

sub getSkin
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my $skin = "";
    $skin = $config->{TWiki}->{cgiQuery}->param( 'skin' ) if( $config->{TWiki}->{cgiQuery} );
    $skin = $config->{TWiki}->{Prefs}->getPreferencesValue ( "SKIN" ) unless( $skin );
    return $skin;
}

# =========================
=pod

---++ sub $config->{TWiki}->getViewUrl (  $web, $topic  )

Returns a fully-qualified URL to the specified topic, which must be normalized
into separate specified =$web= and =$topic= parts.

=cut

sub getViewUrl
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theWeb, $theTopic ) = @_;
    # PTh 20 Jun 2000: renamed sub viewUrl to getViewUrl, added $theWeb
    # WM 14 Feb 2004: Removed support for old syntax not specifying $theWeb

    $theTopic =~ s/\s*//gs; # Illegal URL, remove space

    # PTh 24 May 2000: added $config->{TWiki}->{urlHost}, needed for some environments
    # see also Codev.PageRedirectionNotWorking
    return "$config->{TWiki}->{urlHost}$config->{TWiki}->{dispScriptUrlPath}$config->{TWiki}->{dispViewPath}$config->{TWiki}->{scriptSuffix}/$theWeb/$theTopic";
}

=pod

---++ getScriptURL( $web, $topic, $config->{TWiki}->{script} )
Return value: $absoluteScriptURL

Returns the absolute URL to a TWiki script, providing the wub and topic as
"path info" parameters.  The result looks something like this:
"http://host/twiki/bin/$config->{TWiki}->{script}/$web/$topic"

=cut

sub getScriptUrl
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theWeb, $theTopic, $theScript ) = @_;
    
    my $url = "$config->{TWiki}->{urlHost}$config->{TWiki}->{dispScriptUrlPath}/$theScript$config->{TWiki}->{scriptSuffix}/$theWeb/$theTopic";

    # FIXME consider a plugin call here - useful for certificated logon environment
    
    return $url;
}

=pod

---++ $config->{TWiki}->getOopsUrl ( $web, $topic, $template, @scriptParams )
Return Value: $absoluteOopsURL

Composes a URL for an "oops" error page.  The last parameters depend on the
specific oops template in use, and are passed in the URL as 'param1..paramN'.

The returned URL ends up looking something like:
"http://host/twiki/bin/oops/$web/$topic?template=$template&param1=$scriptParams[0]..."

=cut

sub getOopsUrl
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theWeb, $theTopic, $theTemplate,
        $theParam1, $theParam2, $theParam3, $theParam4 ) = @_;
    # PTh 20 Jun 2000: new sub
    my $web = $config->{TWiki}->{webName};  # current web
    if( $theWeb ) {
        $web = $theWeb;
    }
    my $url = "";
    # $config->{TWiki}->{urlHost} is needed, see Codev.PageRedirectionNotWorking
    $url = $config->{TWiki}->getScriptUrl ( $web, $theTopic, "oops" );
    $url .= "\?template=$theTemplate";
    $url .= "\&amp;param1=" . $config->{TWiki}->handleUrlEncode ( $theParam1 ) if ( $theParam1 );
    $url .= "\&amp;param2=" . $config->{TWiki}->handleUrlEncode ( $theParam2 ) if ( $theParam2 );
    $url .= "\&amp;param3=" . $config->{TWiki}->handleUrlEncode ( $theParam3 ) if ( $theParam3 );
    $url .= "\&amp;param4=" . $config->{TWiki}->handleUrlEncode ( $theParam4 ) if ( $theParam4 );

    return $url;
}

# =========================
=pod

---++ sub $config->{TWiki}->makeTopicSummary (  $theText, $theTopic, $theWeb  )

Not yet documented.

=cut

sub makeTopicSummary
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theText, $theTopic, $theWeb ) = @_;
    # called by search, mailnotify & changes after calling readFileHead

    my $htext = $theText;
    # Format e-mail to add spam padding (HTML tags removed later)
    $htext =~ s/([\s\(])(?:mailto\:)*([a-zA-Z0-9\-\_\.\+]+)\@([a-zA-Z0-9\-\_\.]+)\.([a-zA-Z0-9\-\_]+)(?=[\s\.\,\;\:\!\?\)])/$1 . $config->{TWiki}->{Render}->mailtoLink ( $2, $3, $4 )/ge;
    $htext =~ s/<\!\-\-.*?\-\->//gs;  # remove all HTML comments
    $htext =~ s/<\!\-\-.*$//s;        # cut HTML comment
    $htext =~ s/<[^>]*>//g;           # remove all HTML tags
    $htext =~ s/\&[a-z]+;/ /g;        # remove entities
    $htext =~ s/%WEB%/$theWeb/g;      # resolve web
    $htext =~ s/%TOPIC%/$theTopic/g;  # resolve topic
    $htext =~ s/%WIKITOOLNAME%/$config->{TWiki}->{wikiToolName}/g; # resolve TWiki tool name
    $htext =~ s/%META:.*?%//g;        # remove meta data variables
    $htext =~ s/\[\[([^\]]*\]\[|[^\s]*\s)(.*?)\]\]/$2/g; # keep only link text of [[][]]
    $htext =~ s/[\%\[\]\*\|=_\&\<\>]/ /g; # remove Wiki formatting chars & defuse %VARS%
    $htext =~ s/\-\-\-+\+*\s*\!*/ /g; # remove heading formatting
    $htext =~ s/\s+[\+\-]*/ /g;       # remove newlines and special chars

    # FIXME I18N: Avoid splitting within multi-byte characters (e.g. EUC-JP
    # encoding) by encoding bytes as Perl UTF-8 characters in Perl 5.8+. 
    # This avoids splitting within a Unicode codepoint (or a UTF-16
    # surrogate pair, which is encoded as a single Perl UTF-8 character),
    # but we ideally need to avoid splitting closely related Unicode codepoints.
    # Specifically, this means Unicode combining character sequences (e.g.
    # letters and accents) - might be better to split on word boundary if
    # possible.

    # limit to 162 chars 
    $htext =~ s/(.{162})($config->{TWiki}->{regex}{mixedAlphaNumRegex})(.*?)$/$1$2 \.\.\./g;

    # Encode special chars into XML &#nnn; entities for use in RSS feeds
    # - no encoding for HTML pages, to avoid breaking international 
    # characters. FIXME: Only works for ISO-8859-1 characters, where the
    # Unicode encoding (&#nnn;) is identical.
    if( $config->{TWiki}->{pageMode} eq 'rss' ) {
	# FIXME: Issue for EBCDIC/UTF-8
	$htext =~ s/([\x7f-\xff])/"\&\#" . unpack( "C", $1 ) .";"/ge;
    }

    # prevent text from getting rendered in inline search and link tool 
    # tip text by escaping links (external, internal, Interwiki)
    $htext =~ s/([\s\(])(?=\S)/$1<nop>/g;
    $htext =~ s/([\-\*\s])($config->{TWiki}->{regex}{linkProtocolPattern}\:)/$1<nop>$2/go;
    $htext =~ s/@([a-zA-Z0-9\-\_\.]+)/@<nop>$1/g;	# email address

    return $htext;
}

# =========================
=pod

---++ sub $config->{TWiki}->extractParameters (  $str )

Extracts parameters from a variable string and returns a hash with all parameters.
The nameless parameter's key is _DEFAULT.

   * Example variable: %TEST{ "nameless" name1="val1" name2="val2" }%
   * First extract text between {...} to get: "nameless" name1="val1" name2="val2"
   * Then call this on the text:
   * =my %params = $config->{TWiki}->{Func}->extractParameters ( $text );=
   * The hash contains now: <br />
     _DEFAULT => "nameless" <br />
     name1 => "val1" <br />
     name2 => "val2"

=cut

sub extractParameters
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $str ) = @_;

    my %params = ();
    return %params unless defined $str;
    $str =~ s/\\\"/\\$config->{TWiki}->{TranslationToken}/g;  # escape \"

    if( $str =~ s/^\s*\"(.*?)\"\s*(\w+\s*=\s*\"|$)/$2/ ) {
        # is: %VAR{ "value" }%
        # or: %VAR{ "value" param="etc" ... }%
        # Note: "value" may contain embedded double quotes
        $params{"_DEFAULT"} = $1 if defined $1;  # distinguish between "" and "0";
        if( $2 ) {
            while( $str =~ s/^\s*(\w+)\s*=\s*\"([^\"]*)\"// ) {
                $params{"$1"} = $2 if defined $2;
            }
        }
    } elsif( ( $str =~ s/^\s*(\w+)\s*=\s*\"([^\"]*)\"// ) && ( $1 ) ) {
        # is: %VAR{ name = "value" }%
        $params{"$1"} = $2 if defined $2;
        while( $str =~ s/^\s*(\w+)\s*=\s*\"([^\"]*)\"// ) {
            $params{"$1"} = $2 if defined $2;
        }
    } elsif( $str =~ s/^\s*(.*?)\s*$// ) {
        # is: %VAR{ value }%
        $params{"_DEFAULT"} = $1 unless $1 eq "";
    }
    return map{ s/\\$config->{TWiki}->{TranslationToken}/\"/go; $_ } %params;
}

# =========================
=pod

---++ sub $config->{TWiki}->extractNameValuePair (  $str, $name  )

Not yet documented.

=cut

sub extractNameValuePair
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $str, $name ) = @_;

    my $value = "";
    return $value unless( $str );
    $str =~ s/\\\"/\\$config->{TWiki}->{TranslationToken}/g;  # escape \"

    if( $name ) {
        # format is: %VAR{ ... name = "value" }%
        if( $str =~ /(^|[^\S])$name\s*=\s*\"([^\"]*)\"/ ) {
            $value = $2 if defined $2;  # distinguish between "" and "0"
        }

    } else {
        # test if format: { "value" ... }
        if( $str =~ /(^|\=\s*\"[^\"]*\")\s*\"(.*?)\"\s*(\w+\s*=\s*\"|$)/ ) {
            # is: %VAR{ "value" }%
            # or: %VAR{ "value" param="etc" ... }%
            # or: %VAR{ ... = "..." "value" ... }%
            # Note: "value" may contain embedded double quotes
            $value = $2 if defined $2;  # distinguish between "" and "0";

        } elsif( ( $str =~ /^\s*\w+\s*=\s*\"([^\"]*)/ ) && ( $1 ) ) {
            # is: %VAR{ name = "value" }%
            # do nothing, is not a standalone var

        } else {
            # format is: %VAR{ value }%
            $value = $str;
        }
    }
    $value =~ s/\\$config->{TWiki}->{TranslationToken}/\"/go;  # resolve \"
    return $value;
}

# =========================
=pod

---++ sub $config->{TWiki}->fixN (  $theTag  )

Not yet documented.

=cut

sub fixN
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theTag ) = @_;
    $theTag =~ s/[\r\n]+//gs;
    return $theTag;
}

# =========================
=pod

---++ sub $config->{TWiki}->fixURL (  $theHost, $theAbsPath, $theUrl  )

Not yet documented.

=cut

sub fixURL
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theHost, $theAbsPath, $theUrl ) = @_;

    my $url = $theUrl;
    if( $url =~ /^\// ) {
        # fix absolute URL
        $url = "$theHost$url";
    } elsif( $url =~ /^\./ ) {
        # fix relative URL
        $url = "$theHost$theAbsPath/$url";
    } elsif( $url =~ /^$config->{TWiki}->{regex}{linkProtocolPattern}\:/ ) {
        # full qualified URL, do nothing
    } elsif( $url ) {
        # FIXME: is this test enough to detect relative URLs?
        $url = "$theHost$theAbsPath/$url";
    }

    return $url;
}

# =========================
=pod

---++ sub $config->{TWiki}->fixIncludeLink (  $theWeb, $theLink, $theLabel  )

Not yet documented.

=cut

sub fixIncludeLink
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theWeb, $theLink, $theLabel ) = @_;

    if( $theLabel ) {
        # [[...][...]] link
        if( $theLink =~ /^($config->{TWiki}->{regex}{webNameRegex}\.|$config->{TWiki}->{regex}{defaultWebNameRegex}\.|$config->{TWiki}->{regex}{linkProtocolPattern}\:)/ ) {
            return "[[$theLink][$theLabel]]";  # no change
        }
        # add 'Web.' prefix
        return "[[$theWeb.$theLink][$theLabel]]";

    } else {
        # [[...]] link
        if( $theLink =~ /^($config->{TWiki}->{regex}{webNameRegex}\.|$config->{TWiki}->{regex}{defaultWebNameRegex}\.|$config->{TWiki}->{regex}{linkProtocolPattern}\:)/ ) {
            return "[[$theLink]]";  # no change
        }
        # add 'Web.' prefix
        return "[[$theWeb.$theLink][$theLink]]";
    }
}

# =========================
=pod

---++ sub $config->{TWiki}->cleanupIncludedHTML ( $text, $host, $path )

Clean-up HTML text so that it can be shown embedded in a topic

=cut

sub cleanupIncludedHTML
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $text, $host, $path ) = @_;

    # FIXME: Make aware of <base> tag

    $text =~ s/^.*?<\/head>//is;            # remove all HEAD
    $text =~ s/<script.*?<\/script>//gis;   # remove all SCRIPTs
    $text =~ s/^.*?<body[^>]*>//is;         # remove all to <BODY>
    $text =~ s/(?:\n)<\/body>//is;          # remove </BODY>
    $text =~ s/(?:\n)<\/html>//is;          # remove </HTML>
    $text =~ s/(<[^>]*>)/$config->{TWiki}->fixN ($1)/ges;     # join tags to one line each
    $text =~ s/(\s(href|src|action)\=[\"\']?)([^\"\'\>\s]*)/$1 . $config->{TWiki}->fixURL ( $host, $path, $3 )/geois;

    return $text;
}

# =========================
=pod

---++ sub $config->{TWiki}->applyPatternToIncludedText (  $theText, $thePattern )

Apply a pattern on included text to extract a subset

=cut

sub applyPatternToIncludedText
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theText, $thePattern ) = @_;
    $thePattern =~ s/([^\\])([\$\@\%\&\#\'\`\/])/$1\\$2/g;  # escape some special chars
    $thePattern =~ /(.*)/;     # untaint
    $thePattern = $1;
    $theText = "" unless( $theText =~ s/$thePattern/$1/is );
    return $theText;
}

# =========================
=pod

---++ sub $config->{TWiki}->handleIncludeUrl (  $theUrl, $thePattern )

Not yet documented.

=cut

sub handleIncludeUrl
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theUrl, $thePattern, $theWeb, $theTopic ) = @_;
    my $text = "";
    my $host = "";
    my $port = 80;
    my $path = "";
    my $user = "";
    my $pass = "";

    # For speed, read file directly if URL matches an attachment directory
    if( $theUrl =~ /^$config->{TWiki}->{urlHost}$config->{TWiki}->{pubUrlPath}\/([^\/\.]+)\/([^\/\.]+)\/([^\/]+)$/ ) {
        my $web = $1;
        my $topic = $2;
        my $fileName = "$config->{TWiki}->{pubDir}/$web/$topic/$3";
        if( $fileName =~ m/\.(txt|html?)$/i ) {       # FIXME: Check for MIME type, not file suffix
            unless( -e $fileName ) {
                return $config->{TWiki}->showError ( "Error: File attachment at $theUrl does not exist" );
            }
            if( "$web.$topic" ne "$theWeb.$theTopic" ) {
                # CODE_SMELL: Does not account for not yet authenticated user
                unless( $config->{TWiki}->{Access}->checkAccessPermission ( "VIEW", $config->{TWiki}->{wikiUserName}, "", $topic, $web ) ) {
                    return $config->{TWiki}->showError ( "Error: No permission to view files attached to $web.$topic" );
                }
            }
            $text = $config->{TWiki}->{Store}->readFile ( $fileName );
            $text = $config->{TWiki}->cleanupIncludedHTML ( $text, $config->{TWiki}->{urlHost}, $config->{TWiki}->{pubUrlPath} );
            $text = $config->{TWiki}->applyPatternToIncludedText ( $text, $thePattern ) if( $thePattern );
            return $text;
        }
        # fall through; try to include file over http based on MIME setting
    }

    # RNF 22 Jan 2002 Handle http://user:pass@host
    if( $theUrl =~ /http\:\/\/(.+)\:(.+)\@([^\:]+)\:([0-9]+)(\/.*)/ ) {
        $user = $1;
        $pass = $2;
        $host = $3;
        $port = $4;
        $path = $5;

    } elsif( $theUrl =~ /http\:\/\/(.+)\:(.+)\@([^\/]+)(\/.*)/ ) {
        $user = $1;
        $pass = $2;
        $host = $3;
        $path = $4;

    } elsif( $theUrl =~ /http\:\/\/([^\:]+)\:([0-9]+)(\/.*)/ ) {
        $host = $1;
        $port = $2;
        $path = $3;

    } elsif( $theUrl =~ /http\:\/\/([^\/]+)(\/.*)/ ) {
        $host = $1;
        $path = $2;

    } else {
        $text = $config->{TWiki}->showError ( "Error: Unsupported protocol. (Must be 'http://domain/...')" );
        return $text;
    }

    $text = $config->{TWiki}->{Net}->getUrl ( $host, $port, $path, $user, $pass );
    $text =~ s/\r\n/\n/gs;
    $text =~ s/\r/\n/gs;
    $text =~ s/^(.*?\n)\n(.*)/$2/s;
    my $httpHeader = $1;
    my $contentType = "";
    if( $httpHeader =~ /content\-type\:\s*([^\n]*)/ois ) {
        $contentType = $1;
    }
    if( $contentType =~ /^text\/html/ ) {
        $path =~ s/(.*)\/.*/$1/; # build path for relative address
        $host = "http://$host";   # build host for absolute address
        if( $port != 80 ) {
            $host .= ":$port";
        }
        $text = $config->{TWiki}->cleanupIncludedHTML ( $text, $host, $path );

    } elsif( $contentType =~ /^text\/(plain|css)/ ) {
        # do nothing

    } else {
        $text = $config->{TWiki}->showError ( "Error: Unsupported content type: $contentType."
              . " (Must be text/html, text/plain or text/css)" );
    }

    $text = $config->{TWiki}->applyPatternToIncludedText ( $text, $thePattern ) if( $thePattern );

    return $text;
}

=pod

---++ $config->{TWiki}->handleIncludeFile ( $includeCommandAttribs, $topic, $web, \@verbatimBuffer, @processedTopics )
Return value: $includedText

Processes a specific instance %<nop>INCLUDE{...}% syntax.  Returns the text to be
inserted in place of the INCLUDE command.  $topic and $web should be for the
immediate parent topic in the include hierarchy. @verbatimBuffer is the request-
global buffer for storing removed verbatim blocks, and @processedTopics is a
list of topics already %<nop>INCLUDE%'ed -- these are not allowed to be included
again to prevent infinte recursive inclusion.

=cut

sub handleIncludeFile
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theAttributes, $theTopic, $theWeb, $verbatim, @theProcessedTopics ) = @_;
    my $incfile = $config->{TWiki}->extractNameValuePair ( $theAttributes );
    my $pattern = $config->{TWiki}->extractNameValuePair ( $theAttributes, "pattern" );
    my $rev     = $config->{TWiki}->extractNameValuePair ( $theAttributes, "rev" );
    my $warn    = $config->{TWiki}->extractNameValuePair ( $theAttributes, "warn" );

    if( $incfile =~ /^http\:/ ) {
        # include web page
        return $config->{TWiki}->handleIncludeUrl ( $incfile, $pattern, $theWeb, $theTopic );
    }

    # CrisBailiff, PeterThoeny 12 Jun 2000: Add security
    $incfile =~ s/$config->{TWiki}->{securityFilter}//go;    # zap anything suspicious
    if( $config->{TWiki}->{doSecureInclude} ) {
        # Filter out ".." from filename, this is to
        # prevent includes of "../../file"
        $incfile =~ s/\.+/\./g;
    } else {
        # danger, could include .htpasswd with relative path
        $incfile =~ s/passwd//gi;    # filter out passwd filename
    }

    my $text = "";
    my $meta = "";
    my $isTopic = 0;

    # test for different topic name and file name patterns
    my $fileName = "";
    TRY: {
        # check for topic
        $fileName = "$config->{TWiki}->{dataDir}/$theWeb/$incfile.txt";      # TopicName
        last TRY if( -e $fileName );
        my $incwebfile = $incfile;
        $incwebfile =~ s/\.([^\.]*)$/\/$1/;
        $fileName = "$config->{TWiki}->{dataDir}/$incwebfile.txt";           # Web.TopicName
        last TRY if( -e $fileName );
        $fileName = "$config->{TWiki}->{dataDir}/$theWeb/$incfile";          # TopicName.txt
        last TRY if( -e $fileName );
        $fileName = "$config->{TWiki}->{dataDir}/$incfile";                  # Web/TopicName.txt
        last TRY if( -e $fileName );

        # give up, file not found
        $warn = $config->{TWiki}->{Prefs}->getPreferencesValue ( "INCLUDEWARNING" ) unless( $warn );
        if( $warn =~ /^on$/i ) {
            return $config->{TWiki}->showError ( "Warning: Can't INCLUDE <nop>$incfile, topic not found" );
        } elsif( $warn && $warn !~ /^(off|no)$/i ) {
            $incfile =~ s/\//\./go;
            $warn =~ s/\$topic/$incfile/go;
            return $warn;
        } # else fail silently
        return "";
    }

    # prevent recursive loop
    if( ( @theProcessedTopics ) && ( grep { /^$fileName$/ } @theProcessedTopics ) ) {
        # file already included
        if( $warn || $config->{TWiki}->{Prefs}->getPreferencesFlag ( "INCLUDEWARNING" ) ) {
            unless( $warn =~ /^(off|no)$/i ) {
                return $config->{TWiki}->showError ( "Warning: Can't INCLUDE <nop>$incfile twice, topic is already included" );
            }
        }
        return "";
    } else {
        # remember for next time
        push( @theProcessedTopics, $fileName );
    }

    # set include web/filenames and current web/filenames
    $config->{TWiki}->{includingWebName} = $theWeb;
    $config->{TWiki}->{includingTopicName} = $theTopic;
    if( $fileName =~ s/\/([^\/]*)\/([^\/]*)\.txt$/$1/ ) {
        # identified "/Web/TopicName.txt" filename, e.g. a Wiki topic
        # so save the current web and topic name
        $theWeb = $1;
        $theTopic = $2;
        $isTopic = 1;

        if( $rev ) {
            $rev = "1.$rev" unless( $rev =~ /^1\./ );
            ( $meta, $text ) = $config->{TWiki}->{Store}->readTopicVersion ( $theWeb, $theTopic, $rev );
        } else {
            ( $meta, $text ) = $config->{TWiki}->{Store}->readTopic ( $theWeb, $theTopic );
        }
        # remove everything before %STARTINCLUDE% and after %STOPINCLUDE%
        $text =~ s/.*?%STARTINCLUDE%//s;
        $text =~ s/%STOPINCLUDE%.*//s;

    } # else is a file with relative path, e.g. $config->{TWiki}->{dataDir}/../../path/to/non-twiki/file.ext

    $text = $config->{TWiki}->applyPatternToIncludedText ( $text, $pattern ) if( $pattern );

    # handle all preferences and internal tags (for speed: call by reference)
    $text = $config->{TWiki}->takeOutVerbatim ( $text, $verbatim );

    # Escape rendering: Change " !%VARIABLE%" to " %<nop>VARIABLE%", for final " %VARIABLE%" output
    $text =~ s/(\s)\!\%([A-Z])/$1%<nop>$2/g;

    # handle all preferences and internal tags
    $config->{TWiki}->{Prefs}->handlePreferencesTags ( $text );
    $config->{TWiki}->handleInternalTags ( $text, $theTopic, $theWeb );

    # TWiki Plugin Hook (4th parameter tells plugin that its called from an include)
    $config->{TWiki}->{Plugins}->commonTagsHandler ( $text, $theTopic, $theWeb, 1 );

    # handle tags again because of plugin hook
    $config->{TWiki}->{Prefs}->handlePreferencesTags ( $text );
    $config->{TWiki}->handleInternalTags ( $text, $theTopic, $theWeb );

    # If needed, fix all "TopicNames" to "Web.TopicNames" to get the right context
    if( ( $isTopic ) && ( $theWeb ne $config->{TWiki}->{webName} ) ) {
        # "TopicName" to "Web.TopicName"
        $text =~ s/(^|[\s\(])($config->{TWiki}->{regex}{webNameRegex}\.$config->{TWiki}->{regex}{wikiWordRegex})/$1$config->{TWiki}->{TranslationToken}$2/go;
        $text =~ s/(^|[\s\(])($config->{TWiki}->{regex}{wikiWordRegex})/$1$theWeb\.$2/go;
        $text =~ s/(^|[\s\(])$config->{TWiki}->{TranslationToken}/$1/go;
        # "[[TopicName]]" to "[[Web.TopicName][TopicName]]"
        $text =~ s/\[\[([^\]]+)\]\]/$config->{TWiki}->fixIncludeLink ( $theWeb, $1 )/geo;
        # "[[TopicName][...]]" to "[[Web.TopicName][...]]"
        $text =~ s/\[\[([^\]]+)\]\[([^\]]+)\]\]/$config->{TWiki}->fixIncludeLink ( $theWeb, $1, $2 )/geo;
        # FIXME: Support for <noautolink>
    }
    
    # FIXME What about attachments?

    # recursively process multiple embedded %INCLUDE% statements and prefs
    $text =~ s/%INCLUDE{(.*?)}%/$config->{TWiki}->handleIncludeFile ($1, $theTopic, $theWeb, $verbatim, @theProcessedTopics )/ge;

    return $text;
}

# =========================
# Only does simple search for topicmoved at present, can be expanded when required
=pod

---++ sub $config->{TWiki}->handleMetaSearch (  $attributes  )

Not yet documented.

=cut

sub handleMetaSearch
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $attributes ) = @_;
    
    my $attrWeb           = $config->{TWiki}->extractNameValuePair ( $attributes, "web" );
    my $attrTopic         = $config->{TWiki}->extractNameValuePair ( $attributes, "topic" );
    my $attrType          = $config->{TWiki}->extractNameValuePair ( $attributes, "type" );
    my $attrTitle         = $config->{TWiki}->extractNameValuePair ( $attributes, "title" );
    my $attrDefault       = $config->{TWiki}->extractNameValuePair ( $attributes, "default" );

    my $searchVal = "XXX";
    
    if( ! $attrType ) {
       $attrType = "";
    }

    my $searchWeb = "all";
    
    if( $attrType eq "topicmoved" ) {
       $searchVal = "%META:TOPICMOVED[{].*from=\\\"$attrWeb\.$attrTopic\\\".*[}]%";
    } elsif ( $attrType eq "parent" ) {
       $searchWeb = $attrWeb;
       $searchVal = "%META:TOPICPARENT[{].*name=\\\"($attrWeb\\.)?$attrTopic\\\".*[}]%";
    }

    my $text = $config->{TWiki}->{Search}->searchWeb (
        "inline"        => "1",
        "search"        => $searchVal,
        "web"           => $searchWeb,
        "type"          => "regex",
        "nosummary"     => "on",
        "nosearch"      => "on",
        "noheader"      => "on",
        "nototal"       => "on",
        "noempty"       => "on",
        "template"      => "searchmeta",
    );

    if( $text =~ /^\s*$/ ) {
       $text = "$attrTitle$attrDefault";
    } else {
       $text = "$attrTitle$text";
    }
    return $text;
}

# =========================
=pod

---++ sub $config->{TWiki}->handleSearchWeb ( $attributes, $baseWeb, $baseTopic )

Not yet documented.

=cut

sub handleSearchWeb
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $attributes, $baseWeb, $baseTopic ) = @_;

    return $config->{TWiki}->{Search}->searchWeb (
        "inline"        => "1",
        "baseweb"       => $baseWeb,
        "basetopic"     => $baseTopic,
        "search"        => $config->{TWiki}->extractNameValuePair ( $attributes ) || $config->{TWiki}->extractNameValuePair ( $attributes, "search" ),
        "web"           => $config->{TWiki}->extractNameValuePair ( $attributes, "web" ),
        "topic"         => $config->{TWiki}->extractNameValuePair ( $attributes, "topic" ),
        "excludetopic"  => $config->{TWiki}->extractNameValuePair ( $attributes, "excludetopic" ),
        "scope"         => $config->{TWiki}->extractNameValuePair ( $attributes, "scope" ),
        "order"         => $config->{TWiki}->extractNameValuePair ( $attributes, "order" ),
        "type"          => $config->{TWiki}->extractNameValuePair ( $attributes, "type" )
                        || $config->{TWiki}->{Prefs}->getPreferencesValue ( "SEARCHVARDEFAULTTYPE" ),
        "regex"         => $config->{TWiki}->extractNameValuePair ( $attributes, "regex" ),
        "limit"         => $config->{TWiki}->extractNameValuePair ( $attributes, "limit" ),
        "reverse"       => $config->{TWiki}->extractNameValuePair ( $attributes, "reverse" ),
        "casesensitive" => $config->{TWiki}->extractNameValuePair ( $attributes, "casesensitive" ),
        "nosummary"     => $config->{TWiki}->extractNameValuePair ( $attributes, "nosummary" ),
        "nosearch"      => $config->{TWiki}->extractNameValuePair ( $attributes, "nosearch" ),
        "noheader"      => $config->{TWiki}->extractNameValuePair ( $attributes, "noheader" ),
        "nototal"       => $config->{TWiki}->extractNameValuePair ( $attributes, "nototal" ),
        "bookview"      => $config->{TWiki}->extractNameValuePair ( $attributes, "bookview" ),
        "renameview"    => $config->{TWiki}->extractNameValuePair ( $attributes, "renameview" ),
        "showlock"      => $config->{TWiki}->extractNameValuePair ( $attributes, "showlock" ),
        "expandvariables" => $config->{TWiki}->extractNameValuePair ( $attributes, "expandvariables" ),
        "noempty"       => $config->{TWiki}->extractNameValuePair ( $attributes, "noempty" ),
        "template"      => $config->{TWiki}->extractNameValuePair ( $attributes, "template" ),
        "header"        => $config->{TWiki}->extractNameValuePair ( $attributes, "header" ),
        "format"        => $config->{TWiki}->extractNameValuePair ( $attributes, "format" ),
        "multiple"      => $config->{TWiki}->extractNameValuePair ( $attributes, "multiple" ),
        "separator"     => $config->{TWiki}->extractNameValuePair ( $attributes, "separator" ),
    );
}

# =========================
#TODO: this seems like a duplication with formatGmTime and formatLocTime
#remove any 2.
=pod

---++ sub $config->{TWiki}->handleTime (  $theAttributes, $theZone  )

Not yet documented.

=cut

sub handleTime
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theAttributes, $theZone ) = @_;
    # format examples:
    #   28 Jul 2000 15:33:59 is "$day $month $year $hour:$min:$sec"
    #   001128               is "$ye$mo$day"

    my $format = $config->{TWiki}->extractNameValuePair ( $theAttributes );

    my $value = "";
    my $time = time();

#    if( $format ) {
        $value = $config->{TWiki}->formatTime ($time, $format, $theZone);
 #   } else {
 #       if( $theZone eq "gmtime" ) {
 #           $value = gmtime( $time );
 #       } elsif( $theZone eq "servertime" ) {
 #           $value = localtime( $time );
 #       }
 #   }

#    if( $theZone eq "gmtime" ) {
#		$value = $value." GMT";
#	}

    return $value;
}

# =========================
=pod
---++ sub $config->{TWiki}->formatTime ($epochSeconds, $formatString, $outputTimeZone) ==> $value
| $epochSeconds | epochSecs GMT |
| $formatString | twiki time date format |
| $outputTimeZone | timezone to display. (not sure this will work)(gmtime or servertime) |

=cut
sub formatTime 
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my ($epochSeconds, $formatString, $outputTimeZone) = @_;
    my $value = $epochSeconds;

    # use default TWiki format "31 Dec 1999 - 23:59" unless specified
    $formatString = "\$day \$month \$year - \$hour:\$min" unless( $formatString );
    $outputTimeZone = $config->{TWiki}->{displayTimeValues} unless( $outputTimeZone );

    my( $sec, $min, $hour, $day, $mon, $year, $wday) = gmtime( $epochSeconds );
      ( $sec, $min, $hour, $day, $mon, $year, $wday ) = localtime( $epochSeconds ) if( $outputTimeZone eq "servertime" );

    #standard twiki date time formats
    if( $formatString =~ /rcs/i ) {
        # RCS format, example: "2001/12/31 23:59:59"
        $formatString = "\$year/\$mo/\$day \$hour:\$min:\$sec";
    } elsif ( $formatString =~ /http|email/i ) {
        # HTTP header format, e.g. "Thu, 23 Jul 1998 07:21:56 EST"
 	    # - based on RFC 2616/1123 and HTTP::Date; also used
        # by TWiki::Net for Date header in emails.
        $formatString = "\$wday, \$day \$month \$year \$hour:\$min:\$sec \$tz";
    } elsif ( $formatString =~ /iso/i ) {
        # ISO Format, see spec at http://www.w3.org/TR/NOTE-datetime
        # e.g. "2002-12-31T19:30Z"
        $formatString = "\$year-\$mo-\$dayT\$hour:\$min";
        if( $outputTimeZone eq "gmtime" ) {
            $formatString = $formatString."Z";
        } else {
            #TODO:            $formatString = $formatString.  # TZD  = time zone designator (Z or +hh:mm or -hh:mm) 
        }
    } 
    
    $value = $formatString;
    $value =~ s/\$sec[o]?[n]?[d]?[s]?/sprintf("%.2u",$sec)/geoi;
    $value =~ s/\$min[u]?[t]?[e]?[s]?/sprintf("%.2u",$min)/geoi;
    $value =~ s/\$hou[r]?[s]?/sprintf("%.2u",$hour)/geoi;
    $value =~ s/\$day/sprintf("%.2u",$day)/geoi;
#    my @{$config->{TWiki}->{weekDay}} = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    $value =~ s/\$wday/$config->{TWiki}->{weekDay}[$wday]/geoi;
    $value =~ s/\$mon[t]?[h]?/$config->{TWiki}->{isoMonth}[$mon]/goi;
    $value =~ s/\$mo/sprintf("%.2u",$mon+1)/geoi;
    $value =~ s/\$yea[r]?/sprintf("%.4u",$year+1900)/geoi;
    $value =~ s/\$ye/sprintf("%.2u",$year%100)/geoi;
        
#TODO: how do we get the different timezone strings (and when we add usertime, then what?)    
    my $tz_str = "GMT";
    $tz_str = "Local" if ( $outputTimeZone eq "servertime" );
    $value =~ s/\$tz/$tz_str/geoi;
 
    return $value;        
}

# =========================
=pod
---++ sub $config->{TWiki}->handleRevisionInfo ( $web, $topic, $formatString ) ==> $value
| $web | web and  |
| $topic | topic to display the name for |
| $formatString | twiki format string (like in search) |

=cut
sub handleRevisionInfo 
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theWeb, $theTopic, $theArgs ) = @_;

    my $format = $config->{TWiki}->extractNameValuePair ( $theArgs ) || $config->{TWiki}->extractNameValuePair ( $theArgs, "format" )
                 || "r1.\$rev - \$date - \$wikiusername";
    my $web    = $config->{TWiki}->extractNameValuePair ( $theArgs, "web" ) || $theWeb;
    my $topic  = $config->{TWiki}->extractNameValuePair ( $theArgs, "topic" ) || $theTopic;
    my $cgiQueryLoc = $config->{TWiki}->getCgiQuery () ;
    my $cgiRev = "";
    $cgiRev = $cgiQueryLoc->param('rev') if( $cgiQueryLoc );
    my $revnum = $cgiRev || $config->{TWiki}->extractNameValuePair ( $theArgs, "rev" ) || "";

    my( $date, $user, $rev, $comment ) = $config->{TWiki}->{Store}->getRevisionInfo ( $web, $topic, $revnum );
    my $wikiNameLoc     = $config->{TWiki}->userToWikiName ( $user, 1 );
    my $wikiUserNameLoc = $config->{TWiki}->userToWikiName ( $user );

    my $value = $format;
    $value =~ s/\$web/$web/goi;
    $value =~ s/\$topic/$topic/goi;
    $value =~ s/\$rev/$rev/goi;
    $value =~ s/\$date/$config->{TWiki}->formatTime ($date)/geoi;
    $value =~ s/\$comment/$comment/goi;
    $value =~ s/\$username/$user/goi;
    $value =~ s/\$wikiname/$wikiNameLoc/goi;
    $value =~ s/\$wikiusername/$wikiUserNameLoc/goi;
 
    return $value;        
}

#AS
# =========================
=pod

---++ sub $config->{TWiki}->showError (  $errormessage  )

Not yet documented.

=cut

sub showError
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $errormessage ) = @_;
    return "<font size=\"-1\" class=\"twikiAlert\" color=\"#FF0000\">$errormessage</font>" ;
}

=pod

---++ $config->{TWiki}->handleToc ( $text, $topic, $web, $tocAttributes )
Parameters:
   * $text          : the text of the current topic
   * $topic         : the topic we are in
   * $web           : the web we are in
   * $tocAttributes : "Topic" [web="Web"] [depth="N"]
Return value: $tableOfContents

Andrea Sterbini 22-08-00 / PTh 28 Feb 2001

Handles %<nop>TOC{...}% syntax.  Creates a table of contents using TWiki bulleted
list markup, linked to the section headings of a topic. A section heading is
entered in one of the following forms:
   * $headingPatternSp : \t++... spaces section heading
   * $headingPatternDa : ---++... dashes section heading
   * $headingPatternHt : &lt;h[1-6]> HTML section heading &lt;/h[1-6]>

=cut

sub handleToc
{ 
   my $self = shift;
	my $config = $self->{config} ;


    ##     $_[0]     $_[1]      $_[2]    $_[3]
    ## my( $theText, $theTopic, $theWeb, $attributes ) = @_;

    # get the topic name attribute
    my $topicname = $config->{TWiki}->extractNameValuePair ( $_[3] )  || $_[1];

    # get the web name attribute
    my $web = $config->{TWiki}->extractNameValuePair ( $_[3], "web" ) || $_[2];
    $web =~ s/\//\./g;
    my $webPath = $web;
    $webPath =~ s/\./\//g;

    # get the depth limit attribute
    my $depth = $config->{TWiki}->extractNameValuePair ( $_[3], "depth" ) || 6;

    #get the title attribute
    my $title = $config->{TWiki}->extractNameValuePair ( $_[3], "title" ) || "";
    $title = "\n<span class=\"twikiTocTitle\">$title</span>" if( $title );

    my $result  = "";
    my $line  = "";
    my $level = "";
    my @list  = ();

    if( "$web.$topicname" eq "$_[2].$_[1]" ) {
        # use text from parameter
        @list = split( /\n/, $_[0] );

    } else {
        # read text from file
        if ( ! $config->{TWiki}->{Store}->topicExists ( $web, $topicname ) ) {
            return $config->{TWiki}->showError ( "TOC: Cannot find topic \"$web.$topicname\"" );
        }
        my $t = $config->{TWiki}->{Store}->readWebTopic ( $web, $topicname );
        $t =~ s/.*?%STARTINCLUDE%//s;
        $t =~ s/%STOPINCLUDE%.*//s;
        @list = split( /\n/, $config->{TWiki}->handleCommonTags ( $t, $topicname, $web ) );
    }

    @list = grep { /(<\/?pre>)|($config->{TWiki}->{regex}{headerPatternDa})|($config->{TWiki}->{regex}{headerPatternSp})|($config->{TWiki}->{regex}{headerPatternHt})/ } @list;
    my $insidePre = 0;
    my $i = 0;
    my $tabs = "";
    my $anchor = "";
    my $highest = 99;
    foreach $line ( @list ) {
        if( $line =~ /^.*<pre>.*$/io ) {
            $insidePre = 1;
            $line = "";
        }
        if( $line =~ /^.*<\/pre>.*$/io ) {
            $insidePre = 0;
            $line = "";
        }
        if (!$insidePre) {
            $level = $line ;
            if ( $line =~  /$config->{TWiki}->{regex}{headerPatternDa}/o ) {
                $level =~ s/$config->{TWiki}->{regex}{headerPatternDa}/$1/go;
                $level = length $level;
                $line  =~ s/$config->{TWiki}->{regex}{headerPatternDa}/$2/go;
            } elsif
               ( $line =~  /$config->{TWiki}->{regex}{headerPatternSp}/o ) {
                $level =~ s/$config->{TWiki}->{regex}{headerPatternSp}/$1/go;
                $level = length $level;
                $line  =~ s/$config->{TWiki}->{regex}{headerPatternSp}/$2/go;
            } elsif
               ( $line =~  /$config->{TWiki}->{regex}{headerPatternHt}/io ) {
                $level =~ s/$config->{TWiki}->{regex}{headerPatternHt}/$1/gio;
                $line  =~ s/$config->{TWiki}->{regex}{headerPatternHt}/$2/gio;
            }
            my $urlPath = "";
            if( "$web.$topicname" ne "$config->{TWiki}->{webName}.$config->{TWiki}->{topicName}" ) {
                # not current topic, can't omit URL
                $urlPath = "$config->{TWiki}->{dispScriptUrlPath}$config->{TWiki}->{dispViewPath}$config->{TWiki}->{scriptSuffix}/$webPath/$topicname";
            }
            if( ( $line ) && ( $level <= $depth ) ) {
                $anchor = $config->{TWiki}->{Render}->makeAnchorName ( $line );
                # cut TOC exclude '---+ heading !! exclude'
                $line  =~ s/\s*$config->{TWiki}->{regex}{headerPatternNoTOC}.+$//go;
                $line  =~ s/[\n\r]//go;
                next unless $line;
                $highest = $level if( $level < $highest );
                $tabs = "";
                for( $i=0 ; $i<$level ; $i++ ) {
                    $tabs = "\t$tabs";
                }
                # Remove *bold*, _italic_ and =fixed= formatting
                $line =~ s/(^|[\s\(])\*([^\s]+?|[^\s].*?[^\s])\*($|[\s\,\.\;\:\!\?\)])/$1$2$3/g;
                $line =~ s/(^|[\s\(])_+([^\s]+?|[^\s].*?[^\s])_+($|[\s\,\.\;\:\!\?\)])/$1$2$3/g;
                $line =~ s/(^|[\s\(])=+([^\s]+?|[^\s].*?[^\s])=+($|[\s\,\.\;\:\!\?\)])/$1$2$3/g;
                # Prevent WikiLinks
                $line =~ s/\[\[.*?\]\[(.*?)\]\]/$1/g;  # '[[...][...]]'
                $line =~ s/\[\[(.*?)\]\]/$1/ge;        # '[[...]]'
                $line =~ s/([\s\(])($config->{TWiki}->{regex}{webNameRegex})\.($config->{TWiki}->{regex}{wikiWordRegex})/$1<nop>$3/g;  # 'Web.TopicName'
                $line =~ s/([\s\(])($config->{TWiki}->{regex}{wikiWordRegex})/$1<nop>$2/g;  # 'TopicName'
                $line =~ s/([\s\(])($config->{TWiki}->{regex}{abbrevRegex})/$1<nop>$2/g;    # 'TLA'
                # create linked bullet item, using a relative link to anchor
                $line = "$tabs* <a href=\"$urlPath#$anchor\">$line</a>";
                $result .= "\n$line";
            }
        }
    }
    if( $result ) {
        if( $highest > 1 ) {
            # left shift TOC
            $highest--;
            $result =~ s/^\t{$highest}//gm;
        }
        $result = "<div class=\"twikiToc\">$title$result\n</div>";
        return $result;

    } else {
        return $config->{TWiki}->showError ("TOC: No TOC in \"$web.$topicname\"");
    }
}

# =========================
=pod

---++ sub $config->{TWiki}->getPublicWebList () 

Not yet documented.

=cut

sub getPublicWebList
{ 
   my $self = shift;
	my $config = $self->{config} ;


    # FIXME: Should this go elsewhere?
    # (Not in Store because Store should not be dependent on Prefs.)

    if( ! @{$config->{TWiki}->{publicWebList}} ) {
        # build public web list, e.g. exclude hidden webs, but include current web
        my @list = $config->{TWiki}->{Store}->getAllWebs ( "" );
        my $item = "";
        my $hidden = "";
        foreach $item ( @list ) {
            $hidden = $config->{TWiki}->{Prefs}->getPreferencesValue ( "NOSEARCHALL", $item );
            # exclude topics that are hidden or start with . or _ unless current web
            if( ( $item eq $config->{TWiki}->{webName}  ) || ( ( ! $hidden ) && ( $item =~ /^[^\.\_]/ ) ) ) {
                push( @{$config->{TWiki}->{publicWebList}}, $item );
            }
        }
    }
    return @{$config->{TWiki}->{publicWebList}};
}

# =========================
=pod

---++ sub $config->{TWiki}->expandVariablesOnTopicCreation ( $theText, $theUser, $theWikiName, $theWikiUserName )

Expand limited set of variables with a topic during topic creation

=cut

sub expandVariablesOnTopicCreation { 
   my $self = shift;
	my $config = $self->{config} ;


  my ( $theText, $theUser, $theWikiName, $theWikiUserName ) = @_;

  my $today = $config->{TWiki}->formatTime (time(), "\$day \$mon \$year", "gmtime");
  $theUser         = $config->{TWiki}->{userName}                     unless $theUser;
  $theWikiName     = $config->{TWiki}->userToWikiName ( $theUser, 1 ) unless $theWikiName;
  $theWikiUserName = $config->{TWiki}->userToWikiName ( $theUser )    unless $theWikiUserName;

  $theText =~ s/%DATE%/$today/go;
  $theText =~ s/%USERNAME%/$theUser/go;                     # "jdoe"
  $theText =~ s/%WIKINAME%/$theWikiName/go;                 # "JonDoe"
  $theText =~ s/%WIKIUSERNAME%/$theWikiUserName/go;         # "Main.JonDoe"
  $theText =~ s/%URLPARAM{(.*?)}%/$config->{TWiki}->handleUrlParam ($1)/geo;  # expand URL parameters
  $theText =~ s/%NOP{.*?}%//gos;  # Remove filler: Use it to remove access control at time of
  $theText =~ s/%NOP%//go;        # topic instantiation or to prevent search from hitting a template

  return $theText;
}

# =========================
=pod

---++ sub $config->{TWiki}->handleWebAndTopicList (  $theAttr, $isWeb  )

Not yet documented.

=cut

sub handleWebAndTopicList
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theAttr, $isWeb ) = @_;

    my $format = $config->{TWiki}->extractNameValuePair ( $theAttr ) || $config->{TWiki}->extractNameValuePair ( $theAttr, "format" );
    $format .= '$name' unless( $format =~ /\$name/ );
    my $separator = $config->{TWiki}->extractNameValuePair ( $theAttr, "separator" ) || "\n";
    my $web = $config->{TWiki}->extractNameValuePair ( $theAttr, "web" ) || "";
    my $webs = $config->{TWiki}->extractNameValuePair ( $theAttr, "webs" ) || "public";
    my $selection = $config->{TWiki}->extractNameValuePair ( $theAttr, "selection" ) || "";
    $selection =~ s/\,/ /g;
    $selection = " $selection ";
    my $marker    = $config->{TWiki}->extractNameValuePair ( $theAttr, "marker" ) || 'selected="selected"';

    my @list = ();
    if( $isWeb ) {
        my @webslist = split( /,\s?/, $webs );
        foreach my $aweb ( @webslist ) {
            if( $aweb eq "public" ) {
                push( @list, $config->{TWiki}->getPublicWebList ()  );
            } elsif( $aweb eq "webtemplate" ) {
                push( @list, grep { /^\_/o } $config->{TWiki}->{Store}->getAllWebs ( "" ) );
            } else{
                push( @list, $aweb ) if( $config->{TWiki}->{Store}->webExists ( $aweb ) );
            }
        }
    } else {
        $web = $config->{TWiki}->{webName} if( ! $web );
        my $hidden = $config->{TWiki}->{Prefs}->getPreferencesValue ( "NOSEARCHALL", $web );
        if( ( $web eq $config->{TWiki}->{webName}  ) || ( ! $hidden ) ) {
            @list = $config->{TWiki}->{Store}->getTopicNames ( $web );
        }
    }
    my $text = "";
    my $item = "";
    my $line = "";
    my $mark = "";
    foreach $item ( @list ) {
        $line = $format;
        $line =~ s/\$web/$web/goi;
        $line =~ s/\$name/$item/goi;
        $line =~ s/\$qname/"$item"/goi;
        $mark = ( $selection =~ / \Q$item\E / ) ? $marker : "";
        $line =~ s/\$marker/$mark/goi;
        $text .= "$line$separator";
    }
    $text =~ s/$separator$//s;  # remove last separator
    return $text;
}

# =========================
=pod

---++ sub $config->{TWiki}->handleUrlParam (  $theArgs  )

Not yet documented.

=cut

sub handleUrlParam
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theArgs ) = @_;

    my $param     = $config->{TWiki}->extractNameValuePair ( $theArgs );
    my $newLine   = $config->{TWiki}->extractNameValuePair ( $theArgs, "newline" ) || "";
    my $encode    = $config->{TWiki}->extractNameValuePair ( $theArgs, "encode" ) || "";
    my $multiple  = $config->{TWiki}->extractNameValuePair ( $theArgs, "multiple" ) || "";
    my $separator = $config->{TWiki}->extractNameValuePair ( $theArgs, "separator" ) || "\n";
    my $value = "";
    if( $config->{TWiki}->{cgiQuery} ) {
        if( $multiple ) {
            my @valueArray = $config->{TWiki}->{cgiQuery}->param( $param );
            if( @valueArray ) {
                unless( $multiple =~ m/^on$/i ) {
                    my $item = "";
                    @valueArray = map {
                        $item = $_;
                        $_ = $multiple;
                        $_ .= $item unless( s/\$item/$item/go );
                        $_
                    } @valueArray;
                }
                $value = join ( $separator, @valueArray );
            }
        } else {
            $value = $config->{TWiki}->{cgiQuery}->param( $param );
            $value = "" unless( defined $value );
        }
    }
    $value =~ s/\r?\n/$newLine/go if( $newLine );
    $value = $config->{TWiki}->handleUrlEncode ( $value, 0, $encode ) if( $encode );
    unless( $value ) {
        $value = $config->{TWiki}->extractNameValuePair ( $theArgs, "default" ) || "";
    }
    return $value;
}

# =========================
# Encode to URL parameter or HTML entity
# TODO: For non-ISO-8859-1 $config->{TWiki}->{siteCharset}, need to convert to Unicode 
# for use in entity, or to UTF-8 before URL encoding.

=pod

---++ sub $config->{TWiki}->handleUrlEncode (  $theArgs, $doExtract  )

Not yet documented.

=cut

sub handleUrlEncode
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theArgs, $doExtract, $theType ) = @_;

    my $text = $theArgs;
    my $type = $theType || "";
    if( $doExtract ) {
        $text = $config->{TWiki}->extractNameValuePair ( $theArgs );
        $type = $config->{TWiki}->extractNameValuePair ( $theArgs, "type" ) || "";
    }
    if( $type =~ /^entit(y|ies)$/i ) {
        # HTML entity encoding
	# TODO: Encode characters > 0x7F to Unicode first
        $text =~ s/\"/\&\#034;/g;
        $text =~ s/\%/\&\#037;/g;
        $text =~ s/\*/\&\#042;/g;
        $text =~ s/\_/\&\#095;/g;
        $text =~ s/\=/\&\#061;/g;
        $text =~ s/\[/\&\#091;/g;
        $text =~ s/\]/\&\#093;/g;
        $text =~ s/\</\&\#060;/g;
        $text =~ s/\>/\&\#062;/g;
        $text =~ s/\|/\&\#124;/g;
    } else {
        # URL encoding
        $text =~ s/[\n\r]/\%3Cbr\%20\%2F\%3E/g;
        $text =~ s/\s+/\%20/g;
        $text =~ s/\"/\%22/g;
        $text =~ s/\&/\%26/g;
        $text =~ s/\+/\%2B/g;
        $text =~ s/\</\%3C/g;
        $text =~ s/\>/\%3E/g;
        $text =~ s/\\/\%5C/g;
        # Encode characters > 0x7F (ASCII-derived charsets only)
	# TODO: Encode to UTF-8 first
        $text =~ s/([\x7f-\xff])/'%' . unpack( "H*", $1 ) /ge;
    }
    return $text;
}


=pod

---++ sub $config->{TWiki}->handleNativeUrlEncode ( $theStr, $doExtract )

Perform URL encoding into native charset ($config->{TWiki}->{siteCharset}) - for use when
viewing attachments via browsers that generate UTF-8 URLs, on sites running
with non-UTF-8 (Native) character sets.  Aim is to prevent UTF-8 URL
encoding.  For mainframes, we assume that UTF-8 URLs will be translated
by the web server to an EBCDIC character set.

=cut

sub handleNativeUrlEncode { 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theStr, $doExtract ) = @_;

    my $isEbcdic = ( 'A' eq chr(193) ); 	# True if Perl is using EBCDIC

    if( $config->{TWiki}->{siteCharset} eq "utf-8" or $isEbcdic ) {
	# Just strip double quotes, no URL encoding - let browser encode to
	# UTF-8 or EBCDIC based $config->{TWiki}->{siteCharset} as appropriate
	$theStr =~ s/^"(.*)"$/$1/;	
	return $theStr;
    } else {
	return $config->{TWiki}->handleUrlEncode ( $theStr, $doExtract );
    }
}

=pod

---++ sub $config->{TWiki}->handleIntUrlEncode ( $theStr, $doExtract )

This routine was introduced to URL encode Mozilla's UTF-8 POST URLs in the
TWiki Feb2003 release - encoding is no longer needed since UTF-URLs are now
directly supported, but it is provided for backward compatibility with
skins that may still be using the deprecated %INTURLENCODE%.

=cut

sub handleIntUrlEncode
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theStr ) = @_;

    # Just strip double quotes, no URL encoding - Mozilla UTF-8 URLs
    # directly supported now
    $theStr =~ s/^"(.*)"$/$1/;	
    return $theStr;
}

=pod

---++ sub $config->{TWiki}->handleEnvVariable (  $theVar  )

Not yet documented.

=cut

sub handleEnvVariable
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theVar ) = @_;
    my $value = $ENV{$theVar} || "";
    return $value;
}

=pod

---++ sub $config->{TWiki}->handleTmplP (  $theParam  )

Not yet documented.

=cut

sub handleTmplP
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theParam ) = @_;

    $theParam = $config->{TWiki}->extractNameValuePair ( $theParam );
    my $value = $config->{TWiki}->{Store}->handleTmplP ( $theParam );
    return $value;
}

# =========================
# Create spaced-out topic name for Ref-By search 
=pod

---++ sub $config->{TWiki}->handleSpacedTopic (  $theTopic  )

Not yet documented.

=cut

sub handleSpacedTopic
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theTopic ) = @_;
    my $spacedTopic = $theTopic;
    $spacedTopic =~ s/($config->{TWiki}->{regex}{singleLowerAlphaRegex}+)($config->{TWiki}->{regex}{singleUpperAlphaNumRegex}+)/$1%20*$2/go;   # "%20*" is " *" - I18N: only in ASCII-derived charsets
    return $spacedTopic;
}

# =========================
=pod

---++ sub $config->{TWiki}->handleIcon (  $theParam  )

Not yet documented.

=cut

sub handleIcon
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theParam ) = @_;

    $theParam = $config->{TWiki}->extractNameValuePair ( $theParam );
    my $value = $config->{TWiki}->{Attach}->filenameToIcon ( "file.$theParam" );
    return $value;
}

=pod

---++ sub $config->{TWiki}->handleRelativeTopicPath ( $styleTopic, $web )

Not yet documented.

=cut

sub handleRelativeTopicPath
{ 
   my $self = shift;
	my $config = $self->{config} ;


       my( $theStyleTopic, $theWeb ) = @_;

       if ( !$theStyleTopic ) {
               return "";
       }
       my $theRelativePath;
       # if there is no dot in $theStyleTopic, no web has been specified
       if ( index( $theStyleTopic, "." ) == -1 ) {
               # add local web
               $theRelativePath = $theWeb . "/" . $theStyleTopic;
       } else {
               $theRelativePath = $theStyleTopic; #including dot
       }
       # replace dot by slash is not necessary; TWiki.MyTopic is a valid url
       # add ../ if not already present to make a relative file reference
       if ( index( $theRelativePath, "../" ) == -1 ) {
               $theRelativePath = "../" . $theRelativePath;
       }
       return $theRelativePath;
}

=pod

---++ $config->{TWiki}->handleInternalTags ( $text, $topic, $web )

Modifies $text in-place, replacing variables internal to TWiki with their
values.  Some example variables: %<nop>TOPIC%, %<nop>SCRIPTURL%, %<nop>WIKINAME%, etc.

=cut

sub handleInternalTags
{ 
   my $self = shift;
	my $config = $self->{config} ;


    # modify arguments directly, i.e. call by reference
    # $_[0] is text
    # $_[1] is topic
    # $_[2] is web

    # Make Edit URL unique for every edit - fix for RefreshEditPage.
    $_[0] =~ s!%EDITURL%!"$config->{TWiki}->{dispScriptUrlPath}/edit$config->{TWiki}->{scriptSuffix}/%WEB%/%TOPIC%\?t=" . time()!ge;

    $_[0] =~ s/%NOP{(.*?)}%/$1/gs;  # remove NOP tag in template topics but show content
    $_[0] =~ s/%NOP%/<nop>/g;
    $_[0] =~ s/%TMPL\:P{(.*?)}%/$config->{TWiki}->handleTmplP ($1)/ge;
    $_[0] =~ s/%SEP%/$config->{TWiki}->handleTmplP ('"sep"')/ge;

    $_[0] =~ s/%HTTP_HOST%/$config->{TWiki}->handleEnvVariable ('HTTP_HOST')/ge;
    $_[0] =~ s/%REMOTE_ADDR%/$config->{TWiki}->handleEnvVariable ('REMOTE_ADDR')/ge;
    $_[0] =~ s/%REMOTE_PORT%/$config->{TWiki}->handleEnvVariable ('REMOTE_PORT')/ge;
    $_[0] =~ s/%REMOTE_USER%/$config->{TWiki}->handleEnvVariable ('REMOTE_USER')/ge;

    $_[0] =~ s/%TOPIC%/$_[1]/g;
    $_[0] =~ s/%BASETOPIC%/$config->{TWiki}->{topicName}/g;
    $_[0] =~ s/%INCLUDINGTOPIC%/$config->{TWiki}->{includingTopicName}/g;
    $_[0] =~ s/%SPACEDTOPIC%/$config->{TWiki}->handleSpacedTopic ($_[1])/ge;
    $_[0] =~ s/%WEB%/$_[2]/g;
    $_[0] =~ s/%BASEWEB%/$config->{TWiki}->{webName}/g;
    $_[0] =~ s/%INCLUDINGWEB%/$config->{TWiki}->{includingWebName}/g;

    # I18N information
    $_[0] =~ s/%CHARSET%/$config->{TWiki}->{siteCharset}/g;
    $_[0] =~ s/%SHORTLANG%/$config->{TWiki}->{siteLang}/g;
    $_[0] =~ s/%LANG%/$config->{TWiki}->{siteFullLang}/g;

    $_[0] =~ s/%TOPICLIST{(.*?)}%/$config->{TWiki}->handleWebAndTopicList ($1,'0')/ge;
    $_[0] =~ s/%WEBLIST{(.*?)}%/$config->{TWiki}->handleWebAndTopicList ($1,'1')/ge;

    # URLs and paths
    $_[0] =~ s/%WIKIHOMEURL%/$config->{TWiki}->{wikiHomeUrl}/g;
    $_[0] =~ s/%SCRIPTURL%/$config->{TWiki}->{urlHost}$config->{TWiki}->{dispScriptUrlPath}/g;
    $_[0] =~ s/%SCRIPTURLPATH%/$config->{TWiki}->{dispScriptUrlPath}/g;
    $_[0] =~ s/%SCRIPTSUFFIX%/$config->{TWiki}->{scriptSuffix}/g;
    $_[0] =~ s/%PUBURL%/$config->{TWiki}->{urlHost}$config->{TWiki}->{pubUrlPath}/g;
    $_[0] =~ s/%PUBURLPATH%/$config->{TWiki}->{pubUrlPath}/g;
    $_[0] =~ s/%RELATIVETOPICPATH{(.*?)}%/$config->{TWiki}->handleRelativeTopicPath ($1,$_[2])/ge;

    # Attachments
    $_[0] =~ s!%ATTACHURL%!$config->{TWiki}->{urlHost}%ATTACHURLPATH%!g;
    # I18N: URL-encode full web, topic and filename to the native
    # $config->{TWiki}->{siteCharset} for attachments viewed from browsers that use UTF-8 URL,
    # unless we are in UTF-8 mode or working on EBCDIC mainframe.
    # Include the filename suffixed to %ATTACHURLPATH% - a hack, but required
    # for migration purposes
    $_[0] =~ s!%ATTACHURLPATH%/($config->{TWiki}->{regex}{filenameRegex})!$config->{TWiki}->handleNativeUrlEncode ("$config->{TWiki}->{pubUrlPath}/$_[2]/$_[1]/$1",1)!ge;
    $_[0] =~ s!%ATTACHURLPATH%!$config->{TWiki}->handleNativeUrlEncode ("$config->{TWiki}->{pubUrlPath}/$_[2]/$_[1]",1)!ge;	# No-filename case
    $_[0] =~ s/%ICON{(.*?)}%/$config->{TWiki}->handleIcon ($1)/ge;

    # URL encoding
    $_[0] =~ s/%URLPARAM{(.*?)}%/$config->{TWiki}->handleUrlParam ($1)/ge;
    $_[0] =~ s/%(URL)?ENCODE{(.*?)}%/$config->{TWiki}->handleUrlEncode ($2,1)/ge; 	# ENCODE is documented, URLENCODE is legacy
    $_[0] =~ s/%INTURLENCODE{(.*?)}%/$config->{TWiki}->handleIntUrlEncode ($1)/ge;	# Deprecated - not needed with UTF-8 URL support
    
    # Dates and times
    $_[0] =~ s/%DATE%/$config->{TWiki}->formatTime (time(), "\$day \$mon \$year", "gmtime")/ge; 					# Deprecated, but used in signatures
    $_[0] =~ s/%GMTIME%/$config->{TWiki}->handleTime ("","gmtime")/ge;
    $_[0] =~ s/%GMTIME{(.*?)}%/$config->{TWiki}->handleTime ($1,"gmtime")/ge;
    $_[0] =~ s/%SERVERTIME%/$config->{TWiki}->handleTime ("","servertime")/ge;
    $_[0] =~ s/%SERVERTIME{(.*?)}%/$config->{TWiki}->handleTime ($1,"servertime")/ge;
    $_[0] =~ s/%DISPLAYTIME%/$config->{TWiki}->handleTime ("", $config->{TWiki}->{displayTimeValues})/ge;
    $_[0] =~ s/%DISPLAYTIME{(.*?)}%/$config->{TWiki}->handleTime ($1, $config->{TWiki}->{displayTimeValues})/ge;

    $_[0] =~ s/%WIKIVERSION%/$config->{TWiki}->{wikiversion}/g;
    $_[0] =~ s/%PLUGINVERSION{(.*?)}%/$config->{TWiki}->{Plugins}->getPluginVersion ($1)/ge;
    $_[0] =~ s/%USERNAME%/$config->{TWiki}->{userName}/g;
    $_[0] =~ s/%WIKINAME%/$config->{TWiki}->{wikiName}/g;
    $_[0] =~ s/%WIKIUSERNAME%/$config->{TWiki}->{wikiUserName}/g;
    $_[0] =~ s/%WIKITOOLNAME%/$config->{TWiki}->{wikiToolName}/g;
    $_[0] =~ s/%MAINWEB%/$config->{TWiki}->{mainWebname}/g;
    $_[0] =~ s/%TWIKIWEB%/$config->{TWiki}->{twikiWebname}/g;
    $_[0] =~ s/%HOMETOPIC%/$config->{TWiki}->{mainTopicname}/g;
    $_[0] =~ s/%WIKIUSERSTOPIC%/$config->{TWiki}->{wikiUsersTopicname}/g;
    $_[0] =~ s/%WIKIPREFSTOPIC%/$config->{TWiki}->{wikiPrefsTopicname}/g;
    $_[0] =~ s/%WEBPREFSTOPIC%/$config->{TWiki}->{webPrefsTopicname}/g;
    $_[0] =~ s/%NOTIFYTOPIC%/$config->{TWiki}->{notifyTopicname}/g;
    $_[0] =~ s/%STATISTICSTOPIC%/$config->{TWiki}->{statisticsTopicname}/g;
    $_[0] =~ s/%STARTINCLUDE%//g;
    $_[0] =~ s/%STOPINCLUDE%//g;
    $_[0] =~ s/%SECTION{(.*?)}%//g;
    $_[0] =~ s/%ENDSECTION%//g;
    my $ok = 16; # SEARCH may be nested up to 16 times
    TRY: while( $_[0] =~ s/%SEARCH{(.*?)}%/$config->{TWiki}->handleSearchWeb ($1,$_[2],$_[1])/ge ) {
        last TRY unless( --$ok );
    }
    $_[0] =~ s/%METASEARCH{(.*?)}%/$config->{TWiki}->handleMetaSearch ($1)/ge;
    $_[0] =~ s/%FORMFIELD{(.*?)}%/$config->{TWiki}->{Render}->getFormField ($_[2],$_[1],$1)/ge;

    $_[0] =~ s/%REVINFO%/$config->{TWiki}->handleRevisionInfo ( $_[2], $_[1] )/ge;
    $_[0] =~ s/%REVINFO{(.*?)}%/$config->{TWiki}->handleRevisionInfo ( $_[2], $_[1], $1 )/ge;
}

=pod

---++ $config->{TWiki}->takeOutVerbatim ( $text, \@verbatimBuffer )
Return value: $textWithoutVerbatim

Searches through $text and extracts &lt;verbatim> blocks, appending each
onto the end of the @verbatimBuffer array and replacing it with a token
string which is not affected by TWiki rendering.  The text after these
substitutions is returned.

This function is designed to preserve the contents of verbatim blocks
through some rendering operation.  The general sequence of calls for
this use is something like this:

   $textToRender = $config->{TWiki}->takeOutVerbatim ($inputText, \@verbatimBlocks);
   $renderedText = performSomeRendering($textToRender);
   $resultText = $config->{TWiki}->putBackVerbatim ($renderedText, "pre", @verbatimBlocks);

Note that some changes are made to verbatim blocks here: &lt; and > are replaced
by their HTML entities &amp;lt; and &amp;gt;, and the actual &lt;verbatim>
tags are replaced with &lt;pre> tags so that the text is rendered truly
"verbatim" by a browser.  If this is not desired, pass "verbatim" as the
second parameter of putBackVerbatim instead of "pre".

=cut

sub takeOutVerbatim
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $intext, $verbatim ) = @_;	# $verbatim is ref to array
    
    if( $intext !~ /<verbatim>/oi ) {
        return( $intext );
    }
    
    # Exclude text inside verbatim from variable substitution
    
    my $tmp = "";
    my $outtext = "";
    my $nesting = 0;
    my $verbatimCount = $#{$verbatim} + 1;
    
    foreach( split( /\n/, $intext ) ) {
        if( /^(\s*)<verbatim>\s*$/i ) {
            $nesting++;
            if( $nesting == 1 ) {
                $outtext .= "$1%_VERBATIM$verbatimCount%\n";
                $tmp = "";
                next;
            }
        } elsif( m|^\s*</verbatim>\s*$|i ) {
            $nesting--;
            if( ! $nesting ) {
                $verbatim->[$verbatimCount++] = $tmp;
                next;
            }
        }

        if( $nesting ) {
            $tmp .= "$_\n";
        } else {
            $outtext .= "$_\n";
        }
    }
    
    # Deal with unclosed verbatim
    if( $nesting ) {
        $verbatim->[$verbatimCount] = $tmp;
    }
       
    return $outtext;
}

=pod

---++$config->{TWiki}->putBackVerbatim ( $textWithoutVerbatim, $putBackType, @verbatimBuffer )
Return value: $textWithVerbatim

This function reverses the actions of takeOutVerbatim above.  See the text for
takeOutVerbatim for a more thorough description.

Set $putBackType to 'verbatim' to get back original text, or to 'pre' to
convert to HTML readable verbatim text.

=cut

sub putBackVerbatim
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $text, $type, @verbatim ) = @_;
    
    for( my $i=0; $i<=$#verbatim; $i++ ) {
        my $val = $verbatim[$i];
        if( $type ne "verbatim" ) {
            $val =~ s/&/&amp;/g;
            $val =~ s/</&lt;/g;
            $val =~ s/>/&gt;/g;
            $val =~ s/\t/   /g; # A shame to do this, but been in TWiki.org have converted
                                # 3 spaces to tabs since day 1
        }
        $text =~ s|%_VERBATIM$i%|<$type>\n$val</$type>|;
    }

    return $text;
}

=pod

---++ $config->{TWiki}->handleCommonTags ( $text, $topic, $web, @processedTopics )
Return value: $handledText

Processes %<nop>VARIABLE%, %<nop>TOC%, and %<nop>INCLUDE% syntax; also includes
"commonTagsHandler" plugin hook.  If processing an included topic,
@processedTopics should be a list of topics already included, or in
the process of being included.

Returns the text of the topic, after file inclusion, variable substitution,
table-of-contents generation, and any plugin changes from commonTagsHandler.

=cut

sub handleCommonTags
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $text, $theTopic, $theWeb, @theProcessedTopics ) = @_;

    # PTh 22 Jul 2000: added $theWeb for correct handling of %INCLUDE%, %SEARCH%
    if( !$theWeb ) {
        $theWeb = $config->{TWiki}->{webName};
    }

    # TWiki Plugin Hook (for cache Plugins only)
    $config->{TWiki}->{Plugins}->beforeCommonTagsHandler ( $text, $theTopic, $theWeb );

    my @verbatim = ();
    $text = $config->{TWiki}->takeOutVerbatim ( $text, \@verbatim );

    # Escape rendering: Change " !%VARIABLE%" to " %<nop>VARIABLE%", for final " %VARIABLE%" output
    $text =~ s/(\s)\!\%([A-Z])/$1%<nop>$2/g;

    # handle all preferences and internal tags (for speed: call by reference)
    $config->{TWiki}->{includingWebName} = $theWeb;
    $config->{TWiki}->{includingTopicName} = $theTopic;
    $config->{TWiki}->{Prefs}->handlePreferencesTags ( $text );
    $config->{TWiki}->handleInternalTags ( $text, $theTopic, $theWeb );

    # recursively process multiple embedded %INCLUDE% statements and prefs
    $text =~ s/%INCLUDE{(.*?)}%/$config->{TWiki}->handleIncludeFile ($1, $theTopic, $theWeb, \@verbatim, @theProcessedTopics )/ge;

    # TWiki Plugin Hook
    $config->{TWiki}->{Plugins}->commonTagsHandler ( $text, $theTopic, $theWeb, 0 );

    # handle tags again because of plugin hook
    $config->{TWiki}->{Prefs}->handlePreferencesTags ( $text );
    $config->{TWiki}->handleInternalTags ( $text, $theTopic, $theWeb );

    $text =~ s/%TOC{([^}]*)}%/$config->{TWiki}->handleToc ($text,$theTopic,$theWeb,$1)/ge;
    $text =~ s/%TOC%/$config->{TWiki}->handleToc ($text,$theTopic,$theWeb,"")/ge;

    # Codev.FormattedSearchWithConditionalOutput: remove <nop> lines, possibly introduced by
    # SEARCHes with conditional CALC. This needs to be done after CALC and before table rendering
    $text =~ s/^<nop>\r?\n//gm;

    # Ideally would put back in getRenderedVersion rather than here which would save removing
    # it again!  But this would mean altering many scripts to pass back verbatim
    $text = $config->{TWiki}->putBackVerbatim ( $text, "verbatim", @verbatim );

    # TWiki Plugin Hook (for cache Plugins only)
    $config->{TWiki}->{Plugins}->afterCommonTagsHandler ( $text, $theTopic, $theWeb );

    return $text;
}

# =========================
=pod

---++ sub $config->{TWiki}->handleMetaTags (  $theWeb, $theTopic, $text, $meta, $isTopRev  )

| TODO | move to Render.pm or Meta.pm of Forms.pm |
| | used to render the non-active modes of META data (view, preview ...) |
Not yet documented.

=cut

sub handleMetaTags
{ 
   my $self = shift;
	my $config = $self->{config} ;


    my( $theWeb, $theTopic, $text, $meta, $isTopRev ) = @_;

    $text =~ s/%META{\s*"form"\s*}%/$config->{TWiki}->{Render}->renderFormData ( $theWeb, $theTopic, $meta )/ge;    #this renders META:FORM and META:FIELD
    $text =~ s/%META{\s*"formfield"\s*(.*?)}%/$config->{TWiki}->{Render}->renderFormField ( $meta, $1 )/ge;                 #TODO: what does this do? (is this the old forms system, and so can be deleted)
    $text =~ s/%META{\s*"attachments"\s*(.*)}%/$config->{TWiki}->{Attach}->renderMetaData ( $theWeb,
                                                $theTopic, $meta, $1, $isTopRev )/ge;                                       #renders attachment tables
    $text =~ s/%META{\s*"moved"\s*}%/$config->{TWiki}->{Render}->renderMoved ( $theWeb, $theTopic, $meta )/ge;      #render topic moved information
    $text =~ s/%META{\s*"parent"\s*(.*)}%/$config->{TWiki}->{Render}->renderParent ( $theWeb, $theTopic, $meta, $1 )/ge;    #render the parent information

    $text = $config->{TWiki}->handleCommonTags ( $text, $theTopic );
    $text = $config->{TWiki}->{Render}->getRenderedVersion ( $text, $theWeb );

    return $text;
}

=end twiki

=cut

1;
