# Plugin for Foswiki - The Free and Open Source Wiki, http://foswiki.org/
#
# Copyright (C) 2015 Foswiki Contributors
#
# 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

package Foswiki::Plugins::PubLinkPlugin;

use strict;
use warnings;

our $VERSION           = '1.00';
our $RELEASE           = '11 Sep 2015';
our $NO_PREFS_IN_TOPIC = 1;
our $SHORTDESCRIPTION  = 'Correct PUB links to the Store encoding.';

my $protocolsPattern;

sub initPlugin {
    my ( $topic, $web, $user, $installWeb ) = @_;

# This regex will capture the protocol. Regexs need to allow for the capture.
    $protocolsPattern =
      Foswiki::Func::getRegularExpression('linkProtocolPattern');

    return 1;
}

sub completePageHandler {
### my ( $html, $headers ) = @_;   # do not uncomment, use $_[0], $_[1]... instead

    $_[0] =~
s#(<a .*?href=(["'])(?:$protocolsPattern://$Foswiki::cfg{DefaultUrlHost})?($Foswiki::cfg{PubUrlPath}/?.*?)\2.*?>.*?</a>)#  handleHtmlLink($1, $4) #ge;
    $_[0] =~
s#(<img .*?src=(["'])(?:$protocolsPattern://$Foswiki::cfg{DefaultUrlHost})?($Foswiki::cfg{PubUrlPath}/?.*?)\2.*?/>)#  handleHtmlLink($1, $4) #ge;

}


sub handleHtmlLink {
    my ( $wholeLink, $url ) = @_;

    # Extract just the path component, truncating any querystring
    my ($path)  = $url =~ m/^(.*)\??.*$/;

    # Decode the path back to utf-8 
    my $decoded = Foswiki::urlDecode($path);

    # re-encode the decoded URL into the {Store}{Encoding}
    my $text = Encode::encode( $Foswiki::cfg{Store}{Encoding} || 'utf-8',
        $decoded, sub { HTML::Entities::encode_entities( chr(shift) ) } );

    # And entity-encode each non-ASCII high character.
    $text =~ s{([^0-9a-zA-Z-_.:~!*#/])}{sprintf('%%%02x',ord($1))}ge;

    # Replace the url in the link.
    $wholeLink =~ s/$url/$text/;

    return "$wholeLink";

}

1;

