#!/usr/bin/perl

use CGI ( "-utf8" );
use CGI::Carp qw(fatalsToBrowser);
use CGI qw/:standard/;
use CGI::Cookie;
use Encode qw(encode decode);
my $cgi = CGI->new;
$cgi->header( -charset=> 'utf-8' );
my $fname = $cgi->param("f");
my $contents = $cgi->param("editor");
my $pass = $cgi->param("password");
if(defined($pass)) {
	if($pass eq 'test') {
		$cookie = $cgi->cookie(-name=>'id', -value=>'test', -expires=>'+24h', -path=>'/');
		print $cgi->header(-cookie=>$cookie);
		print '<META http-equiv="refresh" content="0;URL='.$ENV{'REQUEST_URI'}.'"> ';
	}
}
print $cgi->header('text/html');
if(!$cgi->cookie('id')) {
print <<HTML;

<form method="post" action="">
	<center>
		<div style="margin:100px;width:400px;padding:15px;">
			Password: <input type="password" name="password"> <input type="submit" value="Login">
		</div>
	</center>
</form>

HTML
exit;
}else{
	editor_html();
}

sub editor_html
{
print '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';	
if(defined($contents)) {
	$fname = $cgi->param("file_name");
	open OUT, ">:utf8", $fname or die "Cannot open $fname for write :$!";
	print OUT "$contents";
	close OUT;
}
if(defined($fname)) {
	$data=readMyFile($fname);
print <<HTML;


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<head>
	<title>HTML Editor</title>
	<meta charset="utf-8">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<script src="../RoCCIJa/js/ckeditor/ckeditor.js" charset="utf-8"></script>
	<link href="../RoCCIJa/js/ckeditor/sample.css" rel="stylesheet">
</head>

<form action="" method="post">
		<input type="hidden" name="file_name" value="$fname">
		<textarea cols="100" id="editor1" name="editor1" rows="60">
			$data
		</textarea>
		<script>CKEDITOR.replace( 'editor1', {filebrowserUploadUrl: 'http://www.romaniatabi.jp/RoCCIJa/js/ckeditor/uploader.php'});</script>
		<p><input type="submit" value="Submit"></p>
	</form>

HTML

}
}

sub readMyFile
{
	my $myFile= shift;
	my $return='';
	open(FILE1, $myFile);
	while(<FILE1>){
		$return.= $_;
	}
	return $return;
}