package TWiki::Plugins::InterwikiPlugin;
# Plugin for TWiki Collaboration Platform, http://TWiki.org/
#
# Copyright (C) 2000-2003 Andrea Sterbini, a.sterbini@flashnet.it
# Copyright (C) 2001-2004 Peter Thoeny, peter@thoeny.com
#
# 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
#
# =========================
# Interwiki Link Plugin:
#
# Here we handle inter-site links, i.e. links going outside TWiki
# The recognized syntax is:
#       InterSiteName:TopicName
# and inserts <a href="URL/TopicName">InterSiteName:TopicName</a>
# link, where URL is obtained by a topic that lists all
# InterSiteName/URL pairs.
# Inter-site name convention: Sites must start with upper case
# and must be preceeded by white space, '-', '*' or '('
#
# =========================
# =========================



# 'Use locale' for internationalisation of Perl sorting and searching - 
# main locale settings are done in $config->{TWiki}->setupLocale 
    # Do a dynamic 'use locale' for this module



# Regexes for the Site:page format InterWiki reference - updated to support
# 8-bit characters in both parts - see Codev.InternationalisationEnhancements

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} ;


$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{VERSION} = '1.005'; # 16 Feb 2004
$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{interSiteLinkRulesTopicName} = "InterWikis";
$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{VERSION} = '1.003'; # 18 Jan 2003
$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{interSiteLinkRulesTopicName} = "InterWikis";
$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{prefixPattern}  = '(^|[\s\-\*\(])';
if( $config->{TWiki}->{Plugins}->{VERSION} >= 1.020 ) {
    $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{upperAlpha}    = $config->{TWiki}->{Func}->getRegularExpression ("upperAlpha");
    $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{mixedAlphaNum} = $config->{TWiki}->{Func}->getRegularExpression ("mixedAlphaNum");
} else {
    $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{upperAlpha}    = $TWiki::upperAlpha;
    $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{mixedAlphaNum} = $TWiki::mixedAlphaNum;
}
$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{sitePattern}    = "([$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{upperAlpha}][$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{mixedAlphaNum}]+)";
$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{pagePattern}    = "([$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{mixedAlphaNum}_\/][$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{mixedAlphaNum}" . '\+\_\.\,\;\:\!\?\/\%\#-]+?)';
$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{postfixPattern} = '(?=[\s\.\,\;\:\!\?\)]*(\s|$))';
 {
    if( $config->{TWiki}->{useLocale} ) {
        require locale;
	import locale ();
    }
}

}# END of init_config

# =========================
# Plugin startup - read preferences and get all InterWiki Site->URL mappings
sub initPlugin
{ 
   my $self = shift;
	my $config = $self->{config} ;


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

    ( $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{topic}, $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{web}, $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{user}, $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{installWeb} ) = @_;

    # check for Plugins.pm versions
    if( $config->{TWiki}->{Plugins}->{VERSION} < 1 ) {
        $config->{TWiki}->{Func}->writeWarning ( "Version mismatch between InterwikiPlugin and Plugins.pm" );
        return 0;
    }

    # Get plugin preferences from InterwikiPlugin topic
    my $interFileName = $config->{TWiki}->{Func}->getPreferencesValue ( "INTERWIKIPLUGIN_RULESTOPIC" ) 
                        || "$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{installWeb}.$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{interSiteLinkRulesTopicName}";
    $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{suppressTooltip}  = $config->{TWiki}->{Func}->getPreferencesFlag ( "INTERWIKIPLUGIN_SUPPRESSTOOLTIP" );
    $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{debug}            = $config->{TWiki}->{Func}->getPreferencesFlag ( "INTERWIKIPLUGIN_DEBUG" );

    # get the Interwiki site->url map topic
    my $InterFile = '';
    my $dataDir = $config->{TWiki}->{Func}->getDataDir ();
    if( $interFileName =~ m/^([^.]+)\.([^.]+)$/ ) {
        $InterFile = "$dataDir/$1/$2.txt"; 	
    } elsif( $interFileName =~ m/^([^.]+)$/ ) {
        $InterFile = "$dataDir/$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{installWeb}/$1.txt"; 
    } else {
        return 0;
    }

    $InterFile =~ s/%MAINWEB%/$config->{TWiki}->{Func}->getMainWebname ()/geo;
    $InterFile =~ s/%TWIKIWEB%/$config->{TWiki}->{Func}->getTwikiWebname /geo;
    $config->{TWiki}->{Func}->writeDebug ( "- InterwikiPlugin, rules file: $InterFile" ) if $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{debug};

    # FIXME: use readWebTopic
    open(IN, "<$InterFile") or return 0;  # FIXME: Later warn?
    my @data = <IN>;
    close IN;

    # grep "| alias | URL | ..." table and extract into "alias", "URL" list
    # FIXME: Should be able to do this pipeline with just one regex match
    @data = map { split /\s+/, $_, 2 }
            map { s/^\|\s*$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{sitePattern}\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|.*$/$1 $2 $3/os ; $_ }
            grep { m/^\|\s*$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{sitePattern}\s*\|.*?\|.*?\|/o } @data;
    if( $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{debug} ) {
        my $tmp = join(", " , @data );
        $config->{TWiki}->{Func}->writeDebug ( "- InterwikiPlugin, table: $tmp" );
    }
    %{$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{interSiteTable}}  = @data;

    # Plugin correctly initialized
    $config->{TWiki}->{Func}->writeDebug ( "- $config->{TWiki}->{Plugins}->{InterwikiPlugin}->initPlugin ( $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{web}.$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{topic} ) is OK" ) if $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{debug};
    return 1;
}

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


### my ( $text, $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{web} ) = @_;   # do not uncomment, use $_[0], $_[1] instead
    $config->{TWiki}->{Func}->writeDebug ( "- InterwikiPlugin::startRenderingHandler( $_[1] )" ) if $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{debug};

    $_[0] =~ s/(\[\[)$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{sitePattern}:$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{pagePattern}(\]\]|\]\[| )/$config->{TWiki}->{Plugins}->{InterwikiPlugin}->handleInterwiki ($1,$2,$3,$4)/geo;
    $_[0] =~ s/$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{prefixPattern}$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{sitePattern}:$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{pagePattern}$config->{TWiki}->{Plugins}->{InterwikiPlugin}->{postfixPattern}/$config->{TWiki}->{Plugins}->{InterwikiPlugin}->handleInterwiki ($1,$2,$3,"")/geo;
}

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


    my( $thePrefix, $theSite, $theTopic, $thePostfix ) = @_;

    $config->{TWiki}->{Func}->writeDebug ( "- InterwikiPlugin::handleInterwikiSiteLink: (site: $theSite), (topic: $theTopic)" ) if $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{debug};

    my $text = "";
    if( defined( $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{interSiteTable}{ $theSite } ) ) {
        my( $url, $help ) = split( /\s+/, $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{interSiteTable}{ $theSite }, 2 );
        my $title = "";
        if( ! $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{suppressTooltip} ) {
            $help =~ s/<nop>/&nbsp;/goi;
            $help =~ s/[\"\<\>]*//goi;
            $help =~ s/\$page/$theTopic/go;
            $title = " title=\"$help\"";
        }
        $config->{TWiki}->{Func}->writeDebug ( "  (url: $url), (help: $help)" ) if $config->{TWiki}->{Plugins}->{InterwikiPlugin}->{debug};
        if( $url =~ s/\$page/$theTopic/go ) {
            $text = $url;
        } else {
            $text = "$url$theTopic";
        }
        if( $thePostfix ) {
            $text = "$thePrefix$text][";
            $text .= "$theSite\:$theTopic]]" if( $thePostfix eq "]]" );
        } else {
            $text = "$thePrefix<a href=\"$text\"$title>$theSite\:$theTopic</a>";
        }
    } else {
        $text = "$thePrefix$theSite\:$theTopic$thePostfix";
    }
    return $text;
}

# =========================

1;

1;
