Task #2560 - On HotPotatoes import the test's title is retrieved from the (html) title tag.

skala
Ivan Tcholakov 15 years ago
parent f16160d059
commit 81eb7fe847
  1. 531
      main/exercice/hotpotatoes.lib.php
  2. 357
      main/exercice/hotpotatoes.php
  3. 92
      main/inc/lib/text.lib.php

@ -2,9 +2,9 @@
/* For licensing terms, see /license.txt */
/**
* Code library for HotPotatoes integration.
* @package chamilo.exercise
* @author Istvan Mandak (original author)
* Code library for HotPotatoes integration.
* @package chamilo.exercise
* @author Istvan Mandak (original author)
*/
$dbTable = Database::get_course_table(TABLE_DOCUMENT); // TODO: This is a global variable with too simple name, conflicts are possible. Better eliminate it. Correct the test unit too.
@ -13,109 +13,112 @@ $dbTable = Database::get_course_table(TABLE_DOCUMENT); // TODO: This is a global
* Creates a hotpotato directory.
*
* If a directory of that name already exists, don't create any. If a file of that name exists, remove it and create a directory.
* @param string Wanted path
* @return boolean Always true so far
* @param string Wanted path
* @return boolean Always true so far
*/
function hotpotatoes_init($base_work_dir) {
//global $_course, $_user;
$document_path = $base_work_dir.'/';
if (!is_dir($document_path)) {
if (is_file($document_path)) {
@unlink($document_path);
}
@mkdir($document_path, api_get_permissions_for_new_directories());
return true;
} else {
return false;
}
//why create a .htaccess here?
//if (!is_file($document_path.".htacces"))
//{
// if (!($fp = fopen($document_path.".htaccess", "w"))) {
// }
// $str = "order deny,allow\nallow from all";
// if (!fwrite($fp,$str)) { }
//}
//global $_course, $_user;
$document_path = $base_work_dir.'/';
if (!is_dir($document_path)) {
if (is_file($document_path)) {
@unlink($document_path);
}
@mkdir($document_path, api_get_permissions_for_new_directories());
return true;
} else {
return false;
}
//why create a .htaccess here?
//if (!is_file($document_path.".htacces"))
//{
// if (!($fp = fopen($document_path.".htaccess", "w"))) {
// }
// $str = "order deny,allow\nallow from all";
// if (!fwrite($fp,$str)) { }
//}
}
/**
* Gets the title of the quizz file given as parameter.
* @param string File name
* @param string File path
* @return string The exercise title
* @param string File name
* @param string File path
* @return string The exercise title
*/
function GetQuizName($fname, $fpath) {
$title = GetComment($fname);
$title = GetComment($fname);
if ($title == '') {
if (file_exists($fpath.$fname)) {
if (!($fp = fopen($fpath.$fname, 'r'))) {
//die('Could not open Quiz input.');
return basename($fname);
}
if (trim($title) == '') {
if (file_exists($fpath.$fname)) {
if (!($fp = @fopen($fpath.$fname, 'r'))) {
//die('Could not open Quiz input.');
return basename($fname);
}
$contents = fread($fp, filesize($fpath.$fname));
fclose($fp);
$contents = @fread($fp, filesize($fpath.$fname));
@fclose($fp);
$title = api_get_title_html($contents);
}
}
return (string)$title;
$title = api_get_title_html($contents);
}
}
if ($title == '') {
$title = basename($fname);
}
return (string)$title;
}
/**
* Gets the comment about a file from the corresponding database record.
* @param string File path
* @return string Comment from the database record
* @param string File path
* @return string Comment from the database record
* Added conditional to the table if is empty.
*/
function GetComment($path, $course_code = '') {
global $dbTable;
global $dbTable;
if (!empty($course_code)) {
$course_info = api_get_course_info($course_code);
$dbTable = Database::get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
}
$path = Database::escape_string($path);
$query = "SELECT comment FROM $dbTable WHERE path='$path'";
$result = Database::query($query);
if (!empty($course_code)) {
$course_info = api_get_course_info($course_code);
$dbTable = Database::get_course_table(TABLE_DOCUMENT, $course_info['dbName']);
}
$path = Database::escape_string($path);
$query = "SELECT comment FROM $dbTable WHERE path='$path'";
$result = Database::query($query);
while ($row = Database::fetch_array($result)) {
return $row[0];
}
return '';
while ($row = Database::fetch_array($result)) {
return $row[0];
}
return '';
}
/**
* Sets the comment in the database for a particular path.
* @param string File path
* @param string Comment to set
* @return string Result of the database operation (Database::query will output some message directly on error anyway)
* @param string File path
* @param string Comment to set
* @return string Result of the database operation (Database::query will output some message directly on error anyway)
*/
function SetComment($path, $comment) {
global $dbTable;
$path = Database::escape_string($path);
$comment = Database::escape_string($comment);
$query = "UPDATE $dbTable SET comment='$comment' WHERE path='$path'";
$result = Database::query($query);
return "$result";
global $dbTable;
$path = Database::escape_string($path);
$comment = Database::escape_string($comment);
$query = "UPDATE $dbTable SET comment='$comment' WHERE path='$path'";
$result = Database::query($query);
return "$result";
}
/**
* Reads the file contents into a string.
* @param string Urlencoded path
* @return string The file contents or false on security error
* @param string Urlencoded path
* @return string The file contents or false on security error
*/
function ReadFileCont($full_file_path) {
if (Security::check_abs_path(dirname($full_file_path).'/', api_get_path(SYS_COURSE_PATH))) {
if (is_file($full_file_path)) {
if (!($fp = fopen(urldecode($full_file_path), 'r'))) {
return '';
}
$contents = fread($fp, filesize($full_file_path));
fclose($fp);
return $contents;
if (!($fp = fopen(urldecode($full_file_path), 'r'))) {
return '';
}
$contents = fread($fp, filesize($full_file_path));
fclose($fp);
return $contents;
}
}
return false;
@ -123,8 +126,8 @@ function ReadFileCont($full_file_path) {
/**
* Writes the file contents into the given filepath.
* @param string Urlencoded path
* @param string The file contents
* @param string Urlencoded path
* @param string The file contents
* @return boolean True on success, false on security error
*/
function WriteFileCont($full_file_path, $content) {
@ -134,10 +137,10 @@ function WriteFileCont($full_file_path, $content) {
// Check if this is not an attack, trying to upload a php file or something like that.
if (basename($full_file_path) != Security::filter_filename(basename($full_file_path))) { return false; }
if (!($fp = fopen(urldecode($full_file_path), 'w'))) {
//die('Could not open Quiz input.');
}
fwrite($fp, $content);
fclose($fp);
//die('Could not open Quiz input.');
}
fwrite($fp, $content);
fclose($fp);
return true;
}
return false;
@ -145,279 +148,279 @@ function WriteFileCont($full_file_path, $content) {
/**
* Gets the name of an img whose path is given (without directories or extensions).
* @param string An image tag (<img src="...." ...>)
* @return string The image file name or an empty string
* @param string An image tag (<img src="...." ...>)
* @return string The image file name or an empty string
*/
function GetImgName($imgtag) {
// Select src tag from img tag.
$match = array();
//preg_match('/(src=(["\'])1.*(["\'])1)/i', $imgtag, $match); //src
preg_match('/src(\s)*=(\s)*[\'"]([^\'"]*)[\'"]/i', $imgtag, $match); //get the img src as contained between " or '
//list($key, $srctag) = each($match);
$src = $match[3];
//$src = substr($srctag, 5, (strlen($srctag) - 7));
if (stristr($src, 'http') === false) {
$match = array();
//preg_match('/(src=(["\'])1.*(["\'])1)/i', $imgtag, $match); //src
preg_match('/src(\s)*=(\s)*[\'"]([^\'"]*)[\'"]/i', $imgtag, $match); //get the img src as contained between " or '
//list($key, $srctag) = each($match);
$src = $match[3];
//$src = substr($srctag, 5, (strlen($srctag) - 7));
if (stristr($src, 'http') === false) {
// Valid or invalid image name.
if ($src == '') {
return '';
} else {
$tmp_src = basename($src) ;
if ($tmp_src == '') {
return $src;
} else {
return $tmp_src;
}
}
} else {
if ($src == '') {
return '';
} else {
$tmp_src = basename($src) ;
if ($tmp_src == '') {
return $src;
} else {
return $tmp_src;
}
}
} else {
// The img tag contained "http", which means it is probably external. Ignore it.
return '';
}
return '';
}
}
/**
* Gets the source path of an image tag.
* @param string An image tag
* @return string The image source or ""
* @param string An image tag
* @return string The image source or ""
*/
function GetSrcName($imgtag) {
// Select src tag from img tag.
$match = array();
preg_match("|(src=\".*\" )|U", $imgtag, $match); //src
list($key, $srctag) = each($match);
$src = substr($srctag, 5, (strlen($srctag) - 7));
if (stristr($src, 'http') === false) {
$match = array();
preg_match("|(src=\".*\" )|U", $imgtag, $match); //src
list($key, $srctag) = each($match);
$src = substr($srctag, 5, (strlen($srctag) - 7));
if (stristr($src, 'http') === false) {
// valid or invalid image name
return $src;
} else {
return '';
}
return $src;
} else {
return '';
}
}
/**
* Gets the image parameters from an image path.
* @param string File name
* @param string File path
* @param reference Reference to a list of image parameters (emptied, then used to return results)
* @param reference Reference to a counter of images (emptied, then used to return results)
* @param string File name
* @param string File path
* @param reference Reference to a list of image parameters (emptied, then used to return results)
* @param reference Reference to a counter of images (emptied, then used to return results)
*/
function GetImgParams($fname, $fpath, &$imgparams, &$imgcount) {
// Select img tags from context.
$imgparams = array();
//phpinfo();
$contents = ReadFileCont("$fpath"."$fname");
$matches = array();
preg_match_all('(<img .*>)', $contents, $matches);
$imgcount = 0;
while (list($int, $match) = each($matches)) {
// Each match consists of a key and a value.
while (list($key, $imgtag) = each($match)) {
$imgname = GetImgName($imgtag);
if ($imgname != '' && !in_array($imgname, $imgparams)) {
array_push($imgparams, $imgname); // name (+ type) of the images in the html test
$imgcount = $imgcount + 1; // number of images in the html test
}
}
}
$imgparams = array();
//phpinfo();
$contents = ReadFileCont("$fpath"."$fname");
$matches = array();
preg_match_all('(<img .*>)', $contents, $matches);
$imgcount = 0;
while (list($int, $match) = each($matches)) {
// Each match consists of a key and a value.
while (list($key, $imgtag) = each($match)) {
$imgname = GetImgName($imgtag);
if ($imgname != '' && !in_array($imgname, $imgparams)) {
array_push($imgparams, $imgname); // name (+ type) of the images in the html test
$imgcount = $imgcount + 1; // number of images in the html test
}
}
}
}
/**
* Generates a list of hidden fields with the image params given as parameter to this function.
* @param array List of image parameters
* @return string String containing the hidden parameters built from the list given
* @param array List of image parameters
* @return string String containing the hidden parameters built from the list given
*/
function GenerateHiddenList($imgparams) {
$list = '';
if (is_array($imgparams)) {
$list = '';
if (is_array($imgparams)) {
while (list($int, $string) = each($imgparams)) {
$list .= "<input type=\"hidden\" name=\"imgparams[]\" value=\"$string\" />\n";
}
}
return $list;
$list .= "<input type=\"hidden\" name=\"imgparams[]\" value=\"$string\" />\n";
}
}
return $list;
}
/**
* Searches for a node in the given array.
* @param reference Reference to the array to search
* @param string Node we are looking for in the array
* @return mixed Node name or false if not found
* @param reference Reference to the array to search
* @param string Node we are looking for in the array
* @return mixed Node name or false if not found
*/
function myarraysearch(&$array, $node) {
$match = false;
$tmp_array = array();
for ($i = 0; $i < count($array); $i++) {
if (!strcmp($array[$i], $node)) {
$match = $node;
} else {
$match = false;
$tmp_array = array();
for ($i = 0; $i < count($array); $i++) {
if (!strcmp($array[$i], $node)) {
$match = $node;
} else {
array_push($tmp_array, $array[$i]);
}
}
$array = $tmp_array;
return $match;
}
$array = $tmp_array;
return $match;
}
/**
* Searches an image name into an array.
* @param reference Reference to an array to search
* @param string String to look for
* @return mixed String given if found, false otherwise
* @uses myarraysearch This function is just an additional layer on the myarraysearch() function
* @param reference Reference to an array to search
* @param string String to look for
* @return mixed String given if found, false otherwise
* @uses myarraysearch This function is just an additional layer on the myarraysearch() function
*/
function CheckImageName(&$imgparams, $string) {
$checked = myarraysearch($imgparams, $string);
return $checked;
$checked = myarraysearch($imgparams, $string);
return $checked;
}
/**
* Replaces an image tag by ???
* @param string The content to replace
* @return string The modified content
* @param string The content to replace
* @return string The modified content
*/
function ReplaceImgTag($content) {
$newcontent = $content;
$matches = array();
preg_match_all('(<img .*>)', $content, $matches);
$imgcount = 0;
while (list($int, $match) = each($matches)) {
while (list($key, $imgtag) = each($match)) {
$imgname = GetSrcName($imgtag);
if ($imgname == '') {} // Valid or invalid image name.
else {
$newcontent = $content;
$matches = array();
preg_match_all('(<img .*>)', $content, $matches);
$imgcount = 0;
while (list($int, $match) = each($matches)) {
while (list($key, $imgtag) = each($match)) {
$imgname = GetSrcName($imgtag);
if ($imgname == '') {} // Valid or invalid image name.
else {
$prehref = $imgname;
$posthref = basename($imgname);
$newcontent = str_replace($prehref, $posthref, $newcontent);
}
}
}
return $newcontent;
$prehref = $imgname;
$posthref = basename($imgname);
$newcontent = str_replace($prehref, $posthref, $newcontent);
}
}
}
return $newcontent;
}
/**
* Fills the folder name up to a certain length with "0".
* @param string Original folder name
* @param integer Length to reach
* @return string Modified folder name
* @param string Original folder name
* @param integer Length to reach
* @return string Modified folder name
*/
function FillFolderName($name, $nsize) {
$str = '';
for ($i = 0; $i < $nsize - strlen($name); $i++) {
$str .= '0';
}
$str .= $name;
return $str;
$str = '';
for ($i = 0; $i < $nsize - strlen($name); $i++) {
$str .= '0';
}
$str .= $name;
return $str;
}
/**
* Generates the HotPotato folder tree.
* @param string Folder path
* @return string Folder name (modified)
* @param string Folder path
* @return string Folder name (modified)
*/
function GenerateHpFolder($folder) {
$filelist = array();
if ($dir = @opendir($folder)) {
while (($file = readdir($dir)) !== false) {
if ($file != '.') {
if ($file != '..') {
$full_name = $folder.'/'.$file;
if (is_dir($full_name)) {
$filelist[] = $file;
}
}
}
}
}
$w = 0;
do {
$name = FillFolderName(mt_rand(1, 99999), 6);
$checked = myarraysearch($filelist, $name);
// As long as we find the name in the array, continue looping. As soon as we have a new element, quit.
if ($checked) { $w = 1; }
else { $w = 0; }
} while ($w == 1);
$filelist = array();
if ($dir = @opendir($folder)) {
while (($file = readdir($dir)) !== false) {
if ($file != '.') {
if ($file != '..') {
$full_name = $folder.'/'.$file;
if (is_dir($full_name)) {
$filelist[] = $file;
}
}
}
}
}
$w = 0;
do {
$name = FillFolderName(mt_rand(1, 99999), 6);
$checked = myarraysearch($filelist, $name);
// As long as we find the name in the array, continue looping. As soon as we have a new element, quit.
if ($checked) { $w = 1; }
else { $w = 0; }
} while ($w == 1);
return $name;
return $name;
}
/**
* Gets the folder name (strips down path).
* @param string Path
* @return string Folder name stripped down
* @param string Path
* @return string Folder name stripped down
*/
function GetFolderName($fname) {
$name = explode('/', $fname);
$name = $name[sizeof($name) - 2];
return $name;
$name = explode('/', $fname);
$name = $name[sizeof($name) - 2];
return $name;
}
/**
* Gets the folder path (withouth the name of the folder itself) ?
* @param string Path
* @return string Path stripped down
* @param string Path
* @return string Path stripped down
*/
function GetFolderPath($fname) {
$str = '';
$name = explode('/', $fname);
for ($i = 0; $i < sizeof($name) - 1; $i++) {
$str = '';
$name = explode('/', $fname);
for ($i = 0; $i < sizeof($name) - 1; $i++) {
$str = $str.$name[$i].'/';
}
return $str;
return $str;
}
/**
* Checks if there are subfolders.
* @param string Path
* @return integer 1 if a subfolder was found, 0 otherwise
* @param string Path
* @return integer 1 if a subfolder was found, 0 otherwise
*/
function CheckSubFolder($path) {
$folder = GetFolderPath($path);
$dflag = 0;
if ($dir = @opendir($folder)) {
while (($file = readdir($dir)) !== false) {
if ($file != '.') {
if ($file != '..') {
$full_name = $folder.'/'.$file;
if (is_dir($full_name)) {
$dflag = 1; // first directory
}
}
}
}
}
return $dflag;
$folder = GetFolderPath($path);
$dflag = 0;
if ($dir = @opendir($folder)) {
while (($file = readdir($dir)) !== false) {
if ($file != '.') {
if ($file != '..') {
$full_name = $folder.'/'.$file;
if (is_dir($full_name)) {
$dflag = 1; // first directory
}
}
}
}
}
return $dflag;
}
/**
* Hotpotato Garbage Collector
* @param string Path
* @param integer Flag
* @param integer User id
* @return void No return value, but echoes results
* @param string Path
* @param integer Flag
* @param integer User id
* @return void No return value, but echoes results
*/
function HotPotGCt($folder, $flag, $user_id) {
// Garbage Collector
$filelist = array();
if ($dir = @opendir($folder)) {
while (($file = readdir($dir)) !== false) {
if ($file != '.') {
if ($file != '..') {
$full_name = $folder.'/'.$file;
if (is_dir($full_name)) {
HotPotGCt($folder.'/'.$file, $flag, $user_id);
} else {
$filelist[] = $file;
}
}
}
}
closedir($dir);
}
while (list($key, $val) = each($filelist)) {
if (stristr($val, $user_id.'.t.html')) {
if ($flag == 1) {
my_delete($folder.'/'.$val);
} else {
echo $folder.'/'.$val.'<br />';
}
}
}
$filelist = array();
if ($dir = @opendir($folder)) {
while (($file = readdir($dir)) !== false) {
if ($file != '.') {
if ($file != '..') {
$full_name = $folder.'/'.$file;
if (is_dir($full_name)) {
HotPotGCt($folder.'/'.$file, $flag, $user_id);
} else {
$filelist[] = $file;
}
}
}
}
closedir($dir);
}
while (list($key, $val) = each($filelist)) {
if (stristr($val, $user_id.'.t.html')) {
if ($flag == 1) {
my_delete($folder.'/'.$val);
} else {
echo $folder.'/'.$val.'<br />';
}
}
}
}

@ -2,9 +2,9 @@
/* For licensing terms, see /license.txt */
/**
* Code for HotPotatoes integration.
* @package chamilo.exercise
* @author Istvan Mandak (original author)
* Code for HotPotatoes integration.
* @package chamilo.exercise
* @author Istvan Mandak (original author)
*/
@ -26,18 +26,18 @@ $this_section = SECTION_COURSES;
// Access restriction: only teachers are allowed here.
if (!api_is_allowed_to_edit(null, true)) {
api_not_allowed();
api_not_allowed();
}
if (isset($_SESSION['gradebook'])) {
$gradebook = $_SESSION['gradebook'];
$gradebook = $_SESSION['gradebook'];
}
if (!empty($gradebook) && $gradebook == 'view') {
$interbreadcrumb[] = array(
'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
'name' => get_lang('ToolGradebook')
);
$interbreadcrumb[] = array(
'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
'name' => get_lang('ToolGradebook')
);
}
// The breadcrumbs.
$interbreadcrumb[] = array('url' => './exercice.php', 'name' => get_lang('Exercices'));
@ -45,28 +45,28 @@ $interbreadcrumb[] = array('url' => './exercice.php', 'name' => get_lang('Exerci
$is_allowedToEdit = api_is_allowed_to_edit(null, true);
// Database table definitions.
$dbTable = Database::get_course_table(TABLE_DOCUMENT);
$dbTable = Database::get_course_table(TABLE_DOCUMENT);
// Setting some variables.
$document_sys_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
$uploadPath = '/HotPotatoes_files';
$finish = (!empty($_POST['finish']) ? $_POST['finish'] : 0);
$imgcount = (!empty($_POST['imgcount']) ? $_POST['imgcount'] : null);
$fld = (!empty($_POST['fld']) ? $_POST['fld'] : null);
$finish = (!empty($_POST['finish']) ? $_POST['finish'] : 0);
$imgcount = (!empty($_POST['imgcount']) ? $_POST['imgcount'] : null);
$fld = (!empty($_POST['fld']) ? $_POST['fld'] : null);
// If user is allowed to edit...
if (api_is_allowed_to_edit(null, true)) {
// 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, get_lang('HotPotatoesFiles'));
// Update properties in dbase (in any case).
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
// Make invisible (in any case) - why?
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id());
}
// 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, get_lang('HotPotatoesFiles'));
// Update properties in dbase (in any case).
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
// Make invisible (in any case) - why?
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'invisible', api_get_user_id());
}
}
/** Display */
@ -74,163 +74,162 @@ if (api_is_allowed_to_edit(null, true)) {
// If finish is set; it's because the user came from this script in the first place (displaying hidden "finish" field).
if ((api_is_allowed_to_edit(null, true)) && (($finish == 0) || ($finish == 2))) {
$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('Send')) === 0) {
//@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('SendFileError').'<br />'.get_lang('Notice').' : '.get_lang('MaxFileSize').' '.ini_get('upload_max_filesize');
} else {
/* deprecated code
if ($enableDocumentParsing)
{ $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.'/');
$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('Send')) === 0) {
//@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('SendFileError').'<br />'.get_lang('Notice').' : '.get_lang('MaxFileSize').' '.ini_get('upload_max_filesize');
} else {
/* deprecated code
if ($enableDocumentParsing)
{ $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.'/');
$doc_id = add_document($_course, '/HotPotatoes_files/'.$fld, 'folder', 0, $fld);
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
@mkdir($document_sys_path.$uploadPath.'/'.$fld, api_get_permissions_for_new_directories());
$doc_id = add_document($_course, '/HotPotatoes_files/'.$fld, 'folder', 0, $fld);
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
} 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, api_get_user_id(), null, null, $maxFilledSpace, $unzip, '', $allow_output_on_success)) {
if ($finish == 2) {
$imgparams = $_POST['imgparams'];
$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' */
Database::query($query);
api_item_property_update($_course, TOOL_QUIZ, $id, 'QuizAdded', api_get_user_id());
} 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?'.api_get_cidreq());
exit;
}
Display::display_header($nameTools, get_lang('Exercise'));
echo '<div class="actions">';
echo '<a href="exercice.php?show=test">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList')) . get_lang('GoBackToQuestionList') . '</a>';
echo '</div>';
if ($finish==2) { // If we are in the img upload process.
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
@mkdir($document_sys_path.$uploadPath.'/'.$fld, api_get_permissions_for_new_directories());
$doc_id = add_document($_course, '/HotPotatoes_files/'.$fld, 'folder', 0, $fld);
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
} 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, api_get_user_id(), null, null, $maxFilledSpace, $unzip, '', $allow_output_on_success)) {
if ($finish == 2) {
$imgparams = $_POST['imgparams'];
$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'); }
}
}
$title = @htmlspecialchars(GetQuizName($filename, $document_sys_path.$uploadPath.'/'.$fld.'/'), ENT_COMPAT, api_get_system_encoding());
$query = "UPDATE $dbTable SET comment='".Database::escape_string($title)."' WHERE path=\"".$uploadPath."/".$fld."/".$filename."\"";
Database::query($query);
api_item_property_update($_course, TOOL_QUIZ, $id, 'QuizAdded', api_get_user_id());
} 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?'.api_get_cidreq());
exit;
}
Display::display_header($nameTools, get_lang('Exercise'));
echo '<div class="actions">';
echo '<a href="exercice.php?show=test">' . Display :: return_icon('back.png', get_lang('GoBackToQuestionList')) . get_lang('GoBackToQuestionList') . '</a>';
echo '</div>';
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) {
Display::display_normal_message($dialogBox, false);
}
/* UPLOAD SECTION */
echo "<!-- upload -->\n",
"<form action=\"".api_get_self()."?".api_get_cidreq()."\" 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('Send')."\"><br/>\n";*/
//Display::display_icon('hotpotatoes.jpg','',array('align'=> 'right', 'style' => 'position: absolute; padding-top: 30px; margin-left: 500px;'));
echo '<div class="row"><div class="form_header">'.$nameTools.'</div></div>';
echo '<div class="row">';
echo '<div class="label" style="padding:10px">';
echo '<span class="form_required">*</span>';
if ($finish == 0) {
echo get_lang('DownloadFile').' : ';
} else {
echo get_lang('DownloadImg').' : ';
}
echo '</div>';
echo '<div class="formw">';
echo '<div style="float:left;padding:10px" >
<input type="file" name="userFile"><br /><br />
<button type="submit" class="upload" name="submit" value="'.get_lang('Send').'">'.get_lang('SendFile').'</button>
</div>';
echo '<div>'.Display::display_icon('hotpotatoes.jpg', get_lang('HotPotatoes')).'</div>';
echo '</div></div>';
while (list($key, $string) = each($imgparams)) {
$dialogBox .= $string.'; ';
}
}
if ($dialogBox) {
Display::display_normal_message($dialogBox, false);
}
/* UPLOAD SECTION */
echo "<!-- upload -->\n",
"<form action=\"".api_get_self()."?".api_get_cidreq()."\" 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('Send')."\"><br/>\n";*/
//Display::display_icon('hotpotatoes.jpg','',array('align'=> 'right', 'style' => 'position: absolute; padding-top: 30px; margin-left: 500px;'));
echo '<div class="row"><div class="form_header">'.$nameTools.'</div></div>';
echo '<div class="row">';
echo '<div class="label" style="padding:10px">';
echo '<span class="form_required">*</span>';
if ($finish == 0) {
echo get_lang('DownloadFile').' : ';
} else {
echo get_lang('DownloadImg').' : ';
}
echo '</div>';
echo '<div class="formw">';
echo '<div style="float:left;padding:10px" >
<input type="file" name="userFile"><br /><br />
<button type="submit" class="upload" name="submit" value="'.get_lang('Send').'">'.get_lang('SendFile').'</button>
</div>';
echo '<div>'.Display::display_icon('hotpotatoes.jpg', get_lang('HotPotatoes')).'</div>';
echo '</div></div>';
}
// Display the footer.
Display::display_footer();

@ -15,8 +15,8 @@
/**
* This function strips all html-tags found in the input string and outputs a pure text.
* Mostly, the function is to be used before language or encoding detection of the input string.
* @param string $string The input string with html-tags to be converted to plain text.
* @return string The returned plain text as a result.
* @param string $string The input string with html-tags to be converted to plain text.
* @return string The returned plain text as a result.
*/
function api_html_to_text($string) {
// These purifications have been found experimentally, for nice looking output.
@ -37,8 +37,8 @@ function api_html_to_text($string) {
/**
* Detects encoding of html-formatted text.
* @param string $string The input html-formatted text.
* @return string Returns the detected encoding.
* @param string $string The input html-formatted text.
* @return string Returns the detected encoding.
*/
function api_detect_encoding_html($string) {
if (@preg_match('/<head.*(<meta[^>]*content=[^>]*>).*<\/head>/si', $string, $matches)) {
@ -51,8 +51,8 @@ function api_detect_encoding_html($string) {
/**
* Converts the text of a html-document to a given encoding, the meta-tag is changed accordingly.
* @param string $string The input full-html document.
* @param string The new encoding value to be set.
* @param string $string The input full-html document.
* @param string The new encoding value to be set.
*/
function api_set_encoding_html(&$string, $encoding) {
$old_encoding = api_detect_encoding_html($string);
@ -73,13 +73,13 @@ function api_set_encoding_html(&$string, $encoding) {
/**
* Returns the title of a html document.
* @param string $string The contents of the input document.
* @param string $input_encoding The encoding of the input document. If the value is not set, it is detected.
* @param string $$output_encoding The encoding of the retrieved title. If the value is not set, the system encoding is assumend.
* @return string The retrieved title, html-entities and extra-whitespace between the words are cleaned.
* @param string $string The contents of the input document.
* @param string $input_encoding The encoding of the input document. If the value is not set, it is detected.
* @param string $$output_encoding The encoding of the retrieved title. If the value is not set, the system encoding is assumend.
* @return string The retrieved title, html-entities and extra-whitespace between the words are cleaned.
*/
function api_get_title_html(&$string, $output_encoding = null, $input_encoding = null) {
if (@preg_match('/<head.*<title[^>]*>(.*)<\/title>.*<\/head>/si', $string, $matches)) {
if (@preg_match('/<head.+<title[^>]*>(.*)<\/title>/msi', $string, $matches)) {
if (empty($output_encoding)) {
$output_encoding = api_get_system_encoding();
}
@ -101,9 +101,9 @@ define('_PCRE_XML_ENCODING', '/<\?xml.*encoding=[\'"](.*?)[\'"].*\?>/m');
/**
* Detects encoding of xml-formatted text.
* @param string $string The input xml-formatted text.
* @param string $default_encoding This is the default encoding to be returned if there is no way the xml-text's encoding to be detected. If it not spesified, the system encoding is assumed then.
* @return string Returns the detected encoding.
* @param string $string The input xml-formatted text.
* @param string $default_encoding This is the default encoding to be returned if there is no way the xml-text's encoding to be detected. If it not spesified, the system encoding is assumed then.
* @return string Returns the detected encoding.
* @todo The second parameter is to be eliminated. See api_detect_encoding_html().
*/
function api_detect_encoding_xml($string, $default_encoding = null) {
@ -198,11 +198,11 @@ function _api_convert_encoding_xml_callback($matches) {
/**
* Parses CSV data (one line) into an array. This function is not affected by the OS-locale settings.
* @param string $string The input string.
* @param string $delimiter (optional) The field delimiter, one character only. The default delimiter character is comma {,).
* @param string $enclosure (optional) The field enclosure, one character only. The default enclosure character is quote (").
* @param string $escape (optional) The escape character, one character only. The default escape character is backslash (\).
* @return array Returns an array containing the fields read.
* @param string $string The input string.
* @param string $delimiter (optional) The field delimiter, one character only. The default delimiter character is comma {,).
* @param string $enclosure (optional) The field enclosure, one character only. The default enclosure character is quote (").
* @param string $escape (optional) The escape character, one character only. The default escape character is backslash (\).
* @return array Returns an array containing the fields read.
* Note: In order this function to work correctly with UTF-8, limitation for the parameters $delimiter, $enclosure and $escape
* should be kept. These parameters should be single ASCII characters only. Thus the implementation of this function is faster.
* @link http://php.net/manual/en/function.str-getcsv.php (exists as of PHP 5 >= 5.3.0)
@ -261,13 +261,13 @@ function & api_str_getcsv(& $string, $delimiter = ',', $enclosure = '"', $escape
/**
* Reads a line from a file pointer and parses it for CSV fields. This function is not affected by the OS-locale settings.
* @param resource $handle The file pointer, it must be valid and must point to a file successfully opened by fopen().
* @param int $length (optional) Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first).
* If no length is specified, it will keep reading from the stream until it reaches the end of the line.
* @param string $delimiter (optional) The field delimiter, one character only. The default delimiter character is comma {,).
* @param string $enclosure (optional) The field enclosure, one character only. The default enclosure character is quote (").
* @param string $escape (optional) The escape character, one character only. The default escape character is backslash (\).
* @return array Returns an array containing the fields read.
* @param resource $handle The file pointer, it must be valid and must point to a file successfully opened by fopen().
* @param int $length (optional) Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first).
* If no length is specified, it will keep reading from the stream until it reaches the end of the line.
* @param string $delimiter (optional) The field delimiter, one character only. The default delimiter character is comma {,).
* @param string $enclosure (optional) The field enclosure, one character only. The default enclosure character is quote (").
* @param string $escape (optional) The escape character, one character only. The default escape character is backslash (\).
* @return array Returns an array containing the fields read.
* Note: In order this function to work correctly with UTF-8, limitation for the parameters $delimiter, $enclosure and $escape
* should be kept. These parameters should be single ASCII characters only.
* @link http://php.net/manual/en/function.fgetcsv.php
@ -324,8 +324,8 @@ function api_contains_asciisvg($html) {
/**
* Convers a string from camel case into underscore.
* Works correctly with ASCII strings only, implementation for human-language strings is not necessary.
* @param string $string The input string (ASCII)
* @return string The converted result string
* @param string $string The input string (ASCII)
* @return string The converted result string
*/
function api_camel_case_to_underscore($string) {
return strtolower(preg_replace('/([a-z])([A-Z])/', "$1_$2", $string));
@ -334,9 +334,9 @@ function api_camel_case_to_underscore($string) {
/**
* Converts a string with underscores into camel case.
* Works correctly with ASCII strings only, implementation for human-language strings is not necessary.
* @param string $string The input string (ASCII)
* @param bool $capitalise_first_char (optional) If true (default), the function capitalises the first char in the result string.
* @return string The converted result string
* @param string $string The input string (ASCII)
* @param bool $capitalise_first_char (optional) If true (default), the function capitalises the first char in the result string.
* @return string The converted result string
*/
function api_underscore_to_camel_case($string, $capitalise_first_char = true) {
if ($capitalise_first_char) {
@ -354,12 +354,12 @@ function _api_camelize($match) {
* Truncates a string.
*
* @author Brouckaert Olivier
* @param string $text The text to truncate.
* @param integer $length The approximate desired length. The length of the suffix below is to be added to have the total length of the result string.
* @param string $suffix A suffix to be added as a replacement.
* @param string $encoding (optional) The encoding to be used. If it is omitted, the platform character set will be used by default.
* @param boolean $middle If this parameter is true, truncation is done in the middle of the string.
* @return string Truncated string, decorated with the given suffix (replacement).
* @param string $text The text to truncate.
* @param integer $length The approximate desired length. The length of the suffix below is to be added to have the total length of the result string.
* @param string $suffix A suffix to be added as a replacement.
* @param string $encoding (optional) The encoding to be used. If it is omitted, the platform character set will be used by default.
* @param boolean $middle If this parameter is true, truncation is done in the middle of the string.
* @return string Truncated string, decorated with the given suffix (replacement).
*/
function api_trunc_str($text, $length = 30, $suffix = '...', $middle = false, $encoding = null) {
if (empty($encoding)) {
@ -401,11 +401,11 @@ function domesticate($input) {
*
* Actually this function is taken from the PHP BB 1.4 script
* - Goes through the given string, and replaces xxxx://yyyy with an HTML <a> tag linking
* to that URL
* to that URL
* - Goes through the given string, and replaces www.xxxx.yyyy[zzzz] with an HTML <a> tag linking
* to http://www.xxxx.yyyy[/zzzz]
* to http://www.xxxx.yyyy[/zzzz]
* - Goes through the given string, and replaces xxxx@yyyy with an HTML mailto: tag linking
* to that email address
* to that email address
* - Only matches these 2 patterns either after a space, or at the beginning of a line
*
* Notes: the email one might get annoying - it's easy to make it more restrictive, though.. maybe
@ -423,8 +423,8 @@ function make_clickable($string) {
/**
* @desc This function does some parsing on the text that gets inputted. This parsing can be of any kind
* LaTeX notation, Word Censoring, Glossary Terminology (extension will available soon), Musical Notations, ...
* The inspiration for this filter function came from Moodle an phpBB who both use a similar approach
* LaTeX notation, Word Censoring, Glossary Terminology (extension will available soon), Musical Notations, ...
* The inspiration for this filter function came from Moodle an phpBB who both use a similar approach
* @param $input string. some text
* @return $output string. some text that contains the parsed elements.
* @example [tex]\sqrt(2)[/tex]
@ -506,7 +506,7 @@ function _text_parse_tex($textext) {
/**
* This function should not be accessed directly but should be accesse through the text_filter function
* @author Patrick Cool <patrick.cool@UGent.be>
* @author Patrick Cool <patrick.cool@UGent.be>
*/
function _text_parse_glossary($input) {
return $input;
@ -514,7 +514,7 @@ function _text_parse_glossary($input) {
/**
* @desc this function makes a valid link to a different tool
* This function should not be accessed directly but should be accesse through the text_filter function
* This function should not be accessed directly but should be accesse through the text_filter function
* @author Patrick Cool <patrick.cool@UGent.be>
*/
function _text_parse_tool($input) {
@ -557,7 +557,7 @@ function latex_gif_renderer($latex_code) {
* i.e cut('Merry Xmas from Lima',13) = "Merry Xmas fr..."
* @param string the text to "cut"
* @param int count of chars
* @param bool Whether to embed in a <span title="...">...</span>
* @param bool Whether to embed in a <span title="...">...</span>
* @return string
* */
function cut($text, $maxchar, $embed = false) {
@ -565,7 +565,7 @@ function cut($text, $maxchar, $embed = false) {
if ($embed) {
return '<span title="'.$text.'">'.api_substr($text, 0, $maxchar).'...</span>';
}
return api_substr($text, 0, $maxchar).'...' ;
return api_substr($text, 0, $maxchar).'...' ;
}
return $text;
}

Loading…
Cancel
Save