<?php // $Id: hotpotatoes.php,v 1.30 2005/07/10 16:14:15 yannoo Exp $
/*
==============================================================================
	Dokeos - elearning and course management software

	Copyright (c) 2004 Dokeos S.A.
	Copyright (c) 2003 Ghent University (UGent)
	Copyright (c) 2001 Universite catholique de Louvain (UCL)
	Copyright (c) Istvan Mandak

	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
==============================================================================
*/
/**
==============================================================================
*	Code for Hotpotatoes integration.
*
*	@author Istvan Mandak
*	@package dokeos.exercise
==============================================================================
*/

$finish 		= (!empty($_POST['finish'])?$_POST['finish']:0);
$imgcount		= (!empty($_POST['imgcount'])?$_POST['imgcount']:null);
$fld					= (!empty($_POST['fld'])?$_POST['fld']:null);

$langFile='exercice';
include('../inc/claro_init_global.inc.php');
include_once(api_get_library_path().'/fileUpload.lib.php');
include_once(api_get_library_path().'/document.lib.php');
$interbredcrump[]= array ("url"=>"./exercice.php", "name"=> get_lang('Exercices'));
$is_allowedToEdit=(!empty($is_courseAdmin)?$is_courseAdmin:false);

//$dbTable     = '`'.$_course['dbNameGlu']."document`";
$dbTable				= Database::get_course_document_table();
$baseServDir = $rootSys;
$baseServUrl = $urlAppend."/";
$document_sys_path = api_get_path(SYS_COURSE_PATH).$_course['path']."/document";
$uploadPath = "/HotPotatoes_files";

// if user is allowed to edit
if ($is_allowedToEdit)
{
	include_once("hotpotatoes.lib.php");
	//disable document parsing(?) - obviously deprecated
	$enableDocumentParsing=false;
	
	if(hotpotatoes_init($document_sys_path.$uploadPath))
	{//if the directory doesn't exist
		//create the "HotPotatoes" directory
		$doc_id = add_document($_course, '/HotPotatoes_files','folder',0,'HotPotatoes Files');
		//update properties in dbase (in any case)
		item_property_update($_course,TOOL_DOCUMENT,$doc_id,'FolderCreated',$_uid);
		//make invisible(in any case) - why?
		item_property_update($_course,TOOL_DOCUMENT,$doc_id,'invisible',$_uid);
	}
}

 /** display */
// if finish is set; it's because the user came from this script in the first place (displaying hidden "finish" field)
if(($is_allowedToEdit) && (($finish == 0) || ($finish == 2)))
//if(($is_allowedToEdit) )
{
	$nameTools = get_lang('HotPotatoesTests');

	//moved this down here as the upload handling functions give output
	if (isset($_POST['submit']))
	{
		//check that the submit button was pressed when the button had the "Download" value
		//This should be updated to "upload" here and on the button, and it would be better to
		// check something else than a string displayd on a button
		if (strcmp($_POST['submit'],get_lang('Download'))===0) 
		{
			/** el kell tarolni <- english please */
			include_once(api_get_library_path().'/fileManage.lib.php');
			/*======================================
				FILEMANAGER BASIC VARIABLES DEFINITION
				======================================*/
			include_once(api_get_library_path()."/pclzip/pclzip.lib.php");
			
			//@todo: this value should be moved to the platform admin section
			$maxFilledSpace = 100000000;
			
			//initialise $finish
			if (!isset($finish)) {$finish = 0;}
		
			//if the size is not defined, it's probably because there has been an error or no file was submitted
			if(!$_FILES['userFile']['size'])
			{
				$dialogBox .= get_lang('FileError').'<br />'.get_lang('Notice').' : '.get_lang('MaxFileSize').' '.ini_get('upload_max_filesize');
			}
			else
			{
				/* deprecated code
				if ($enableDocumentParsing==true)
				{ $enableDocumentParsing=false;
				$oke=1;}
				else { $oke = 0; }
				*/
				//$unzip = 'unzip';
				$unzip = 0;
				if(preg_match('/\.zip$/i',$_FILES['userFile']['name'])){
					//if it's a zip, allow zip upload
					$unzip = 1;
				}
				if ($finish==0)
				{		//generate new test folder if on first step of file upload
					$filename = replace_dangerous_char(trim($_FILES['userFile']['name']),'strict');	
					$fld = GenerateHpFolder($document_sys_path.$uploadPath."/");
					@mkdir($document_sys_path.$uploadPath."/".$fld, 0777);
					$doc_id = add_document($_course, '/HotPotatoes_files/'.$fld,'folder',0,$fld);
					item_property_update($_course,TOOL_DOCUMENT,$doc_id,'FolderCreated',$_uid);
				}
				else
				{ //it is not the first step... get the filename directly from the system params
					$filename = $_FILES['userFile']['name'];	
				}						
				
				/*if (treat_uploaded_file($_FILES['userFile'], $document_sys_path,
							$uploadPath."/".$fld, $maxFilledSpace, $unzip))*/
				$allow_output_on_success = false;
				if (handle_uploaded_document($_course,$_FILES['userFile'],$document_sys_path,$uploadPath."/".$fld,$_uid,null,null,$maxFilledSpace,$unzip,'',$allow_output_on_success))
				{
					
					if ($finish==2)
					{
						$checked = CheckImageName($imgparams,$filename);
						if ($checked)
						{ $imgcount = $imgcount-1; }
						else
						{ 
							$dialogBox .= $filename." ".get_lang('NameNotEqual');
							my_delete($document_sys_path.$uploadPath."/".$fld."/".$filename);
							update_db_info("delete", $uploadPath."/".$fld."/".$filename);
						}
						if ($imgcount==0)  // all image uploaded
						{
							$finish=1;
						}
					}
					else
					{ //if we are (still) on the first step of the upload process
						if ($finish==0)
						{ 
							$finish = 2;
							// get number and name of images from the files contents
							GetImgParams("/".$filename,$document_sys_path.$uploadPath."/".$fld,$imgparams,$imgcount);
							if ($imgcount==0) //there is no img link, so finish the upload process
							{ $finish = 1; }
							else //there is still one or more img missing
							{ $dialogBox .= get_lang('DownloadEnd'); }
						}
					}
					$newComment = "";
	
					$query = "UPDATE $dbTable SET comment='$newComment' WHERE path=\"".$uploadPath."/".$fld."/".$filename."\""; 
					/*, visibility='v' */
	
					api_sql_query($query,__FILE__,__LINE__);
					// "WHAT'S NEW" notification: update table item_property (previously last_tooledit)
					//update_last_tooledit($_course, $nameTools, $id, get_lang('new_document'), $_uid);
					item_property_update($_course, TOOL_QUIZ, $id, "QuizAdded", $_uid);
				}
				else
				{
					if ($finish==2)
					{
						// delete?
						//$dialogBox .= get_lang('NoImg');
					}
					$finish = 0;	// error
	
					if (api_failure::get_last_failure() == 'not_enough_space')
					{
						$dialogBox .= get_lang('NoSpace');
					}
					elseif (api_failure::get_last_failure() == 'php_file_in_zip_file')
					{
						$dialogBox .= get_lang('ZipNoPhp');
					}
	
				}
	
				/*		if ($oke==1)
				{ $enableDocumentParsing=true;  $oke=0;}
				*/
			}
		}
	}
	if ($finish == 1)
	{ /** ok -> send to main exercises page */
		header("Location: exercice.php");
		exit;
	} 
	
	Display::display_header($nameTools,"Exercise");
	$interbredcrump[]=array("url" => "exercice.php","name" => get_lang('Exercices'));
	/* -----*/
	?>

	<br />
	<table border="0" cellpadding="0" cellspacing="0" width="100%">
	<tr>
  	<td width="50%"><h3><?php echo $nameTools; ?></h3></td>
  	<td width="50%" align="right">
	  </td>
	</tr>
	</table>
	<table border="0" cellpadding="0" cellspacing="0" width="100%">
	<tr>

<?php

	if ($finish==2) //if we are in the img upload process
	{
	 $dialogBox.= get_lang('ImgNote_st').$imgcount.get_lang('ImgNote_en')."<br>";
		while(list($key,$string)=each($imgparams))
		{ 
			$dialogBox.=$string."; ";
		}
	}

	if ($dialogBox)
	{
		echo 	"<td>\n<!-- dialog box -->\n&nbsp;\n</td>\n";
		Display::display_normal_message($dialogBox); //main API
		echo	"</td>\n";
	}
	else
	{
		echo "<td>\n<!-- dialog box -->\n&nbsp;\n</td>\n";
	}

	/*--------------------------------------
			  UPLOAD SECTION
	 --------------------------------------*/
	echo	"<!-- upload  -->\n",
			"<td align=\"right\">\n",
			"<form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\" enctype=\"multipart/form-data\">\n",
			"<input type=\"hidden\" name=\"uploadPath\" value=\"\">\n",
			"<input type=\"hidden\" name=\"fld\" value=\"$fld\">\n",
			"<input type=\"hidden\" name=\"imgcount\" value=\"$imgcount\">\n",
			"<input type=\"hidden\" name=\"finish\" value=\"$finish\">\n";
	echo GenerateHiddenList($imgparams);
	if ($finish==0){ echo get_lang('DownloadFile');}
	else {echo get_lang('DownloadImg');}
	echo 	" : ",
			"<input type=\"file\" name=\"userFile\">\n",
			"<input type=\"submit\" name=\"submit\" value=\"".get_lang('Download')."\"><br/>\n";
?>
		</td>
	</tr>
	</table>

<?php

	Display::display_footer();
}
/*
else
{
	if ($finish == 1)
	{ // ok
		//include("exercice.php");
		header("Location: exercice.php");
	} 
	else
	{
	}
}
*/
?>
