<?php // $Id: create_document.php,v 1.60 2005/06/28 09:45:28 olivierb78 Exp $
/*
==============================================================================
	Dokeos - elearning and course management software

	Copyright (c) 2004 Dokeos S.A.
	Copyright (c) 2003 University of Ghent (UGent)
	Copyright (c) 2001 Universite catholique de Louvain (UCL)
	Copyright (c) Olivier Brouckaert

	For a full list of contributors, see "credits.txt".
	The full license can be read in "license.txt".

	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.

	See the GNU General Public License for more details.

	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
==============================================================================
*/
/**
==============================================================================
*	This file allows creating new html documents with an online WYSIWYG html
*	editor.
*
*	@package dokeos.document
==============================================================================
*/

/*
==============================================================================
		INIT SECTION
==============================================================================
*/

$langFile = "document";

include('../inc/claro_init_global.inc.php');
include (api_get_library_path().'/fileUpload.lib.php');
include (api_get_library_path().'/document.lib.php');
include (api_get_library_path().'/groupmanager.lib.php');
$nameTools = get_lang('CreateDocument');


/*
-----------------------------------------------------------
	Constants and variables
-----------------------------------------------------------
*/
$dbTable = $_course['dbNameGlu']."document";

$formSent = $_REQUEST['formSent'];
$filename = $_REQUEST['filename'];
$texte  = $_REQUEST['texte'];
$dir = $_GET['dir']; // please do not modify this dirname formatting

/*
==============================================================================
		MAIN CODE
==============================================================================
*/
if(strstr($dir,'..'))
{
	$dir='/';
}

if($dir[0] == '.')
{
	$dir=substr($dir,1);
}

if($dir[0] != '/')
{
	$dir='/'.$dir;
}

if($dir[strlen($dir)-1] != '/')
{
	$dir.='/';
}

$filepath=api_get_path('SYS_COURSE_PATH').$_course['path'].'/document'.$dir;

if(!is_dir($filepath))
{
	$filepath=api_get_path('SYS_COURSE_PATH').$_course['path'].'/document/';

	$dir='/';
}

/**************************************************/
$to_group_id = 0;

if(isset($_SESSION['_gid']) && $_SESSION['_gid']!='')
{
	$req_gid = '&amp;gidReq='.$_SESSION['_gid'];
	$interbredcrump[]= array ("url"=>"../group/group_space.php?gidReq=".$_SESSION['_gid'], "name"=> get_lang('GroupSpace'));
	$noPHP_SELF=true;
	$to_group_id = $_SESSION['_gid'];
	$group = GroupManager::get_group_properties($to_group_id);
	$path = explode('/',$dir);
	if( '/'.$path[1] != $group['directory'])
	{
		api_not_allowed();
	}
}
$interbredcrump[]=array("url"=>"./document.php?curdirpath=".urlencode($_GET['dir']).$req_gid, "name"=> get_lang('Documents'));

if (! $is_allowed_in_course) api_not_allowed();

$is_allowedToEdit=$is_courseAdmin;

if($is_allowedToEdit || $_SESSION['group_member_with_upload_rights'] )
{
	if($formSent)
	{
		$filename=stripslashes($filename);

		$texte=trim(str_replace(array("\r","\n"),"",stripslashes($texte)));

		if(!strstr($texte,'/css/frames.css'))
		{
			$texte=str_replace('</title></head>','</title><link rel="stylesheet" href="./css/frames.css" type="text/css" /></head>',$texte);
		}

		$filename=replace_dangerous_char($filename);

		if($extension != 'htm' && $extension != 'html')
		{
			$extension='html';
		}

		if(empty($texte))
		{
			$msgError=get_lang('NoText');
		}
		elseif(empty($filename))
		{
			$msgError=get_lang('NoFileName');
		}
		elseif(file_exists($filepath.$filename.'.'.$extension))
		{
			$msgError=get_lang('FileExists');
		}
		else
		{
			if($fp=@fopen($filepath.$filename.'.'.$extension,'w'))
			{
				$path_to_remove=api_get_path('WEB_COURSE_PATH').$_course['path'].'/document'.$dir;

				$texte=str_replace($path_to_remove,'./',$texte);

				$texte=str_replace('mp3player.swf?son='.urlencode($path_to_remove),'mp3player.swf?son=.%2F',$texte);

				fputs($fp,$texte);

				fclose($fp);

				if(!is_dir($filepath.'css'))
				{
					mkdir($filepath.'css',0777);

					$doc_id=add_document($_course,$dir.'css','folder',0,'css');

					item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', $_uid);
					item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_uid);
				}

				if(!is_file($filepath.'css/frames.css'))
				{
					copy(api_get_path(SYS_CODE_PATH).'css/frames.css',$filepath.'css/frames.css');

					$doc_id=add_document($_course,$dir.'css/frames.css','file',filesize($filepath.'css/frames.css'),'frames.css');

					item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_uid);
					item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', $_uid);
				}

				$file_size = filesize($filepath.$filename.'.'.$extension);
				$save_file_path=$dir.$filename.'.'.$extension;

				// "WHAT'S NEW" notification: update table item_property (previously last_tooledit)
				//set_default_settings($dir,$filename.'.'.$extension);// put in document database
				//update_last_tooledit($_course, get_lang('Doc'), mysql_insert_id(), get_lang('_new_document'), $_uid);
				$document_id = add_document($_course,$save_file_path,'file',$file_size,$filename);
				if($document_id)
				{
					item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $_uid,$to_group_id);

    				//update parent folders
					item_property_update_on_folder($_course,$_GET['dir'],$_uid);

	                $new_comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
                	$new_title = isset($_POST['title']) ? trim($_POST['title']) : '';
                	if ($new_comment || $new_title)
                	{
                    	$TABLE_DOCUMENT  = "`".$_course['dbNameGlu']."document`"; $ct = '';
                    	if ($new_comment) $ct .= ", comment='$new_comment'";
                    	if ($new_title)   $ct .= ", title='$new_title'";
                    	api_sql_query("UPDATE $TABLE_DOCUMENT SET" . substr($ct, 1) .
                    	    " WHERE id = '$document_id'", __FILE__, __LINE__);
            	    }

					header('Location: document.php?curdirpath='.urlencode($_GET['dir']));
					exit();
				}
			}
			else
			{
				$msgError=get_lang('Impossible');
			}
		}
	}
}

if(file_exists($filepath.$doc))
{
	$extension=explode('.',$doc);
	$extension=$extension[sizeof($extension)-1];

	$filename=str_replace('.'.$extension,'',$doc);

	$extension=strtolower($extension);

	if(!in_array($extension,array('html','htm')))
	{
		$extension=$filename=$texte='';
	}
	else
	{
		$texte=file($filepath.$doc);
	}
}

/*
-----------------------------------------------------------
	Header
-----------------------------------------------------------
*/
Display::display_header($nameTools,"Doc");

include(api_get_library_path().'/events.lib.inc.php');

event_access_tool(TOOL_DOCUMENT);
?>

<br/>

<h3 style="margin-top: 0; margin-bottom: 0"><?php echo get_lang('CreateDocument'); ?></h3>

<br/>

<?php
if(!empty($msgError))
{
	Display::display_normal_message($msgError); //main API
}
?>

<form name="formEdit" action="<?php echo $_SERVER['PHP_SELF']; ?>?dir=<?php echo urlencode($_GET['dir']); ?>" method="post" style="margin:0px;" onsubmit="javascript:if(document.formEdit.texte.value.toLowerCase().indexOf('<html>') == -1) { document.formEdit.texte.value='&lt;html&gt;&lt;head&gt;&lt;title&gt;'+document.formEdit.filename.value+'.html&lt;/title&gt;&lt;/head&gt;&lt;body&gt;'+document.formEdit.texte.value+'&lt;/body&gt;&lt;/html&gt;'; }">
<input type="hidden" name="formSent" value="1" />

<table border="0" cellpadding="5" cellspacing="0" width="100%">
 <tr>
  <td width="10%" nowrap="nowrap"><?php echo get_lang('FileName'); ?> :</td>
  <td width="90%">
  <?php
  if( isset($group))
  {
  		$dir = explode('/',$dir);
  		unset($dir[0]);
  		unset($dir[1]);
  		$dir = implode('/',$dir);
  }
  echo $dir;
  ?>
	<input type="text" name="filename" size="30" value="<?php if(!empty($filename)) echo htmlspecialchars($filename); ?>" />
	<input type="hidden" name="extension" value="html" />.html
  </td>
 </tr>

  <?php
  if(get_setting('use_document_title')=='true')
  {
	?>
    <tr>
    <td><?php echo get_lang('Title');?></td>
    <td><input type="text" size="30" name="title" style="width:300px;"></td>
    </tr>
	<?php
  }
  ?>

 <tr>
  <td colspan="2">

<script type="text/javascript">
<!--
_document_path='<?php echo api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir; ?>';
//-->
</script>

<?php
    api_disp_html_area('texte',isset($_POST['texte'])?stripslashes($_POST['texte']):$texte,'400px');
?>

  </td>
 </tr>
  <tr>
   <td valign="top">
    <?php echo get_lang('Comment');?>
	</td>
	<td>
    <textarea rows="3" cols="30" name="comment" wrap="virtual" style="width:300px;"></textarea>
  </td>
 </tr>
 <tr>
  <td colspan="2">
    <input type="submit" value="<?php echo get_lang('Ok'); ?>" />
  </td>
 </tr>
</table>

</form>

<?php
Display::display_footer();
?>
