#!/usr/bin/perl -wT
#
# TWiki WikiClone (see wiki.pm for $wikiversion and other info)
#
# Copyright (C) 1999-2002 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

# This is identical to preview except it builds text from pretext, the action,
# and posttext

use CGI::Carp qw(fatalsToBrowser);
use CGI;
use lib ( '.' );
use lib ( '../lib' );
use TWiki;

use strict;

&main();


sub main
{
  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 );
  my $text = "";  # to suppress warning

  my $tmpl = ""; 
  my $ptext = "";
  my $meta = "";
  my $formFields = "";
  my $wikiUserName = &TWiki::userToWikiName( $userName );
  my $action = $query->param( 'action' );
  my $from = $query->param( 'actionfrom' ) || "$webName.$topic";
  $from =~ s/\./\//g;
  $from =~ s/-/\#/g;

  if( ! &TWiki::Store::webExists( $webName ) ) {
    my $url = &TWiki::getOopsUrl( $webName, $topic, "oopsnoweb" );
    TWiki::redirect( $query, $url );
    return;
  }

  my( $mirrorSiteName, $mirrorViewURL ) = &TWiki::readOnlyMirrorWeb( $webName );
  if( $mirrorSiteName ) {
    my $url = &TWiki::getOopsUrl( $webName, $topic, "oopsmirror", $mirrorSiteName, $mirrorViewURL );
    TWiki::redirect( $query, $url );
    return;
  }

  if ( $action eq "Cancel") {
    my $viewUrl = "$TWiki::defaultUrlHost$TWiki::scriptUrlPath/view/";
    TWiki::redirect( $query, "$viewUrl$from" );
    return;
  }
  
  # reset lock time, this is to prevent contention in case of a long edit session
  &TWiki::Store::lockTopic( $topic );

  my $skin = $query->param( "skin" ) || &TWiki::Prefs::getPreferencesValue( "SKIN" );

  # Is user looking to change the form used?  Sits oddly in preview, but to avoid Javascript and pick
  # up text on edit page it has to be in preview.
#    my $changeform = $query->param( 'submitChangeForm' ) || "";
#    if( $changeform ) {
#        &TWiki::Form::changeForm( $webName, $topic, $query );
#        return;
#    }

  # get view template, standard view or a view with a different skin
  $tmpl = &TWiki::Store::readTemplate( "preview", $skin );
  my $dontNotify = $query->param( "dontnotify" ) || "";
  $tmpl =~ s/%DONTNOTIFY%/$dontNotify/go;
  my $saveCmd = $query->param( "cmd" ) || "";
  if( $saveCmd ) {
    if( ! &TWiki::Access::userIsInGroup( $wikiUserName, $TWiki::superAdminGroup ) ) {
      # user has no permission to execute undocumented cmd=... parameter
      my $url = &TWiki::getOopsUrl( $webName, $topic, "oopsaccessgroup", "$TWiki::mainWebname.$TWiki::superAdminGroup" );
      TWiki::redirect( $query, $url );
      return;
    }
    $tmpl =~ s/\(preview\)/\(preview cmd=$saveCmd\)/go;
  }
  $tmpl =~ s/%CMD%/$saveCmd/go;

  # Note: don't believe cmd can _ever_ be repRev, coming from editaction
#    if( $saveCmd ne "repRev" ) {
  $text = "";
  ( $meta, $text ) = &TWiki::Store::readTopic( $webName, $topic );
      
  # parent setting
  my $theParent = $query->param( 'topicparent' ) || "";
  if( $theParent ) {
    $tmpl =~ s/%TOPICPARENT%/$theParent/go;
    $meta->put( "TOPICPARENT", ( "name" => $theParent ) );
  }
  $tmpl =~ s/%TOPICPARENT%/$theParent/;
  
  my $formTemplate = $query->param( "formtemplate" );
  if( $formTemplate ) {
    $meta->remove( "FORM" );
    $meta->put( "FORM", ( name => $formTemplate ) ) if( $formTemplate ne "none" );
    $tmpl =~ s/%FORMTEMPLATE%/$formTemplate/go;
  } else {
    $tmpl =~ s/%FORMTEMPLATE%//go;
  }
  
  my $unlock = "on";
  if ( $action eq "QuietSave") {
    $dontNotify = "checked";
  }
  if (($action eq "QuietSave") || ($action eq "Save")) {
    $text =~ s/ {3}/\t/go;
    my $error = &TWiki::Store::saveTopic( $webName, $topic, $text, $meta, $saveCmd, $unlock, $dontNotify );
    if ($error) {
      my $url = &TWiki::getOopsUrl( $webName, $topic, "oopssaveerr", $error );
      TWiki::redirect( $query, $url );
    }
    else {
      if ( $from =~ /_/ ) {
        $from =~ /(.*?)\#(.*)/;
        $from = "$1?nocache=on#$2";
      }
      my $viewUrl = "$TWiki::defaultUrlHost$TWiki::scriptUrlPath/view/";
      TWiki::redirect( $query, "$viewUrl$from" );
      return;
    }
    return;
  }
  
  TWiki::Plugins::afterEditHandler( $text, $topic, $webName );

  $ptext = $text;

  if( $meta->count( "FORM" ) ) {
    $formFields = &TWiki::Form::getFieldParams( $meta );
  }
  # repRev handling commented out
  #    } else {
  #        $text = $query->param( "text" ); # text to save
  #        ( $meta, $ptext ) = &TWiki::Store::_extractMetaData( $webName, $topic, $text );
  #    }
  
  $ptext =~ s/ {3}/\t/go;
  $ptext = &TWiki::handleCommonTags( $ptext, $topic );
  $ptext = &TWiki::getRenderedVersion( $ptext );

  # do not allow click on link before save:
  $ptext =~ s@(href=".*?")@href="%SCRIPTURLPATH%/oops%SCRIPTSUFFIX%/%WEB%/%TOPIC%\?template=oopspreview"@goi;
  $ptext = &TWiki::handleCommonTags( $ptext, $topic );

  $tmpl = &TWiki::handleCommonTags( $tmpl, $topic );
  $tmpl = &TWiki::handleMetaTags( $webName, $topic, $tmpl, $meta );
  $tmpl = &TWiki::getRenderedVersion( $tmpl );
  $tmpl =~ s/%TEXT%/$ptext/go;
  
  $text = &TWiki::encodeSpecialChars( $text );

  $tmpl =~ s/%HIDDENTEXT%/$text/go;
  $tmpl =~ s/%FORMFIELDS%/$formFields/go;
  $tmpl =~ s|</*nop/*>||goi;   # remove <nop> tags (PTh 06 Nov 2000)
  &TWiki::writeHeader( $query );
  print $tmpl;
}
