#!/usr/bin/perl -w

# Copyright 2001-2006 The Apache Software Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

=head1 demo/moewiki - minimal AxKit2 wiki implementation

This is a module that demonstrates an absolute minimum for a Wiki
software in AxKit. By saying 'minimal', I really mean it. Editing
existing pages in HTML source code, that's it. The "Edit this page"
link on every page should be considered pure luxus accessory.

=cut

use XML::LibXML;
my $parser = new XML::LibXML();
$parser->expand_xinclude(0);

sub hook_xmlresponse {
    my ($self, $input) = @_;
    my $client = $self->client;

    return DECLINED if (!defined $client->param('edit'));

    my $file = $client->headers_in->filename;
    $file =~ s/\.xml$//;
    return BAD_REQUEST if $file !~ m/\/[a-zA-Z0-9_-]+$/;

    if (! -f $file.'.xml') {
        $input->dom("<html><body>\nThis page has just been created.\n</body></html>");
    } elsif ($client->param('text')) {
        my $dom = $parser->parse_html_string($client->param('text'));
        $dom->setEncoding('UTF-8');
        open(FH,'>:utf8',$file.'.xml');
        print FH $dom->toStringC14N();
        close(FH);
        my $uri = $client->headers_in->request_uri;
        $uri =~ s/\?.*$//;
        warn("URI: $uri");
        $self->client->headers_out->header('Location', "http://".$client->headers_in->header('Host').$uri);
        return REDIRECT;
    }

    $input->transform(XSLT('demo/moewiki/edit.xsl'));
    return DECLINED;
}
