#!/usr/bin/perl -wT
#
# TWiki Collaboration Platform, http://TWiki.org/
#
# Copyright (C) 1999-2004 Peter Thoeny, peter@thoeny.com
#
# 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

BEGIN {
    # Set default current working directory
    if( $ENV{"SCRIPT_FILENAME"} && $ENV{"SCRIPT_FILENAME"} =~ /^(.+)\/[^\/]+$/ ) {
        chdir $1;
    }
    # Set library paths in @INC at compile time
    unshift @INC, '.';
    require 'setlib.cfg';
}

use strict;
use CGI::Carp qw(fatalsToBrowser);
use CGI;
use TWiki;
use TWiki::UI::Upload;

my $query = new CGI;

my $thePathInfo = $query->path_info();
my $theRemoteUser = $query->remote_user();
my $theTopic = $query->param( 'topic' );
my $theUrl = $query->url;

my ( $topic, $webName, $dummy, $userName ) = 
  TWiki::initialize( $thePathInfo, $theRemoteUser, $theTopic,
                     $theUrl, $query );

# Check to see if a new topic already exists
return unless TWiki::UI::webExists($webName, $topic);
if ( TWiki::Store::topicExists($webName, $topic) ) {
   TWiki::UI::oops($webName, $topic, "newtopic", "ERROR $webName.$topic already exists");
}

return if TWiki::UI::isMirror( $webName, $topic );

# Create the new topic
my $saveCmd = $query->param( "cmd" ) || "";
my $text = $query->param( "text" );
my $meta = "";

my $unlock = $query->param( "unlock" ) || "";
my $dontNotify = $query->param( "dontnotify" ) || "";
my $changeform = $query->param( 'submitChangeForm' ) || "";
my $theParent = $query->param( 'topicparent' ) || "";
my $formTemplate = $query->param( "formtemplate" );

my $wikiUserName = TWiki::userToWikiName( $userName );
return unless TWiki::UI::isAccessPermitted( $webName, $topic,
                                            "change", $wikiUserName );
# A template was requested; read it, and expand URLPARAMs within the
# template using our CGI record
my $templatetopic = $query->param( "templatetopic");
if ($templatetopic) {
  ($meta, $text) = &TWiki::Store::readTopic( $webName, $templatetopic );
  # If template topic is non-existent, the text will be blank (input will be ignored.)
  $text = TWiki::expandVariablesOnTopicCreation( $text );
}

if ( ! $meta ) {
   $meta = TWiki::Meta->new();
}
	
# PTh 06 Nov 2000: check if proper use of save script
if( ! ( defined $text ) ) { 
  $text = "\n"; # Let us assume single line.
} elsif( ! $text ) {
  # Allow empty topic assuming that there is attachment.
  $text = "\n";
}
$text = TWiki::Render::decodeSpecialChars( $text );
$text =~ s/ {3}/\t/go;


# parent setting
if( $theParent ) {
   $meta->put( "TOPICPARENT", ( "name" => $theParent ) );
}
if( $formTemplate ) {
    $meta->put( "FORM", ( name => $formTemplate ) ) if( $formTemplate ne "none" );
}

# use TWiki::Form;
# # CODE_SMELL: this fieldVars2Meta thing should be in UI, not Meta
# # Expand field variables, unless this new page is templated
# TWiki::Form::fieldVars2Meta( $webName, $query, $meta ) ;
# # unless $templatetopic;
# # What's the problem if ther is template?
use TWiki::Prefs;
$text = TWiki::Prefs::updateSetFromForm( $meta, $text );

my $error = TWiki::Store::saveTopic( $webName, $topic, $text, $meta, $saveCmd, $unlock, $dontNotify );

if( $error ) {
  TWiki::UI::oops( $webName, $topic, "saveerr", $error );
} 

# Upload directs to topic view.
my $filepath = $query->param( "filepath" ) || "";
if ( $filepath ) {
   TWiki::UI::Upload::upload( $webName, $topic, $userName, $query );
} else {
   TWiki::redirect( $query, TWiki::getViewUrl( TWiki::Store::normalizeWebTopicName($webName, $topic)) );
}

1;

